Skip to content

Choose the effective max_threads once per query - #125946

Merged
serxa merged 11 commits into
masterfrom
effective-max-threads-per-query
Nov 14, 2026
Merged

serxa merged 11 commits into
masterfrom
effective-max-threads-per-query

Conversation

@serxa

@serxa serxa commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

When max_threads is auto, getEffectiveMaxThreads lowers it under memory pressure (max_threads_min_free_memory_per_thread) and to the fair share of CPU slots of the concurrency control (use_concurrency_control_for_max_threads). Both inputs were read live at each of the 18 call sites: read streams of every table expression, aggregation and merge threads, window functions, unions, inserts, IStorage::read and every BuildQueryPipelineSettings. A query that started or finished in another session between two of them changed the result, so different parts of one query could be planned with different numbers of streams. A set built while the query already ran counted the query's own CPU allocation in the fair share. Every call also took the global mutex of the concurrency control.

Now the free memory and the fair share are taken once per query, on first use, into a QueryMaxThreadsSnapshot. makeQueryContext creates the snapshot, and every context copied from the query context shares it. getEffectiveMaxThreads takes a Context and combines the snapshot with that context's settings. A subquery with its own max_threads still gets its own value, but from the same snapshot. The parts of a query that run under a separate query context share the snapshot of the outer query: the body of a DEFINER or NONE view (including a materialized view planned while its parent INSERT runs), the nested INSERT of an Alias table, the scan of system.user_query_log, the read rounds of a streaming MergeTree query and the direct write of a large block from a Buffer table to its destination. max_insert_threads_min_free_memory_per_thread reads the same snapshot. A context that is not a query context has no snapshot and reads the current state, as before.

Related: #125447
Related: #125085

Changelog category (leave one):

  • Improvement

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

The number of threads of a query with an automatic max_threads is chosen once per query: all its parts (subqueries, sets, read streams of joined tables, pipeline resizes) are planned with the same free memory (max_threads_min_free_memory_per_thread) and the same fair share of CPU slots (use_concurrency_control_for_max_threads).


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

Version info

  • Merged into: 26.11.1.2325-master (included in 26.11 and later)

`getEffectiveMaxThreads` read the free memory and the fair share of CPU slots
live at each of its 18 call sites, so different parts of one query could be
planned with different numbers of streams. Take both values once per query
into a `QueryMaxThreadsSnapshot`, created by `makeQueryContext` and shared by
every context copied from the query context, and compute the effective value
from the snapshot and the settings of the calling context.

Related: #125447

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

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3cc671b]

Summary: ✅


AI Review

Summary

Reviewed #125946 at 3cc671be5ded2a04def02fec0d273dcee402b5bc, including all prior discussion. The change samples free memory and CPU fair share once per query, shares that snapshot with nested execution contexts, and applies each context's own settings. No remaining actionable findings: the prior snapshot-propagation, behavioral-coverage, and single-thread initialization findings are addressed in the current code.

Missing context / blind spots
  • ⚠️ Runtime validation is incomplete: no local build is available, and the current head's full CI is still running. Completion of the unit tests, including EffectiveMaxThreads.* and SQLSecurityContext.SharesQueryMaxThreadsSnapshot, and the normal CI checks will close this gap.
Final Verdict

Status: ✅ Approve — no code changes requested; normal CI completion remains required. No new inline comments or thread-state changes were necessary.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 15, 2026
Comment thread src/Interpreters/Context.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Oct 15, 2026
`getSQLSecurityOverriddenContext` creates the context of a `DEFINER` or
`NONE` view from the global context and makes it a query context, so the
view body took its own snapshot of free memory and CPU slots. A
materialized view is planned while its parent `INSERT` runs, so its fair
share counted the parent's own allocation. Carry the outer query's snapshot
into the view context, like its process list element.

Related: #125946 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Change the fair share of CPU slots and the free memory between two calls of
`getEffectiveMaxThreads`: the query and its copies keep the values of the
first call, a copy still applies its own `max_threads`, and an independent
query sees the new values.

Related: #125946 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/Context.cpp Resolved
…scan of the user query log

`AliasSink::onStart` and `ReadFromUserQueryLog::initializePipeline` make a
query context for a part of a running query, which gave it a fresh
snapshot: the nested `INSERT` of an `Alias` table counted the CPU
allocation of its own outer query. Carry the outer query's snapshot.

