Skip to content

Count one statement as one query in a table's max_concurrent_queries limit - #122056

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/max-concurrent-queries-one-slot-per-query
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/max-concurrent-queries-one-slot-per-query

Conversation

@groeneai

@groeneai groeneai commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120949

Changelog category (leave one):

  • Improvement

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

A SELECT that reads one MergeTree table through several readers of a single statement on one server, the fragments of a distributed query plan or the replicas of a cluster whose entries resolve to that server, now counts as one query against the table's max_concurrent_queries limit instead of competing against itself for its slots. The limit is taken under the statement's initial query id, and its slot is released by the last of the statement's readers rather than the first.

Description

ReadFromMergeTree::AnalysisResult::checkLimits keys the slot on getCurrentQueryId(), and each read of one statement carries a query id of its own, so a statement whose readers meet on one server competes against itself and is refused with TOO_MANY_SIMULTANEOUS_QUERIES. Measured on master 618a561273dfb, table with max_concurrent_queries = 1:

enable_parallel_replicas = 1, max_parallel_replicas = 3, cluster of three loopback entries on one server
  Code: 202. Too many simultaneous queries for table <db>.t_pr. Maximum is: 1. (TOO_MANY_SIMULTANEOUS_QUERIES)
enable_parallel_replicas = 0
  served
make_distributed_plan = 1, distributed_plan_execute_locally = 0
  Code: 202, through stage_0_0

Scope, which decides the category: query_id_set is a MergeTreeData member, so the limit counts per server process and a statement that reaches each process once cannot collide with itself. Measured earlier on a cluster with one entry per process: 0 failures in 80 parallel-replica runs, against 6 in 120 with one process listed three times. Reachable in a deployment is the distributed-plan case, where several fragments of one plan go to one worker, and make_distributed_plan is PRIVATE_PREVIEW. So this goes in as an Improvement rather than a bug fix, even though 01666_merge_tree_max_query_limit.sh has carried --enable_parallel_replicas 0 since 26.8 for exactly this reason.

getInitialQueryId() is what every fragment and secondary query of one statement shares, with a fallback for a client-sent secondary query, which has none; RemoteQueryExecutor fills that empty id with the statement's own before sending, so its parallel replicas share it too. The running set holds a reader count per id, so the slot is freed by the last reader: the readers of one statement stop at different times.

05232 covers the slot's lifetime in both distributed-plan cases and the parallel-replicas case, each also for a client-sent secondary query.

05232's in-process case relies on the per-task process-list entries of #120949 (merged) to observe two fragments reading one table.


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

@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Sep 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a4b2f94]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The change counts qualifying MergeTree readers of one statement against a single max_concurrent_queries slot, retains that slot through the last qualifying reader, and propagates a shared ID for client-sent secondary queries. Reviewed head: a4b2f944f481933660357c655db586268b8a4a4f. One previously reported admission-limit concern remains, dismissed by the author; there are no new inline findings.

Missing context / blind spots
  • ⚠️ The current CI report records the stateless jobs as skipped by the review-thread gate. No local server binary was available for independent execution. The author reports that the secondary-query regression fails on the previous revision and passes repeatedly with the fix; completed CI execution of 05232 would independently confirm that evidence.
Findings

