Skip to content

Choose the number of streams of a query from the fair share of CPU slots - #125085

Merged
alexey-milovidov merged 4 commits into
masterfrom
concurrency-control-streams
Oct 14, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
concurrency-control-streams

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

The concurrent QPS of ClickHouse in ClickBench is worse than Firebolt's, even on machines where single-query times are the same. On c8g.metal-48xl, the sum of hot query times is 2.64 s vs 2.66 s, but QPS is 32.5 vs 42.3. On c7a.metal-48xl it is 28.5 vs 33.5, and on c6a.metal 15.8 vs 24.1.
Related: https://benchmark.clickhouse.com/#system=-&type=-&machine=-6t|ca2|6ax|g4e|6ale|3al&cluster_size=-&opensource=-&hardware=+c&tuned=+n&storage=-&metric=qps&queries=-

The reason: a query is always planned with one stream per CPU core. The concurrency control limits how many threads run, but not how many streams the query is planned with. With 10 concurrent queries, every query still builds a pipeline for all cores. That means one partial aggregation state per stream, the cost of merging all of them, more memory, and oversubscription. With the ClickBench queries run sequentially, max_threads = 96 costs 1.58x the CPU time of max_threads = 8 for the same work. Large GROUP BY queries cost 1.3-1.6x more, and ORDER BY ... LIMIT queries 3-6x more.

This PR extends the concurrency control to the choice of the number of streams. When max_threads is auto, it is lowered to the fair share of CPU slots of ConcurrencyControl: the slot limit divided evenly between the live allocations and the new query (at least one). A query on an idle server is planned with all cores, as before. An explicitly set max_threads is respected. The new setting use_concurrency_control_for_max_threads (enabled by default) disables it.

ConcurrencyControl now counts its live allocations and has a getFairShare method. The new helper getEffectiveMaxThreads(settings) combines the existing memory-based limit (max_threads_min_free_memory_per_thread) with the fair share. It replaces the direct calls to getMaxThreadsForAvailableMemory for max_threads, in the planner, the old interpreters, BuildQueryPipelineSettings and IStorage.

Local check on a 96-core Neoverse-V2 machine, 100M-row hits, with 10 clients cycling through the ClickBench queries as the ClickBench QPS test does. The machine was shared and heavily loaded, so throughput is too noisy to quote. Per-query metrics from system.query_log:

  • CPU time per query: the old behaviour uses 1.18x as much (mean over the 43 queries);
  • p99 memory usage: 7.67 GiB vs 9.33 GiB;
  • threads per query: 25 vs 38.

This needs confirmation by the ClickBench QPS test on dedicated machines.

The fair share depends on the other queries running on the server, so a functional test cannot assert stream counts deterministically under parallel CI. The counting is covered by a gtest (ConcurrencyControl.FairShare).

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

When max_threads is not set explicitly, a query is planned with the fair share of CPU slots of the concurrency control instead of all CPU cores. This increases the throughput and lowers the memory usage under many concurrent queries, while a query on an idle server still uses all cores. It can be disabled with the setting use_concurrency_control_for_max_threads.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.2340-master (included in 26.10 and later)

The number of streams (and threads) a query is planned with was always the number
of CPU cores. The concurrency control limits how many threads run, but not how many
streams the query is planned with. With many concurrent queries, every query still
built a pipeline for all cores: one partial aggregation state per stream, merging
all of them, more memory, and oversubscription of the threads that it was granted.
This is why the concurrent QPS of ClickBench is worse than of systems that share
one pool of workers between queries.

Now, when `max_threads` is `auto`, it is lowered to the fair share of CPU slots of
`ConcurrencyControl`: the slot limit divided evenly between the live allocations
and the new query. A query on an idle server uses all cores as before. It can be
disabled with the new setting `use_concurrency_control_for_max_threads`.

The helper `getEffectiveMaxThreads` replaces the direct calls to
`getMaxThreadsForAvailableMemory` for `max_threads`, so the limit applies everywhere
the planner and the pipeline builder pick the parallelism.

Related: https://benchmark.clickhouse.com/#system=-&type=-&machine=-6t|ca2|6ax|g4e|6ale|3al&cluster_size=-&opensource=-&hardware=+c&tuned=+n&storage=-&metric=qps&queries=-

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... label Oct 10, 2026
# Conflicts:
#	src/Planner/Planner.cpp
@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a185638]

Summary: ✅


AI Review

Summary

This PR lowers auto max_threads to the fair share of ConcurrencyControl allocations so queries build fewer streams under contention. The direction makes sense, but I do not think it is merge-ready yet: explicitly pinned auto(...) values are still rewritten under load, and parallel-hash joins still size themselves from raw max_threads, which leaves one of the heaviest per-thread data structures outside the new budget.

Findings
  • ⚠️ Majors
    • [src/Interpreters/getEffectiveMaxThreads.cpp:25] The new fair-share cap keys only on is_auto. That flag is also true for an explicitly set auto(...) value, so SET max_threads = auto(32) still gets silently lowered under load even though the PR text says explicit max_threads values are respected.
      Suggested fix: also require !settings[Setting::max_threads].isChanged() (or equivalent) before applying the fair-share cap, and add a focused regression test for explicitly pinned auto(...) values.
    • [src/Planner/PlannerJoins.cpp:1386, src/Interpreters/ExpressionAnalyzer.cpp:1058, src/Interpreters/ConcurrentHashJoin.cpp:200] Parallel-hash joins still size ConcurrentHashJoin / concurrent SpillingHashJoin from raw max_threads, not from the new effective thread budget. Under contention, the rest of the plan is lowered to the fair share, but the join still allocates one shard/hash table per core, so a major part of the memory and merge overhead this PR is targeting remains.
      Suggested fix: thread getEffectiveMaxThreads through JoinAlgorithmParams and the old-analyzer join constructors too, so join slot counts follow the same effective budget as aggregation, read resizes, UNION, and window steps.
