Skip to content

Treat connection_pool_max_wait_ms = 0 as an infinite timeout instead of a busy-spin - #112380

Merged
azat merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-connection-pool-zero-wait-infinite
Aug 2, 2026
Merged

azat merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-connection-pool-zero-wait-infinite

Conversation

@groeneai

@groeneai groeneai commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #112053
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):

Fixes connection_pool_max_wait_ms so that its documented and default value 0 means an infinite timeout. A query that found the connection pool full used to retry in a tight loop, consuming CPU and logging No 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_ms is unsigned and documents 0 as an infinite timeout, but PoolBase::get spells "infinite" as a negative timeout (if (timeout < 0) available.wait(lock);). ConnectionPool::getUnchecked forwarded the setting untranslated, so 0 took the finite branch with a zero-length wait_for and the surrounding while (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 > 0 rather than == 0 because SettingFieldTimespan multiplies its UInt64 by 1000 unchecked, so a huge value already wraps to zero or a negative millisecond count and already reaches the infinite branch; > 0 folds 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 after wait_for returns, so connection_pool_max_wait_ms = 5000 never 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 from system.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 covers 0 and 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's notify_one is 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 and notify_one, so the spin delays the event that would end it.

Scope, checked with git grep: only two classes implement IConnectionPool, and the failover path reaches this same function (ConnectionPoolWithFailover::tryGetEntry -> ConnectionEstablisher::run -> pool->getUnchecked), so no second hunk is needed. Of the other PoolBase subclasses, ThriftHiveMetastoreClientPool only passes a hardcoded positive constant and WasmCompartmentPool only calls get(-1), so both already block. No src/ call site passes 0.

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 at b6a0dba2df19, which added it and only changed ConnectionPool), so the mismatch belongs to the adapter, and widening PoolBase::get would change a shared contract for one caller.

Left for separate work: distributed_connections_pool_size = 0 is 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 -1 callers but now default.

