Repository navigation
Treat connection_pool_max_wait_ms = 0 as an infinite timeout instead of a busy-spin - #112380
Conversation
Internal second-model review - adjudication log (click to expand)Pre-publication review by an independent model, plus my own cold review of the resulting code.
Severity: ❌ blocker / Scope checks that came back clean, recorded here because a negative result is also a result: I Session id: cron:clickhouse-review-slot-53:20260729-000300 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-46:20260728-184300 |
|
cc @azat @Algunenano — could you review this? |
|
Workflow [PR], commit [1cc1017] Summary: ✅
AI ReviewSummaryThis PR fixes the documented Findings
Final Verdict
|
CI finish ledger - 2d6d81aCI is complete: 174 check runs, 147 success, 24 skipped, 3 failure, None of these is PR-caused. This change touches
Session id: cron:clickhouse-maint-slot-19:20260729-124000 |
| {"input_format_read_datetime_number_as_raw_value", true, false, "From 26.8, an unquoted number for a `DateTime`/`DateTime64` column in the `JSON` and `Values`/`Quoted` paths (and in `JSONExtract` and typed `JSON`) is a Unix timestamp in seconds, consistent with the `Values` format, `CAST` and `toDateTime64`. Set this to `true` (or `SET compatibility = '26.7'`) to restore the pre-26.8 behavior, where a bare unquoted integer fed to a `DateTime64` column was read as the raw scaled value (ticks). The tab-separated, CSV and other escaped/whole-text formats are not governed by this setting."}, | ||
| {"query_plan_short_circuit_constant_false_join", false, true, "New setting to short-circuit a JOIN with a constant-false ON condition so the non-contributing side is not read. previous_value=false so `compatibility` with versions before 26.8 restores the pre-existing behavior (no short-circuit)."}, | ||
| {"distributed_cache_min_inflight_bytes_to_discard_connection_on_seek", 0, 4 * 1024 * 1024, "New setting to drop and reopen a distributed cache connection on a seek when too many in-flight bytes would otherwise be discarded. Defaults to 4 MiB; 0 restores the previous behavior (always reuse the connection via the read range id)."}, | ||
| {"connection_pool_max_wait_ms", 0, 0, "The value is unchanged, but 0 now means the documented infinite timeout: a query waiting for a full connection pool blocks until a connection is returned instead of retrying in a loop with a zero-length wait."}, |
There was a problem hiding this comment.
Interesting idea to use history as changelog, good
There was a problem hiding this comment.
Actually this causes conflicts with private let's remove this, it is OK, it is not that major, I doubt that anyone uses this setting.
There was a problem hiding this comment.
Removed in 1cc1017.
One consequence worth knowing: a SettingsChangesHistory entry sitting in an unreleased block disappears on a backport anyway, because that block does not exist on the release branch, so the entry was only ever going to cover master. Your call either way.
| @@ -0,0 +1,295 @@ | |||
| #include <gtest/gtest.h> | |||
There was a problem hiding this comment.
This test is too complex, unlikely it will be ever read by someone, please try to cover with statless/integration test, if not, remove the test
There was a problem hiding this comment.
Smth like
for i in 1 2; do
clickhouse-client --query "
SELECT count() FROM remote('127.0.0.1:9000', numbers(3)) WHERE sleepEachRow(2)
SETTINGS prefer_localhost_replica = 0, distributed_connections_pool_size = 1,
connection_pool_max_wait_ms = 0,
function_sleep_max_microseconds_per_block = 60000000" &
done
There was a problem hiding this comment.
Replaced with a stateless test, close to your shape: two concurrent remote() queries over a pool of size 1, reading the outcome from system.text_log. The gtest is deleted.
Two cells. The first uses connection_pool_max_wait_ms = 0 and asserts the waiter took the indefinite branch; reverting the adapter translation reddens it. The second uses 1, which keeps the finite branch, and bounds the emitted line count so the limiter below is covered too; removing the limiter reddens that cell alone.
It is no-parallel. I would rather not have tagged it, but the pool is keyed on host, port, credentials and pool size, and a test database makes none of those unique, so concurrent copies queue behind one connection: with 6 copies the runs went from 7s to 37s, which would cross the client bound under the repeated runs of the flaky check.
|
@azat I leave it to you, I have too many PRs too review |
CI finish ledger — 5f21392Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task CI is fully finished on this head: 174 check runs, 156 success, 18 skipped, 0 failures,
All four failures from the previous head ( Session id: cron:our-pr-ci-monitor:20260801-130000 |
|
Also squash everything, we don't need the intermediate history |
| echo "the queries never ran at the same time, so the pool was never full" | ||
| } | ||
|
|
||
| contend 0 1 2 |
There was a problem hiding this comment.
Why do we need 0, 1 and 2, the test is already very slow likely, leave only 0 and 1
There was a problem hiding this comment.
There were only two, 0 and 1. contend 0 1 2 read as three values but the arguments were wait_ms=0 plus the two query id suffixes, which is my fault for writing it that way. It now reads contend 0 zero and contend 1 finite.
The slowness was real though: 27 s before, 7 s now.
| # only while the holder is still running. A waiter that takes longer to start than the holder runs | ||
| # for never waits at all, and reports the same counts as a wait that was lost, so an attempt that | ||
| # fails to overlap is retried instead of asserted on. | ||
| for _ in {1..5}; do |
There was a problem hiding this comment.
are you sure we need retries here? the test can be very slow
There was a problem hiding this comment.
Gone. They were covering a real race, so I removed its cause instead of the loop: the holder used to free the connection on its own after a fixed sleep, and a waiter that started after that found the pool free and never waited, which is what had to be retried.
The holder is now killed once the waiter is actually seen contending, so the pool is full whenever the waiter reaches it and there is nothing to repeat. That is also where the time went: 27 s to 7 s.
`connection_pool_max_wait_ms` is unsigned and documents 0 as an infinite timeout, but `PoolBase::get` spells infinite as a negative timeout. `ConnectionPool::getUnchecked` forwarded the setting untranslated, so 0 took the finite branch with a zero length `wait_for` and the surrounding loop re-scanned and logged on every iteration. Since a negative value cannot be written, the documented contract was unreachable. The spin also starves the release path, which needs the same mutex to return the connection and notify, so it delays the event that would end it. Also limits the frequency of the finite-wait log line, which is emitted once per timeout per waiter. Closes ClickHouse#112053.
5f21392 to
1cc1017
Compare
|
Squashed to one commit, It was safe to do here even though the branch carried your master merge: the merge's second parent is already the branch's merge base with master, so basing the single commit on it leaves the tree and the patch id byte identical and master still reads as merged. Verified all three before pushing. The other three asks are answered in their threads. The test also picked up two assertions while I was in there, both from mutations that used to pass: it now bounds the indefinite-wait line count on both sides (replacing the blocking wait with a 1 ms one reported that line 2083 times and satisfied the old check), and it requires the waiting query itself to succeed (dropping |
| /// negative value cannot be written. `PoolBase::get` spells "infinite" as a negative timeout, | ||
| /// hence the translation: without it 0 selects a zero-length wait and the retry loop spins. | ||
| const Int64 wait_ms = settings[Setting::connection_pool_max_wait_ms].totalMilliseconds(); | ||
| return Base::get(wait_ms > 0 ? wait_ms : -1); |
There was a problem hiding this comment.
wait_ms > 0 ? wait_ms : -1 moves the documented/default connection_pool_max_wait_ms = 0 path onto PoolBase's naked available.wait(lock) branch. That wait has no cancellation predicate or stop token, and the only wakeup in PoolBase is PoolEntryHelper::~PoolEntryHelper's available.notify_one() in src/Common/PoolBase.h.
So a query killed while the pool is full still cannot unwind until some other query returns a connection; with the currently accepted distributed_connections_pool_size = 0 setting there is not even a possible notifier, so this change turns that configuration into a permanent park instead of a retrying misconfiguration. Because 0 is both the documented meaning and the default, I think this needs handling in the same PR rather than a follow-up: either reject distributed_connections_pool_size = 0 here, or keep 0 on a bounded wait/check-cancellation loop until PoolBase::get itself becomes interruptible.
There was a problem hiding this comment.
Both underlying facts are right, but the causal claim is not: the finite branch is equally uninterruptible, so routing 0 to the infinite branch does not regress cancellation. Measured on this branch (1cc1017), KILL QUERY ... ASYNC against a query parked on a full pool with distributed_connections_pool_size = 0:
connection_pool_max_wait_ms |
branch taken | is_cancelled after KILL |
client unwound |
|---|---|---|---|
1 (what 0 did before this PR) |
finite wait_for |
1 | no, still parked at the 45s bound |
| 0 (this PR) | infinite wait |
1 | no, still parked at the 45s bound |
The finite branch records is_cancelled = 1 and still never returns, because nothing in PoolBase::get reads it: grepping the whole while (true) body in src/Common/PoolBase.h:123-166 for isCancelled|checkTimeLimit|stop_token|ProcessListElement gives 0 matches on either arm. The pre-PR loop was a re-scan loop, not a cancellation-observing one, so "cancellation observed on each turn of the loop" does not hold.
Server side, counting PoolBase frames in system.stack_trace on a freshly started server: 0 before the probe, 1 while the finite-arm query is parked, and still 1 after its client has exited and the KILL has landed, with the query still listed in system.processes. So the old behaviour leaks the same unbounded server-side wait.
Same result in the realistic shape (distributed_connections_pool_size = 1, a holder occupying the connection, killing the waiter): the waiter unwound 57.9s after the KILL on both arms, i.e. when the holder finished, not when the kill landed.
distributed_connections_pool_size = 0 is accepted (src/Core/Settings.cpp:485, UInt64 with no minimum) and does hang, but identically on both arms: with max_items == 0 the allocate branch is unreachable, so the loop can only wait. That is a real pre-existing defect, and this PR neither introduces nor worsens it.
For scope, Base::get(-1) is already a production path in this same class (ConnectionPool.h:98, reached by the single-argument ConnectionPool::get(timeouts)), and it predates the src/ layout: git log -S "Base::get(-1)" on that file bottoms out at 06446b4 (2020-04-03). UserDefinedWebAssembly.cpp:431 uses it too. So the infinite branch is not novel here.
On the two suggested remedies: keeping 0 on a bounded wait is the busy-spin this PR exists to remove, and it buys no cancellation for the reason above. Making PoolBase::get interruptible changes a contract shared by four pool types and is worth doing separately. Rejecting distributed_connections_pool_size = 0 is a backward-incompatible validation change on a long-accepted setting, and it would need a SettingsChangesHistory entry, which was just removed from this PR at the reviewer's request.
So I am leaving the scope as is. What this PR does change for the default is the retry loop itself: 0 previously took the finite branch with a zero length wait_for, so it re-scanned and logged on every iteration, and it reacquires the same mutex that PoolEntryHelper::~PoolEntryHelper needs to return the connection and notify, so it delays the event that would end the wait. It now parks once and logs once. For the order of magnitude, a mutation arm that replaces the blocking wait with a 1 ms one emitted that line 2083 times where the blocking version emits exactly 1.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 12/12 (100.00%) · Uncovered code |
Runtime maps 0 to -1 in ConnectionPool::getUnchecked (ClickHouse#112380). Keep http_* zero clarifications only. Signed-off-by: Bartok9 <[email protected]>
Closes: #112053
Related: #106961
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes
connection_pool_max_wait_msso that its documented and default value0means an infinite timeout. A query that found the connection pool full used to retry in a tight loop, consuming CPU and loggingNo free connections in pool. Waiting 0 ms.on every iteration. It now waits until a connection is returned to the pool. Closes #112053.Description
connection_pool_max_wait_msis unsigned and documents0as an infinite timeout, butPoolBase::getspells "infinite" as a negative timeout (if (timeout < 0) available.wait(lock);).ConnectionPool::getUncheckedforwarded the setting untranslated, so0took the finite branch with a zero-lengthwait_forand the surroundingwhile (true)re-scanned and logged once per iteration. Since a negative value cannot be written, the documented contract was unreachable.The fix is that missing translation in the adapter,
wait_ms > 0 ? wait_ms : -1. The predicate is> 0rather than== 0becauseSettingFieldTimespanmultiplies itsUInt64by 1000 unchecked, so a huge value already wraps to zero or a negative millisecond count and already reaches the infinite branch;> 0folds both onto the one sentinel without changing what those values do today. #112757 rejects that whole class at the setting instead.This is not a behaviour regression. The retry loop has no exit other than success: no
break, no deadline re-check and no throw afterwait_forreturns, soconnection_pool_max_wait_ms = 5000never expired either, it retried forever in 5 s steps.Also limits the frequency of the finite-wait log line, which is emitted once per timeout per waiter: 2807 lines against 1 on the same workload at
connection_pool_max_wait_ms = 1.Validated by a stateless test: concurrent
remote()queries over a pool of size 1, reading the outcome fromsystem.text_log. The holder is killed once the waiter is seen contending, so the pool is always full when the waiter reaches it. One cell covers0and reddens when the translation is reverted; a second covers a positive timeout and reddens when the limiter is removed. It also reddens when the blocking wait is replaced by a short one, and when the pool'snotify_oneis dropped. Green on repeats, 7 s.Scope check, layer choice, and adjacent concerns
The spin is worse than CPU burn, which is why the server looked stuck: the spinning thread holds the pool mutex almost continuously and starves
PoolEntryHelper::~PoolEntryHelper, which needs that mutex to release the connection andnotify_one, so the spin delays the event that would end it.Scope, checked with
git grep: only two classes implementIConnectionPool, and the failover path reaches this same function (ConnectionPoolWithFailover::tryGetEntry->ConnectionEstablisher::run->pool->getUnchecked), so no second hunk is needed. Of the otherPoolBasesubclasses,ThriftHiveMetastoreClientPoolonly passes a hardcoded positive constant andWasmCompartmentPoolonly callsget(-1), so both already block. Nosrc/call site passes0.On the issue I said I would put this guard in
src/Common/PoolBase.h. I moved it to the adapter after checking provenance: the negative-sentinel contract and its comment predate the setting (both present atb6a0dba2df19, which added it and only changedConnectionPool), so the mismatch belongs to the adapter, and wideningPoolBase::getwould change a shared contract for one caller.Left for separate work:
distributed_connections_pool_size = 0is accepted and creates a pool that can never hand out a connection, so the wait becomes permanent (it previously spun forever instead);available.wait(lock)has no predicate or stop token, and on the hedged path a block parks the carrier thread, both already true of the-1callers but now default.The test is
no-parallelbecause the pool is keyed on host, port, credentials and pool size, none of which a test database makes unique, so concurrent copies queue behind one connection (measured 7 s alone, 16 s with 6 copies).Version info
26.8.1.648(included in26.8and later)