Tests
  • ⚠️ This PR is labeled Performance Improvement, but the only automated performance signal visible on the PR is the cloud report with no_change on single-query workloads. Please add or link a focused before/after measurement of the claimed concurrent-QPS improvement (for example ClickBench QPS, or a smaller reproducer that varies concurrent clients while keeping the workload stable).
  • ⚠️ Please add a targeted regression test for explicitly set max_threads = auto(...) / auto, because that user-visible contract changed here and is easy to regress again.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Respect explicitly changed max_threads values even when they are in auto(...) form.
    • Thread the effective parallelism budget through the parallel-hash join builders in both the planner and the old analyzer.
    • Provide a before/after measurement that validates the claimed concurrency-throughput win.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: b49f8fca-e351-4d07-b45e-bfe05732ccdb
  • MIRAI run: 3c836b55-1680-4a3a-8cc4-05c4c8d2fed6
  • PR check IDs:
    • clickbench_1019869_1791797026
    • clickbench_1019875_1791797026
    • clickbench_1019881_1791797026
    • tpch_adapted_1_official_1019892_1791797026
    • tpch_adapted_1_official_1019904_1791797026
    • tpch_adapted_1_official_1019939_1791797026

alexey-milovidov and others added 2 commits October 12, 2026 07:16
…share of CPU slots

The test checks the number of sinks equal to `max_insert_threads`, which is capped
by `max_threads`. With `max_threads` being `auto`, it is now lowered to the fair
share of CPU slots, which depends on the concurrently running tests (4 instead of 8
in the Fast test). Disable `use_concurrency_control_for_max_threads` in the test.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125085&sha=767bc99f807d398d54b3562195dc939b730039be&name_0=PR&name_1=Fast%20test
#125085

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a185638b8 with master 371b23a4b (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

16 object files changed (+29.14 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/getEffectiveMaxThreads.cpp.o new 30.67 KiB +30.67 KiB

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

20 translation units recompiled, 149 s compile time in total, 19 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +5.8 s (+4%) in total before that adjustment.

Job report

@alexey-milovidov alexey-milovidov added the memory When memory usage is higher than expected label Oct 12, 2026

@alexey-milovidov alexey-milovidov left a comment •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

All LGTM.

This option should improve the performance and memory usage in general. However, the number of streams can't "grow back" for long-running queries, so there could be some degradation in rare cases.

@alexey-milovidov alexey-milovidov self-assigned this Oct 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 13, 2026
Merged via the queue into master with commit 77e12e3 Oct 14, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the concurrency-control-streams branch October 14, 2026 00:20
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
robinld pushed a commit to robinld/ClickHouse that referenced this pull request Oct 14, 2026
Since ClickHouse#125085 an auto `max_threads` is lowered to the fair share of CPU
slots (`getEffectiveMaxThreads`). Under the test runner's concurrent load
the two `--max_threads=0` EXPLAIN PIPELINE checks of `algorithm: Thread`
can get a single stream; `ReadFromMergeTree` then reads in order
(`readInOrder` instead of `readFromPool`) and the line disappears. The
failing arm_binary job's server log shows `fair share of CPU slots 1
(32 requested)` for exactly the query that lost its line.

Pin `use_concurrency_control_for_max_threads = 0` on those two
invocations, as ClickHouse#125715 does for `02149_read_in_order_fixed_prefix`.
The other invocations do not depend on the number of streams.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai pushed a commit to groeneai/ClickHouse that referenced this pull request Oct 15, 2026
Since ClickHouse#125085, `max_threads = auto` is
lowered to the fair share of CPU slots of `ConcurrencyControl` when other queries are
running. Under the concurrent load of the test runner the read in order can be planned
with a single stream, so both parts are read by one `readInOrder` call and
`EXPLAIN PIPELINE` shows `ReverseTransform × 2` instead of two separate chains.

Disable `use_concurrency_control_for_max_threads` in the test, as its output depends on
the number of streams.

Failed in the merge queue of ClickHouse#118315:
https://github.com/ClickHouse/ClickHouse/actions/runs/38491344800/job/115617405459

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit to JayPokale/ClickHouse that referenced this pull request Oct 19, 2026
…trol

The two `all > 1` checks need the `LIMIT 1` read to log more than one
non-final file segment of `b.bin`. With the prefetched pool disabled (as in
CI), each stream of `MergeTreeReadPool` starts at a different mark range, so
the number of logged segments is bounded by the streams and threads that
start reading before the limit closes the query.

Since ClickHouse#125085 an auto `max_threads` is lowered to the fair share of CPU
slots. In the failing job (PR ClickHouse#109455, Stateless tests (arm_asan_ubsan,
azure, sequential, 1/2)) background pipelines held the slots and the read
got `Lower number of threads for query to the fair share of CPU slots 1
(8 requested)` and `Reading approx. 1000000 rows with 1 streams`, so it
read one granule, one segment, and printed FAIL twice.

Disable `use_concurrency_control` for the read: `getEffectiveMaxThreads`
then keeps the auto value and the executor spawns threads without slots.

Validated with the CI test config and a MinIO-backed `s3_disk`: with
`concurrent_threads_soft_limit_num = 1` the unfixed test fails 5/5 with
CI's diff and log lines, the fixed one passes 20/20 there (7-8 streams)
and 50/50 on the default config.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... memory When memory usage is higher than expected pr-performance Pull request with some performance improvements 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.

2 participants