The test is no-parallel because 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

  • Merged into: 26.8.1.648 (included in 26.8 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author
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.
Two review rounds: 2 independent passes (8 findings) and 2 gate passes (engine: codex; 4 findings),
one fix round in between. Every finding was adjudicated against the source rather than accepted or
rejected on assertion.

# Sev Finding Verdict Evidence / action
1 ❌ The abandonment path detached two threads that kept references to observeContention's frame locals, so the writes they make after the timeout are a use-after-return. Reachable in this PR's own CI, since the unit-test bugfix validator builds the merge-base with only the test overlaid and therefore runs the fix-absent arm under ASan+UBSan. AGREE - fixed @ 2d6d81a Found independently by both passes. All shared objects moved into a heap-allocated ContentionState co-owned by both threads through a shared_ptr captured by value; no lambda captures a frame local by reference (acceptance grep: 0 hits). Verified in isolation with a two-arm ASan probe differing only in capture shape: the old shape reports stack-use-after-return, the shipped shape reports nothing. Re-checked that the Poco channel is not part of the lifetime problem: setChannel duplicates its argument, so the logger holds its own reference.
2 ⚠️ WrappedHugeTimeoutBlocksIndefinitely asserted totalMilliseconds() < 0, encoding today's SettingFieldTimespan overflow (a value #106961 changes), so the case would redden through no change of its own. It also could not distinguish > 0 from == 0. AGREE - fixed @ 2d6d81a Renamed to HugeTimeoutFollowsTheAdapterContract; it now reads the effective value at runtime and asserts the branch that value selects, both ways. My prescribed remedy (assert the exact logged number) was wrong and was correctly not implemented: #106961 also changes the number the pool logs, by clamping it, so an exact-string assertion would have failed under the merge and reintroduced the very self-invalidation this finding is about. I verified that PR is real and unmerged (saturatedDuration.h absent on master) and re-derived the value independently: UInt64::max * 1000 wraps to -1000 us, so totalMilliseconds() is -1 today and positive after the merge. Both branches are asserted.
3 ⚠️ EXPECT_EQ(wait_lines, 1u) made the new test flaky on a correct binary, and a fixed 300 ms delay did not guarantee the waiter had reached the wait. AGREE - fixed @ 2d6d81a PoolBase::get's infinite branch is a predicate-less available.wait(lock), so a permitted spurious wakeup logs a second line. Now bounded >= 1 && <= 100, which keeps four orders of magnitude of margin over the measured spinning counts, and observation starts on the pool's own first wait line (30 s bounded) instead of after a delay. The lower bound and an explicit "the waiter never reached the wait" assertion close the hole where the case could pass by asserting nothing.
4 💡 The test's file-level comment quotes a spin count of 453625 that the shipped harness no longer produces. AGREE - noted, not fixed Converged on independently by both passes. The figure was measured against the earlier harness, which the fix round replaced; the current measurements are 441185 in a debug build and 70472 under ASan+UBSan, and the PR body carries those. No assertion reads the number: the live bound is 100, and all three measured values are at least four orders of magnitude above it, so the comment's orders-of-magnitude argument holds under each. Left as a comment-only cleanup rather than spending another build and review round on it.
5 💡 OBSERVATION_TIME's comment does not record that the sleep is no longer load-sensitive now that observation starts on the first wait line. AGREE - noted, not fixed Same class as #4: accurate as written, one clause short of recording why the fixed delay is no longer a race.
6 💡 The PR body said three classes derive from PoolBase; git grep returns four. AGREE - fixed in the body Corrected before publication. The fourth is a test fixture, which also only ever passes -1, so the scope conclusion is unchanged.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Scope checks that came back clean, recorded here because a negative result is also a result: I
enumerated the invariant carriers independently before reading the plan and got the same set, so of
the PoolBase subclasses only this one can receive 0, both IConnectionPool implementations reach
the fixed function, and an independent sweep of the settings documenting 0 as an infinite timeout
returns the same three, one of which is already handled in RWLockImpl and one of which is a
different mechanism tracked separately.

Session id: cron:clickhouse-review-slot-53:20260729-000300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. unit_tests_dbms --gtest_filter='ConnectionPoolWait.*' fails every run without the fix: a one-connection pool contended for 300 ms logs 441185 wait lines in a debug build (70472 under ASan+UBSan), the first being No free connections in pool. Waiting 0 ms., and the connection handover starves. Not timing-dependent: the assertion is a line COUNT against a bound of 100, and observation starts on the pool's own first wait line rather than after a fixed delay.
b Root cause explained? Yes. connection_pool_max_wait_ms is unsigned and documents 0 as an infinite timeout; PoolBase::get encodes "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 enclosing while (true) re-scanned and logged on every iteration. Because the setting cannot hold a negative value, the documented contract was unreachable.
c Fix matches root cause? Yes. The missing translation is added at the adapter that owns the setting (wait_ms > 0 ? wait_ms : -1), so the existing infinite-wait branch is selected. No bound is widened, no test is weakened, no defensive check masks anything. src/Common/PoolBase.h is untouched.
d Test intent preserved / new tests added? New tests added: src/Client/tests/gtest_connection_pool_wait.cpp, 3 cases (zero blocks once; a positive timeout still takes the finite branch; a wrapped-huge value still blocks). No existing test is modified or weakened; PoolBase*/ConnectionPool* stay green (25/25).
e Both directions demonstrated? Yes, on readelf-verified Build IDs. With the fix (88531a03): PASS 3/3, 1 wait line. Mutation reverting only the translation (60ee181a): FAIL, 441185 wait lines against the bound of 100, the two control cases still green. Restore rebuilt bit-identically to 88531a03 and passes. Also run under ASan+UBSan, which is the configuration the unit-test bugfix validator uses: fix absent (4297e0e7) FAILs as designed with 0 sanitizer reports, fix present (0338be2b) PASSes 3/3 with 0 reports.
f Fix is general across code paths? Yes. Only two classes implement IConnectionPool, and the failover path reaches this same function (ConnectionPoolWithFailover::tryGetEntry -> ConnectionEstablisher::run -> pool->getUnchecked), so one hunk covers both. ConnectionPool::get(timeouts, settings) funnels through getUnchecked, and get(timeouts) already passed -1. The other two PoolBase subclasses are provably not carriers: ThriftHiveMetastoreClientPool only ever passes a hardcoded positive constant, WasmCompartmentPool only ever calls get(-1).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, over the value domain of this setting, which is what applies here. 0 -> infinite (fixed); positive -> unchanged finite branch (pinned by a test); wrapped-negative from the SettingFieldTimespan unsigned-multiply overflow (18446744073709551615 -> -1) -> infinite, the same behaviour it already had, pinned by a third test. This is why the predicate is > 0 and not == 0: a == 0 test would leave a second, undocumented route into the infinite branch.
h Backward compatible? (maintainer-approved exception only) No setting VALUE changes, so no gate is possible or needed; SettingsChangesHistory.cpp records the behaviour change with previous_value == new_value (the established idiom, and a provable no-op for compatibility). A user cannot restore the old spin, which is intended: the old behaviour was the bug and never matched the documentation. Stated plainly in the body rather than implying an escape hatch exists.
i Invariants and contracts preserved? Yes. PoolBase::get's documented contract ("with timeout < 0, the timeout is infinite") is now honoured rather than redefined - the callee is unchanged and the caller is the one brought into line. No lock is taken, released or reordered, and no new failure path is introduced: available.wait(lock) is the same branch the other PoolBase callers already use. The retry loop's pre-existing lack of a deadline exit is unchanged and disclosed.

Session id: cron:clickhouse-impl-slot-46:20260728-184300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @Algunenano — could you review this? connection_pool_max_wait_ms is unsigned and documents 0 as an infinite timeout, but PoolBase::get encodes infinite as a negative timeout, so ConnectionPool::getUnchecked forwarding the setting untranslated made the default 0 select a zero-length wait and spin the retry loop; the fix adds the missing translation in that adapter, leaving PoolBase.h untouched.

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

clickhouse-gh Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1cc1017]

Summary: ✅


AI Review

Summary

This PR fixes the documented connection_pool_max_wait_ms = 0 contract by translating 0 to the infinite-wait sentinel and adds a focused stateless regression test plus log throttling for the finite-wait branch. I found one operational regression in the new default path: it now routes distributed queries onto PoolBase's non-interruptible infinite wait, which can leave waits parked until some other query returns a connection and becomes permanent when distributed_connections_pool_size = 0.