Related: #125946 (comment)

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

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3cc671be5 with master 58726cc5c (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.65, programs/clickhouse-keeper ×0.62 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.4 s 12.6 s +8.4 s (+201%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 7.7 s +5.4 s (+237%)
Compile time of recompiled translation units

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

Job report

@serxa

serxa commented Oct 17, 2026

Copy link
Copy Markdown
Member Author

@groeneai The only failed check, Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel), is 05345_text_index_prewhere_read_step_order (the reference differs in read_order_index_first). It looks unrelated to this PR: the test ran with an explicit --max_threads 1, which this PR does not change. In CIDB it has been failing in the same job since 2026-10-16, on master and on more than a dozen unrelated PRs (for example #126245, #126225, #126213, #124907). Please investigate the failure.

@groeneai

Copy link
Copy Markdown
Collaborator

Agreed, it is unrelated. It is fixed by my #125892 (test only), merged on 2026-10-16 at 11:30 UTC. Your run on dc27c9f8 was on 2026-10-15, before that merge.

It is the same diff as on master: only read_order_index_first flips, every result row matches, and the runner's reruns failed 1/50. The test compares RowsReadByPrewhereReaders with SelectedRows on the initiator's query_log row only, so when a remote replica reads some of the marks the ratio check flips. --max_threads 1 does not prevent that. #125892 runs the four measured reads with enable_parallel_replicas = 0.

In CIDB, the four failures after the merge all came from workflows started before it. Since 12:47 UTC on 2026-10-16 the test passed in all 152 ParallelReplicas runs (28 of them on master), with no failure in any job. Nothing needs to change in this PR. A re-run of the old workflow reuses its old merge commit, so the next push is what picks up the fix.

serxa and others added 3 commits November 10, 2026 19:28
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…queries

Take both values with one `once_flag`, and share the snapshot with one
null-safe `Context::shareQueryMaxThreadsSnapshot`. The read rounds of a
streaming `MergeTree` query are planned from a query context made once for
the query, which took its own snapshot after the outer query's allocation
started; share the outer query's snapshot instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@serxa
serxa marked this pull request as ready for review November 10, 2026 20:19
`getEffectiveMaxThreads` returned early for one thread before it read the
snapshot, so a parent `INSERT` with `max_threads = 1` left it empty, and a
materialized view with an automatic `max_threads` took it later, counting
the parent's CPU slot. Take the snapshot first.

Related: #125946 (comment)

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

serxa commented Nov 14, 2026

Copy link
Copy Markdown
Member Author

@groeneai Please review this PR.

What it does. Today the free memory and the fair share of CPU slots that getEffectiveMaxThreads uses are read live at each call site. This PR takes them once per query, into a QueryMaxThreadsSnapshot.

What to look for:

  • Whether every part of a query is planned from the same snapshot, including:
    • subqueries and sets
    • views with DEFINER/NONE SQL security, including materialized views planned during the parent INSERT
    • the nested insert of Alias
    • the system.user_query_log scan
    • the read rounds of streaming MergeTree queries
  • Whether independent queries still take a fresh snapshot.
  • Any simpler way to get the same behaviour.

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I reviewed 21d6b2b6 merged into today's master (58726cc5, a clean merge; master has no new callers of getEffectiveMaxThreads) and measured it against a master build. Setup: idle server, concurrent_threads_soft_limit_num = 16, automatic max_threads, max_threads_min_free_memory_per_thread = 0. The numbers are the fair share from the Lower number of threads for query to the fair share of CPU slots N trace line, over all calls of the query. The parent query plans with 16 in every row.

Part planned while the query already runs master this PR
MV body during INSERT ... SELECT, DEFINER and NONE 8 16
nested INSERT of Alias / the MVs behind it 8 / 5 16
read rounds of SELECT ... FROM t STREAM 8 16
loop(), the inner plan of each iteration 8 16
direct write of an INSERT into Buffer / the destination's MVs 8 / 5 8
an independent query while another one runs 8 8

Your list

  • Subqueries and sets: subquery contexts are copies of the query context, and the in-place set builds (FutureSetFromSubquery::buildSetInplace / buildOrderedSetInplace) build their pipeline with the caller's context, which is derived from it, so all of them share it. They are planned before execution, so both builds give 16 there.
  • DEFINER/NONE views and MVs: shared. createSelectInsertContext builds each view's context from its parent view's, so a chain of MVs keeps one snapshot.
  • Alias and streaming: shared, measured above. The read rounds are spliced into the outer pipeline (MergeTreeCommitOrderSource::updatePipeline) and run on its executor, so the snapshot from the start of the stream matches the threads that run them.
  • system.user_query_log: shared. It is built in initializePipeline, before the executor allocates, so the two builds cannot differ there.
  • Independent queries: still fresh. PARALLEL WITH, EXECUTE AS, SYSTEM sub-statements, refreshes (a new context per refresh), the streaming engines, dictionary loads, async insert flushes, merges and mutations all call makeQueryContext for each run.

One gap: the direct write of Buffer. A block over the maximum thresholds is written to the destination in the INSERT's own thread (StorageBuffer.cpp#L921), but writeBlockToDestination makes a fresh query context from the Buffer's own context (#L1379-L1380), so the nested INSERT and the destination's MVs count the outer INSERT's allocation (8 instead of 16). This fixed it locally (all 16, and the background flush still works):

void writeBlockToDestination(const Block & block, StoragePtr table, const Context * query_context = nullptr);
...
    insert_context->makeQueryContext();
    if (query_context)
        insert_context->shareQueryMaxThreadsSnapshot(*query_context);

with BufferSink::consume passing getContext().get(). The flushes keep nullptr: their rows come from many INSERTs.

Simpler alternatives: I don't see one.

  • Taking the snapshot eagerly in makeQueryContext would remove the ordering issue fixed in 21d6b2b6, but makeQueryContext runs before ProcessList::insert, which can wait up to queue_max_wait_ms (ProcessList.cpp#L249-L255), so the snapshot could predate admission. First use is better.
  • Inheriting it in makeQueryContext by default would not reach DEFINER/NONE views, user_query_log or Buffer anyway: they start from getGlobalContext() or the storage's own context. The explicit share is needed there in any design, and a missed call site falls back to the current behaviour, which is the safer failure.

Not for this PR: some parts never read the effective value, so no snapshot reaches them, e.g. the build layout of a parallel hash join (HashJoinBuildLayout::twoLevel(params.max_threads), with the raw setting from PlannerJoins.cpp#L1356) and QueryPlanOptimizationSettings::max_threads. The changelog's "joined tables" holds for their read streams.

serxa and others added 2 commits November 14, 2026 18:26
…estination

A block over the maximum thresholds of a `Buffer` table is written to the
destination in the `INSERT`'s own thread, under a fresh query context made
from the `Buffer`'s context, so the nested `INSERT` and the destination's
materialized views counted the outer `INSERT`'s CPU slot. Share the outer
query's snapshot there. Background flushes keep their own: their rows come
from many inserts.

Related: #125946 (review)

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

serxa commented Nov 14, 2026

Copy link
Copy Markdown
Member Author

Thanks for the measurements. I applied the Buffer fix as you proposed, in aaf9ab7: writeBlockToDestination takes the INSERT's context, BufferSink::consume passes it, and flushes pass nullptr. I also merged master (3cc671b).

In the changelog entry, "joined tables" now reads "read streams of joined tables", because the parallel hash join layout and QueryPlanOptimizationSettings::max_threads still read the raw setting. Moving those to the effective value is a separate change.

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-checked aaf9ab7762e: 3cc671be5de is exactly the tree I measured (my patch on 21d6b2b6 merged into the same master 58726cc5; only the header comment is new), so the direct write of Buffer and its destination's MVs now plan with 16, and flushes are unchanged. The narrowed changelog entry matches the code.

@serxa
serxa added this pull request to the merge queue Nov 14, 2026
Merged via the queue into master with commit 50be9c1 Nov 14, 2026
193 checks passed
@serxa
serxa deleted the effective-max-threads-per-query branch November 14, 2026 23:21
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 14, 2026
cursor Bot pushed a commit that referenced this pull request Nov 16, 2026
…uffer-insert-auth-ebd9

Resolve the conflicts with #125946 and
#126158.

- `StorageBuffer::writeBlockToDestination` keeps the identity and the flush stage of this
  branch and takes master's `query_context`: the direct write passes the inserting query's
  context to share its `max_threads` snapshot, a flush passes `nullptr` as on master. The
  snapshot is shared on the context this branch builds before restoring the identity.
- `getSQLSecurityOverriddenContext` keeps both master's snapshot sharing and the
  background-operation marker of this branch.
- `AsynchronousInsertQueue::InsertQuery::toTupleCmp` keeps master's `[[nodiscard]]` and
  the `auth_initial_address` key of this branch.

Co-authored-by: yakov <[email protected]>
@serxa serxa self-assigned this Nov 18, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 20, 2026
…n-split-single-thread-plan

Resolve the conflict in src/Planner/Planner.cpp: master moved addWindowSteps to
src/Planner/PlannerSteps.cpp, so the change is re-applied there, with master's
getEffectiveMaxThreads(*query_context). The comment about sampling the value once
is dropped: since ClickHouse#125946 the value comes from a per-query snapshot.

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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-improvement Pull request with some product 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.

3 participants