⚠️ Majors

  • src/Processors/QueryPlan/ReadFromMergeTree.cpp:566: Independent statements can share a table admission slot when their client-chosen initial_query_id values collide. For example, two initiators can concurrently run a query named report against one worker: their worker-side current_query_id values are distinct, but both look up report. With max_concurrent_queries = 1, the second reader increments the existing reference count before the capacity check in MergeTreeData::insertQueryIdOrThrowNoLock, admitting both statements. [dismissed by author -- https://github.com/Count one statement as one query in a table's max_concurrent_queries limit #122056#discussion_r4096868899] Sharing a read lock does not enforce admission capacity, and the separate per-user limit does not preserve this table's configured limit.

    Suggested fix: propagate a server-generated statement identity that distinguishes independent initiators/statements while remaining shared by their fragments. Add a focused regression with independent initiators reusing one client query ID and verify that the second statement is refused.

Final Verdict

Status: ⚠️ Request changes. Preserve the table admission limit for independent statements with colliding root query IDs and cover that boundary with a regression test. The dismissed concern remains summary-only; no duplicate inline comment was posted.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 24, 2026
auto query_id = context_.getCurrentQueryId();
/// The limit counts whole queries: `initial_query_id` is shared by every fragment and secondary
/// query of one client query, and is empty only when the client itself sent a secondary query.
auto query_id = context_.getInitialQueryId();

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.

Keying the slot by initial_query_id alone is not enough to identify one logical statement on this server.

ProcessList explicitly avoids initial_* for server-side limits because those fields are client-supplied and not uniqueness-checked on the receiving host (see the rationale around current_query_id in ProcessList.cpp). After this change, two unrelated distributed queries that reuse the same root query_id on different initiators will collapse onto one query_id_set entry here and only consume one max_concurrent_queries slot.

We need a server-unique logical-query key (or at least a key that includes trusted initiator identity), otherwise reusing query_id becomes a way to undercount the table limit.

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.

Unrelated statements that reuse one root query_id already share the table read lock, since IStorage::lockForShare is keyed on getInitialQueryId() with the same last-holder-frees count, so this limit follows that convention. The per-user limit max_concurrent_queries_for_user is unaffected: ProcessList still keys it on the authenticated user.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 377f0ec

Every failure below has an owner: a fixing PR (mine 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.

Check / test Reason Owner / fixing PR
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) job error before any test ran: Failed to load test selection: CIDB query failed ... play.clickhouse.com Read timed out (read timeout=60); 69 PRs hit this same signature between 09:09Z and 20:03Z a fix task is created (investigating at full effort, fixing-PR link to follow here)
Stateless tests (arm_asan_ubsan, targeted) same test-selection read timeout against the CI database, same outage window a fix task is created (investigating at full effort, fixing-PR link to follow here)
Finish Workflow / Post Hooks cascade of the errored targeted shard: it dropped Bugfix validation, so the new-tests hook found no validating job a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR aggregator statuses reporting the rows above, no independent failure a fix task is created (investigating at full effort, fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260924-210057

groeneai and others added 2 commits September 28, 2026 16:34
A table's max_concurrent_queries counts query ids, and several kinds of
one statement read the same table under ids of their own: a replica read
under parallel replicas, and a fragment of a distributed query plan. A
single statement then competes against itself for the table's slots and
is rejected with TOO_MANY_SIMULTANEOUS_QUERIES.

Measured on master, one shard with three replicas of this server and a
table with max_concurrent_queries = 1: a SELECT under
enable_parallel_replicas = 1 fails with Code 202 while the identical
SELECT without parallel replicas is served, and a dispatched
distributed-plan query over the same table fails the same way.

The limit is taken under the initial query id, which every fragment and
secondary query of one statement shares, and the running set holds a
reader count per id so the slot is freed by the last reader rather than
the first. 01666's comment loses the workaround it described.
The comment said only the dispatched arm tells a slot released by the
last reader from one released by the first, because in-process fragments
never stop early. On master with ClickHouse#120949, a build that keeps the new key
but drops the reader count now fails the in-process arm too, in 8 of 10
runs, so the claim no longer holds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/max-concurrent-queries-one-slot-per-query branch from 377f0ec to 74f0a73 Compare September 28, 2026 17:48
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 4214ca7c2a1195c89a10012244b4225823198db9 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@antoniofilipovic antoniofilipovic self-assigned this Sep 29, 2026
The test arms the server-global fail point
parallel_replicas_wait_for_unused_replicas, and master's Style check
(failpoint_tests_are_isolated) now requires every stateless test that
arms a fail point to be tagged no-parallel and no-fasttest. The test
already carries no-fasttest; 04207_pr_additional_filters.sql, which arms
the same fail point, is tagged the same way.

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

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Failed to load test selection targeted-shard errors in my 2026-09-24 ledger: #122111 (external, merged 2026-09-26).

@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

Dear @antoniofilipovic, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@antoniofilipovic

Copy link
Copy Markdown
Member

@groeneai can you merge master into this one and fix conflicts if there are some?

@antoniofilipovic antoniofilipovic left a comment

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.

Change looks reasonable, please merge master before and fix new conflicts if there are some

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged current master into the branch, new head 3249da8. There were no conflicts, and the PR's own diff is unchanged. On the merged tree 05232 and 01666 pass 50/50 each with randomized settings, and 05232 still fails on a master build without this change.

groeneai and others added 2 commits November 13, 2026 15:02
A client can send a statement as a secondary query with no initial query id.
`RemoteQueryExecutor` forwarded that empty id unchanged, so each parallel
replica fell back to its own `current_query_id` in
`ReadFromMergeTree::checkLimits`, took a slot of its own in the table's
`max_concurrent_queries`, and the statement could refuse itself with
TOO_MANY_SIMULTANEOUS_QUERIES. Fill the empty initial query id with this
query's id before sending, as the distributed plan already does for its tasks.

05232's parallel-replica case now also runs as a client-sent secondary query:
it fails 5/5 on the previous head (Code 202 from a replica) and passes with
this change.

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

This branch has not been deployed

No deployments
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 comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-review-human PR origin: human review feedback on a groeneai PR pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants