Repository navigation
Choose the effective max_threads once per query - #125946
Conversation
`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]>
|
Workflow [PR], commit [3cc671b] Summary: ✅
AI ReviewSummaryReviewed #125946 at Missing context / blind spots
Final VerdictStatus: ✅ Approve — no code changes requested; normal CI completion remains required. No new inline comments or thread-state changes were necessary. |
`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]>
…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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units1353 translation units recompiled, 9326 s compile time in total, 1353 of them have a recent master baseline. |
|
@groeneai The only failed check, |
|
Agreed, it is unrelated. It is fixed by my #125892 (test only), merged on 2026-10-16 at 11:30 UTC. Your run on It is the same diff as on 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 |
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]>
`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]>
|
@groeneai Please review this PR. What it does. Today the free memory and the fair share of CPU slots that What to look for:
|
groeneai
left a comment
There was a problem hiding this comment.
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/NONEviews and MVs: shared.createSelectInsertContextbuilds each view's context from its parent view's, so a chain of MVs keeps one snapshot.Aliasand 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 ininitializePipeline, before the executor allocates, so the two builds cannot differ there.- Independent queries: still fresh.
PARALLEL WITH,EXECUTE AS,SYSTEMsub-statements, refreshes (a new context per refresh), the streaming engines, dictionary loads, async insert flushes, merges and mutations all callmakeQueryContextfor 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
makeQueryContextwould remove the ordering issue fixed in21d6b2b6, butmakeQueryContextruns beforeProcessList::insert, which can wait up toqueue_max_wait_ms(ProcessList.cpp#L249-L255), so the snapshot could predate admission. First use is better. - Inheriting it in
makeQueryContextby default would not reachDEFINER/NONEviews,user_query_logorBufferanyway: they start fromgetGlobalContext()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.
…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]>
|
Thanks for the measurements. I applied the In the changelog entry, "joined tables" now reads "read streams of joined tables", because the parallel hash join layout and |
groeneai
left a comment
There was a problem hiding this comment.
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.
…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]>
…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]>
When
max_threadsis auto,getEffectiveMaxThreadslowers 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::readand everyBuildQueryPipelineSettings. 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.makeQueryContextcreates the snapshot, and every context copied from the query context shares it.getEffectiveMaxThreadstakes aContextand combines the snapshot with that context's settings. A subquery with its ownmax_threadsstill 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 aDEFINERorNONEview (including a materialized view planned while its parentINSERTruns), the nestedINSERTof anAliastable, the scan ofsystem.user_query_log, the read rounds of a streamingMergeTreequery and the direct write of a large block from aBuffertable to its destination.max_insert_threads_min_free_memory_per_threadreads 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):
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_threadsis 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
26.11.1.2325-master(included in26.11and later)