Findings

⚠️ Majors

  • [src/Client/ConnectionPool.cpp:160] Translating 0 to -1 sends the documented/default path into PoolBase's bare available.wait(lock) branch, but that branch has no cancellation hook and the only wakeup is PoolEntryHelper::~PoolEntryHelper's notify_one. A killed query waiting on a full pool therefore cannot unwind until another query releases a connection, and the currently accepted distributed_connections_pool_size = 0 setting now has no possible notifier at all, so it parks forever. This needs either validation that rejects zero-sized distributed pools in the same change, or a bounded wait/check-cancellation loop until PoolBase::get is made interruptible.
Final Verdict

⚠️ Changes needed before merge: the 0-timeout fix currently broadens PoolBase's uncancellable infinite wait to the default distributed-query path and turns accepted zero-sized distributed pools into permanently parked waits.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 29, 2026
Comment thread src/Core/Settings.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2d6d81a

CI is complete: 174 check runs, 147 success, 24 skipped, 3 failure, Finish Workflow green.
Every failure below has an owner. All 8 Unit tests (*) runs are green, including
Bugfix validation (unit tests), which is the job that exercises the gtest this PR adds.

None of these is PR-caused. This change touches src/Client/ConnectionPool.cpp, its gtest,
src/Core/Settings.cpp and src/Core/SettingsChangesHistory.cpp; the failing tests are
s3_queue integration, a stateless MergeTree query-limit test and a distributed-plan test,
with no file overlap, and connection_pool_max_wait_ms appears in none of them.

Check / test Reason Owner / fixing PR
Integration tests (arm_binary, distributed plan, 2/4) / test_storage_s3_queue/test_system_stop.py::test_stopped_table_releases_hash_ring_slot server abort, not a network fault: signal 6 with ObjectStorageQueueSource::FileIterator::next and verbose_abort frames in the log; the Code: 210 Connection reset by peer is the client observing the dead server #108977 (ours, open)
Integration tests (arm_binary, distributed plan, 2/4) / test_storage_s3_queue/test_system_stop.py::test_refresh_survives_unready_dependencies collateral of the same abort: the server is already gone, so this test fails on its own first DROP TABLE IF EXISTS during setup #108977 (ours, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit fails 3/3 under parallel replicas on coverage builds #112385 (ours, open)
Stateless tests (arm_binary, parallel) / 04367_distributed_plan_merge_scatter_multishard query hang in local execution of distributed plans, killed on timeout; 138/138 reruns with the same settings passed, so not settings randomization #111762 (external, open)

Session id: cron:clickhouse-maint-slot-19:20260729-124000

@PedroTadim PedroTadim self-assigned this Jul 30, 2026
Comment thread src/Client/ConnectionPool.cpp Resolved
Comment thread src/Core/SettingsChangesHistory.cpp Outdated
{"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."},

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.

Interesting idea to use history as changelog, good

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.

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.

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.

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>

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.

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

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.

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

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.

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.

62d1014

Comment thread src/Client/ConnectionPool.cpp Resolved
@azat azat self-assigned this Jul 31, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@azat I leave it to you, I have too many PRs too review

@PedroTadim PedroTadim removed their assignment Jul 31, 2026
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5f21392

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

CI is fully finished on this head: 174 check runs, 156 success, 18 skipped, 0 failures,
Finish Workflow green. CIDB agrees over 321703 rows for this commit: 0 FAIL/ERROR.

Check / test Reason Owner / fixing PR
(none) — 174 checks completed, 0 failures

All four failures from the previous head (2d6d81a1a10d) are gone on this one, including
both test_storage_s3_queue/test_system_stop.py cases and 01666_merge_tree_max_query_limit.

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

@azat

azat commented Aug 1, 2026

Copy link
Copy Markdown
Member

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

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.

Why do we need 0, 1 and 2, the test is already very slow likely, leave only 0 and 1

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.

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

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.

are you sure we need retries here? the test can be very slow

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.

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.
@groeneai
groeneai force-pushed the fix-connection-pool-zero-wait-infinite branch from 5f21392 to 1cc1017 Compare August 1, 2026 17:44
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

Squashed to one commit, 1cc1017.

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 notify_one from the pool release path left the log counts untouched).

/// 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);

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.

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.

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

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

Full report · Diff report

@azat
azat enabled auto-merge August 2, 2026 21:38
@azat
azat added this pull request to the merge queue Aug 2, 2026
Merged via the queue into ClickHouse:master with commit 3885f7b Aug 2, 2026
179 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 2, 2026
Bartok9 added a commit to Bartok9/ClickHouse that referenced this pull request Aug 5, 2026
Runtime maps 0 to -1 in ConnectionPool::getUnchecked (ClickHouse#112380).
Keep http_* zero clarifications only.

Signed-off-by: Bartok9 <[email protected]>
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore labels Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

connection_pool_max_wait_ms default is 0, (non negative), but Common/PoolBase.h check expect it to be <0

7 participants