Skip to content

Report a distributed-plan task's own metrics in system.query_log - #120949

Merged
antoniofilipovic merged 28 commits into
ClickHouse:masterfrom
groeneai:groeneai/distributed-plan-task-query-log-attribution
Sep 28, 2026
Merged

antoniofilipovic merged 28 commits into
ClickHouse:masterfrom
groeneai:groeneai/distributed-plan-task-query-log-attribution

Conversation

@groeneai

@groeneai groeneai commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115514
Related: #122056

Changelog category (leave one):

  • Improvement

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

system.query_log and system.processes now report the metrics of each task of a distributed query plan (make_distributed_plan = 1) in a row of its own: a task is a secondary query with its own query_id, correlated to the statement that started it by initial_query_id. The initiator's row reports its own work instead of the volume its tasks read.

Description

A query with distributed_plan_execute_locally = 1 logged one QueryFinish row per fragment, all of them claiming to be the initial query and each reporting the whole query's read_rows: measured 13 such rows, read_rows = 300185 on every one, and the parts reported nowhere.

Root cause: a row's counters come from its process-list entry's thread group, and executeTask gave a task its own thread group but no entry, so it reported through the initiator's.

An in-process task becomes a secondary query with an entry of its own, internal, because the initiator is already admitted and waits for it. initial_query_id is inherited rather than re-derived at both task-creation sites, so a plan whose own initiator is a secondary query stays rooted at the client's query. A client-sent secondary query has no initial_query_id at all (setCurrentQueryId fills it only for an initial query) and its tasks fall back to its current id; whether to resolve that at the remote fan-out instead is a scoping question for the area owner.

The initiator's row now reports 1 row read against 300185, and X-ClickHouse-Summary still totals the whole query. Memory limits become per task in local mode, stricter than master; read, time and temporary-data limits are unchanged.

05231 records the values it measures in its reference file: per execution path, the initiator's row, and one task row per reader bucket with the parts it was assigned, scanned and pruned. It reddens on a pre-fix build, measured today: the in-process task rows are absent there.

The max_concurrent_queries part of the earlier revision is #122056 now, stacked on this branch.


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

Version info

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

groeneai and others added 9 commits September 18, 2026 11:25
A query run with make_distributed_plan = 1, distributed_plan_execute_locally = 1
produced N+1 QueryFinish rows that all carried the initiator's query_id,
is_initial_query = 1 and the initiator's QueryStatus, so no row reported a task's
own work. Measured on a 2-part fixture with 3 reader buckets: 13 rows, one
distinct query_id, ProfileEvents['SelectedParts'] = 0 on every row, and the task
rows' read_rows tracking the initiator's running total up to its final 300185.
The same query with make_distributed_plan = 0 reports SelectedParts = 1 and
read_rows = 1025 in its single row.

A row's counters are snapshotted from its process-list entry's thread group
(logQueryFinishImpl -> QueryStatus::getInfo). executeTask gave a task its own
query context and thread group but never an entry of its own, and since
Context::createCopy copies process_list_elem while makeQueryContext() does not
reset it, the task context still pointed at the initiator's QueryStatus. The
task's increments landed in the task's group; the row was built from the
initiator's.

448b09a moved local tasks off the initiator's thread group but left its
process-list entry behind, so this completes that change: an in-process task
becomes a secondary query with its own identity and its own entry, exactly as a
dispatched task already is on a worker (StatelessTaskExecutor::startTask). The
entry is internal because this initiator is admitted on the same server and waits
for the task; with is_internal = false the query rejects itself with
TOO_MANY_SIMULTANEOUS_QUERIES under max_concurrent_queries_for_user = 1, measured
on a purpose-built control binary.

initial_query_id is the chain's first query and is inherited rather than
re-derived (as RemoteQueryExecutor::sendQuery does), so the dispatched sibling
site now fills it from getInitialQueryId() instead of getCurrentQueryId(). The
two are identical for a top-level initiator and differ only when a
make_distributed_plan query is itself a secondary query, where the worker's rows
previously claimed the middle query as the chain root.

Note that the mechanism given in ClickHouse#115514's description (a fragment building its
pipeline before logQueryStart) is not the cause: increments accumulate in the
thread group whenever they happen, and the measurement above discriminates the
two explanations.

Read, memory, execution-time and temporary-data limits consequently apply per
task in local mode, matching the worker path's documented semantics, and the
initiator's own read_rows no longer accrues its tasks' progress.

Related: ClickHouse#115514
Three additions to 05231_distributed_plan_task_query_log_attribution, none of
them touching the fix itself:

ast_fuzzer_runs is pinned to 0 for the file. The stress profile sets it to 5, a
fuzzed re-run inherits log_comment, and the test's initiator lookup takes the
most recent matching row, so a mutated clone could be bound as the initiator and
then fail the counter assertions. The runner's own ast_fuzzer_runs = 0 applies
only to its infrastructure queries, so a default-profile run cannot see this.

Each oracle block now starts by asserting that the initiator row was found. A
scalar subquery with no matching row yields the type default, so the row filter
would degenerate into initial_query_id = '', match unrelated traffic, and surface
as a confusing counter mismatch instead of naming its own cause.

A third block covers a plan whose own initiator is a secondary query, which is
the only shape where filling a task's initial_query_id from getInitialQueryId()
rather than getCurrentQueryId() changes the value. prefer_localhost_replica = 0
is what produces that shape: 127.0.0.1 at the server's own port is a local
address and is read in place, which leaves no nested initiator at all. Measured
on the fixture, all 12 of the nested plan's task rows are rooted at the query the
client sent with the change, and none of them are without it, where all 12 are
rooted at the intermediate shard query instead. The block also asserts that the
shard read ran as a query of its own, so it cannot pass on the trivial
top-level shape.

04335_distributed_plan_cancel polls system.processes for a task of the query that
is already reading before killing it, which was gated to the dispatched arm under
the comment "Remote tasks run as queries of their own under the initiator's id".
An in-process task is one of those too now, so the probe runs in both arms. The
local arm observes a reading task on its first poll with the change and in none
of its 600 polls without it; the polling budget is unchanged.

Related: ClickHouse#115514
A distributed query plan reads a table through several fragments, each with a
query id of its own. The table-level max_concurrent_queries slot was taken with
`Context::getCurrentQueryId()`, so one query claimed one slot per reader bucket:
with the limit set to 1 a plan rejected itself with TOO_MANY_SIMULTANEOUS_QUERIES,
and below the limit it consumed several of the slots configured for the table.

`MergeTreeData`'s id set exists to deduplicate exactly this: one query reading a
table through several steps must hold a single slot. The identity that expresses
it is `initial_query_id`, the first query of the chain, which every fragment and
secondary query inherits, so the slot is now keyed on it. For an initial query
`setCurrentQueryId` fills `initial_query_id` from `current_query_id`, and a
classic distributed secondary query already carries the initiator's id, so the
key is unchanged for both; a context that never had an `initial_query_id` keeps
the previous key through the fallback rather than losing the guard.

Measured on a table with `max_concurrent_queries = 1` and three reader buckets,
10 runs per cell: a dispatched plan failed 10/10 before this change (it has
carried per-task ids since worker tasks were introduced) and passes 10/10 after;
an in-process plan, which gains its per-task ids in this branch, likewise.
Independent concurrent queries are still rejected, which
01666_merge_tree_max_query_limit asserts.

The new block in 05231_distributed_plan_task_query_log_attribution runs a plan
over a table limited to one query on both arms and fails with code 202 without
this change. The same test now also asserts the other half of the attribution
contract: the initiator's own row must no longer report the rows its tasks read
(measured 300185 before, 1 after).
Keying the slot on the logical query made the fragments of one query present the
same id to `MergeTreeData::insertQueryIdOrThrowNoLock`, which returned false for a
duplicate, so `getQueryIdHolder` handed a holder to the first fragment only. That
holder belongs to that fragment's own pipeline, and every fragment builds and
destroys a pipeline of its own, so the id left the set as soon as one of them
finished and an unrelated query was admitted against a limit the query was still
using. The id set now counts holders instead of deduplicating them: each fragment
owns one and the slot is released by the last to stop reading.

Measured with a plan whose reader buckets are skewed, probing an independent query
throughout the plan's lifetime, 10 runs: without the count the probe was admitted
while three fragments were still reading in 7 runs (in-process) and 4 of 5
(dispatched); with it, in none. The throttle is not weakened - with 12 fragments of
one plan reading, an independent query is still refused code 202.

The same accounting decides the parallel-replicas path, where one statement reads a
table on several replicas of one server. With the fan-out proven (three secondary
queries reading the table), a statement over a table limited to one query is
rejected in 4 of 10 and 5 of 10 runs on master and in none of 20 after this change.
01666_merge_tree_max_query_limit documented that rejection and worked around it by
disabling parallel replicas; the workaround stays, because the slot is freed when
the reading pipeline is destroyed rather than when the statement returns, and that
window is what the test's next statement runs into (10 of 10 on master, 6 of 10
here). Its rationale now names that reason instead.

New test 05232_distributed_plan_max_concurrent_queries covers both properties: an
unrelated query is refused while any fragment of a plan still reads, in both
execution modes, and a statement reading the table on several replicas is served.
It passes 30/30 here, fails 10/10 without the reference count, and its
parallel-replica block catches the rejection on master in 9 of 10 runs.

05231_distributed_plan_task_query_log_attribution gains two guards. Its
limited-table block asserts that at least two fragments really reached the table,
without which it would also pass on a plan that fell back to local execution or
collapsed to one task (measured: three task rows report parts with three reader
buckets, one with a single bucket). Its metric blocks now also bound the tasks'
summed read_rows from below, so the case where nobody reports the volume cannot
pass (measured: 150187 dispatched, 300184 in-process, 8 for a plan matching no row).

04515_cascades_worker_count_node_source explained its use of the dispatched arm by
only a dispatched fragment having a process-list entry of its own. An in-process
fragment now has one too, so the rationale is restated as the reason that survives:
that entry is internal, and an internal query reserves no slot.
`05232` gave every parallel-replica attempt the same table while requiring
every attempt to be served, so a slot left over from the previous attempt
could have failed a retry. Each attempt now reads its own table, which makes
that assertion independent of when a served statement's slot is released.
Measured on the retry path, the refusal does not actually occur: 0 of 20
statement pairs issued back to back are refused, and the old shape survives
10 of 10 runs with the retry forced, so this removes a possibility rather
than a reproduced failure. The 6 of 10 release lag measured earlier is the
window after `KILL QUERY ... SYNC`, which this block does not enter.

Its two arms also printed the same line while proving different things: on a
build without the reference count, the in-process arm passes and only the
dispatched arm fails, 10 of 10. Each arm now names what it proves, and a
comment records that the in-process fragments stop together, so that arm
cannot show the release on the last reader.

`04515`'s rationale for its CPU-slot arm named the wrong mechanism. Measured,
both arms log five fragment rows and neither reports a slot at all, because
`adjustSettingsForMakeDistributedPlan` forces `use_concurrency_control` off
for every `make_distributed_plan` query, after the query's own `SETTINGS`.
That arm was live when it was added and was silenced by `aaba436b9eae0`; the
comment now states what is measured. Its assertion, coverage and reference
file are unchanged.
`05021` asserted `read_rows < 2000` on the initiator row of an in-process
plan. That row used to accumulate the fragments' progress, so the bound
really did separate the one part the worker reads from the three the
coordinator selected: it reports 1022 on a build without this change. Here
the fragments record on their own entries and the initiator's row reports
only the exchange input, 2 rows, so the assertion could no longer fail and
passed on both binaries alike.

The bound now sums `read_rows` over the query's task rows, correlated by
`initial_query_id`, and asserts the family exists, since an empty one sums to
0 and would pass. Measured 1020 rows over 16 task rows, identical in all ten
randomized runs, against the 3020 an unpruned three-part read takes; 2000 is
kept. Lowering it to 1000 prints 0, as does corrupting the probe marker so
the family is empty. On a build without this change the family is empty,
because every task row there carries the initiator's own `query_id` with
`is_initial_query = 1`, so the repaired assertion reddens without the fix
instead of standing green on both sides of it.

`04656` selected task rows by the `query_id` of the latest `main` task, which
covered the whole family only while the tasks shared the initiator's id. It
now keys on `initial_query_id`: the probe covers ten rows again rather than
one, all still reporting both unsupported settings off, and its reference is
unchanged. Its comment said the ids are shared; they are not, and it now
says what they are.

`05047_cascades_aggregation_pushdown_merge_spill` justified reading spill
evidence from `system.text_log` with fragment counters reaching no
`query_log` entry, which is what this change removes. The oracle is valid
either way and is untouched; the sentence now gives the reason that still
holds.
A client can send its statement as a secondary query. `clickhouse-client
--query_kind secondary_query` does exactly that, `TCPHandler` accepts it in a
Query packet, and `Context::setCurrentQueryId` fills `initial_query_id` only
for `INITIAL_QUERY`, so the statement arrives with that field empty.

The table's `max_concurrent_queries` slot falls back to `current_query_id`
when the logical id is empty, which is right for a context whose current id
is its whole query, and wrong for the contexts this feature creates: a
fragment's `current_query_id` is per fragment. Such a statement therefore
counted once per reader bucket and rejected itself with
TOO_MANY_SIMULTANEOUS_QUERIES over a table limited to one query, in both
execution arms. Master serves it, every fragment there inheriting the
client's id, so the in-process arm was a regression; the dispatched arm was
left with the same defect it is meant to fix. It also left the task rows in
`system.query_log` with an empty `initial_query_id`, which is the column that
correlates them with the statement they belong to.

The id is now resolved once, on the initiator, before the local and the
dispatched path split: `executeTask` fills it before overwriting
`current_query_id` with the fragment's, and `startStage` puts the same value
in the task description, from which the worker assigns its own client info.
`ReadFromMergeTree`'s fallback is unchanged, being still correct for a
context that carries no ids at all.

Measured over a table with `max_concurrent_queries = 1` and two reader
buckets: `Code: 202` before, served after, on both arms, with two fragment
rows reporting `SelectedParts > 0` under the statement's own id and no task
row left with an empty one. Two controls hold: the same statement from an
ordinary client is served on both builds, and two concurrent plain secondary
queries over the limited table still give the second `Code: 202`, so the
guard is re-keyed rather than weakened.

`05232` gains one arm per execution mode, since a single arm would leave
`startStage` untested. Being served proves little on its own, so each arm also
requires at least two of the statement's fragments to report a read; that
count is 0 before the change, both because the query is refused and because
the fragment rows carry no id to correlate on.
Keep only the pre-existing properties a reader cannot derive: the two ClientInfo query ids, where a log row's counters come from, and what the query-id map's count means. The task entry is internal because this initiator is already admitted on the same server and waits for the task, so admitting the task too could reject it against itself; that argument, and the rest of the fix's rationale, is in the earlier commits and the PR body.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Seven rounds of pre-publication review by an independent model (engine: codex) plus a cold reviewer
pass each round, on a rotating slot so no round adjudicates its own work. Round 1: 6 findings, all
test-side. Round 2: 6, one a real regression in the source change. Round 3: 6, one a real defect in
that round's own fix. Round 4: 8, none in the source change. Round 5: 6, one of them this change's
effect on an existing test's oracle. Round 6: 1, and it reopened row 1 for a class row 19 had waved
away. Round 7 was the internal bounce cap: a cold read of the whole diff, with the round-6 fix as the
one hunk no gate had seen, and it raised nothing that changes the code. The cap is reached, so this
is published as is; every residual is listed below rather than carried silently.
All fixes are in
this PR's branch; the rows below are the terminal record per finding.

# Sev Finding Verdict Evidence / action
1 ❌ Distinct per-task ids make sibling reader buckets claim a slot each against the table's own max_concurrent_queries, so one query can reject itself AGREE, fixed ReadFromMergeTree keyed that guard on current_query_id, and MergeTreeData::insertQueryIdOrThrowNoLock deduplicates by exactly that id, so before this change the buckets shared the initiator's single slot. Measured both directions, then keyed the guard on the logical query (initial_query_id) and added a regression block.
2 ❌ Sharing one slot across fragments releases it when the fragment that took it finishes, while its siblings still read AGREE, fixed The holder is attached to one fragment's pipeline and every later fragment receives none, so the logical id left the set mid-query and an unrelated query could enter against a limit of one. Before the re-key two fragments held two ids, so a freed slot always matched a reader that had stopped. Reference-counted the id set: a slot is now released when the last fragment of a query stops reading.
3 ⚠️ The re-key changes parallel replicas too, where the same self-rejection is documented and worked around in 01666 rather than fixed AGREE, fixed That path is not gated by any distributed-plan setting, and the earlier probe carried no proof that the read had fanned out at all. Re-measured with the fan-out proven, both binaries.
4 ⚠️ The table-limit regression block asserts only that two queries do not throw AGREE, fixed It would also pass on a fallback to local execution or a collapse to one task, which is how the regression would return unseen. Added a per-arm guard that at least two task rows report parts read from the limited table.
5 ⚠️ The initiator bound admits a missing or partially contaminated value AGREE, fixed The contract needs the initiator's row to carry only its own reads; > 1000 also passes at 0. Remedy modified after weighing it: pinning the measured 1 exactly would redden on any randomized run that legitimately reads a few exchange rows, so the tasks' summed read_rows is bounded from below instead, which rejects the degenerate case without a brittle constant.
6 ⚠️ Nothing asserts the other half of the contract: that the initiator's row no longer reports the tasks' reads AGREE, fixed ProfileEvents were never on the initiator, but its read_rows did accumulate the tasks' progress (measured climbing to 300185 on the base binary). Asserted on the initiator's own row so a later change cannot re-introduce double counting silently.
7 ⚠️ system.query_log.read_rows still documents initiator-side summing of all replicas DISAGREE (evidence) That text describes the classic replica-progress path (RemoteQueryExecutor -> updateProgressIn), which this change does not touch; a Distributed query still sums. A distributed plan has not aggregated its tasks since the dispatched path landed: a worker task's progress reaches the progress callback only, never the initiator's process-list entry. The caveat is therefore a statement about the feature rather than about these hunks, so it is raised as a question in the description instead of self-authored here.
8 ⚠️ The getInitialQueryId() correction has no live oracle: reverting it left the suite green AGREE, fixed Both accessors are equal for a top-level initiator, so the test was indifferent. Measured that a nested remote() read under prefer_localhost_replica = 0 does nest a plan, and asserted the lineage in both directions.
9 ⚠️ The new test can bind a fuzzed re-run as its initiator under the stress profile AGREE, fixed The stress profile sets ast_fuzzer_runs = 5 and a fuzzed clone inherits log_comment; 04515 documents the same trap. Pinned ast_fuzzer_runs = 0 for the file.
10 ⚠️ The system.processes behaviour named in the changelog is not observed by any test AGREE, fixed 04335 already polls a task in system.processes by initial_query_id, but gated on remote execution under a comment this change falsifies. Ungated it for both modes after measuring both directions.
11 💡 The oracle's initiator lookup can silently bind an empty id AGREE, fixed A scalar subquery with no row yields the type default, so the filter degenerates. Explicit guard first in every block.
12 💡 04515's rationale for skipping local execution is falsified by these hunks AGREE, fixed It said only a dispatched fragment gets its own process-list entry and counters; an in-process one now does too. Rationale corrected, coverage unchanged.
13 💡 Changelog entry not compact; description over budget; a stale sentence offered a probe the test now contains AGREE, fixed Entry cut to two sentences; description condensed and corrected at review time.
14 ⚠️ Keying the slot on the logical query lets two initiators that supply the same query_id share it, since that id is unique only within an initiator AGREE on the mechanism, remedy declined (evidence) Conceded and stated in the description. initial_query_id is already the identity IStorage::lockForShare uses for the same table's read lock at 13 call sites including the ordinary SELECT and INSERT paths, and RWLock.cpp's owner_queries is a refcounted map keyed the same way whose fast path grants a colliding second holder re-entrantly, so that conflation is today's behaviour one layer over. A collision-resistant token is also not available to key on: only initial_query_id crosses the interserver wire, and the worker builds its ClientInfo from the global context, so a composite key would differ between initiator and worker and reopen row 1's rejection. A wire-level logical-query id is a versioned format change I will not self-author; say the word and it follows as its own PR.
15 ⚠️ The parallel-replica block retries against one limited table and requires every attempt to be served, racing the window where a finished statement still owns its slot AGREE, fixed Raised independently by the gate and the cold pass. The window is the one this PR documents in 01666: the slot is freed when the pipeline is destroyed, after the statement returned. A fresh table per attempt removes it rather than shrinking it.
16 ⚠️ Row 12's replacement rationale is wrong too: is_internal does not govern the CPU-slot counters that test asserts AGREE, fixed Raised independently by the gate and the cold pass. is_internal is consumed only inside ProcessList::insert; a fragment's slots come from its own pipeline on the path both arms share, and adjustSettingsForMakeDistributedPlan forces use_concurrency_control off for every such query after the query's own SETTINGS are applied. Measured per arm, then stated.
17 ⚠️ 05232's in-process arm does not discriminate the refcount of row 2 AGREE, remedy modified Correct, and visible in the round's own logs: without the refcount the in-process arm still refuses the independent query while only the dispatched arm reddens, identically 10/10. The hunk keeps a live oracle there. Entering a tail window in the in-process arm is measured impossible, because no in-process fragment exits early: they end together. So the arms now say what each one proves instead.
18 ⚠️ A lower bound on the initiator's own read_rows was asked for as well DISAGREE (evidence) The initiator half already reddens on base through the upper bound: Code: 395, at 300185 against a bound of 1000. A lower bound asserts a different contract, that the initiator reports its own reads, which no statement of this diff can be deleted to break; and the value it would pin is a stable-but-underived 1, the brittle constant already rejected in row 5 of this table for the same reason.
19 💡 The empty-initial_query_id fallback in the re-keyed guard is unexplained Answered wrongly here, corrected by row 26 The answer given was that the fallback is then the pre-change behaviour. That holds only where current_query_id is itself the logical query; for a fragment it is per fragment, which row 26 measures.
20 ⚠️ Moving a fragment's progress to its own row voids an existing read-volume oracle: 05021's pruned-part check reads read_rows from the initiator row of an in-process plan AGREE, fixed Raised independently by the gate and the cold pass. That row used to accumulate the fragments' progress (measured 300185 against 1 here), so the bound really did separate one part read from the coordinator's three; after this change it sees only the exchange input and the bound cannot fail. The test stayed green on both binaries, which is the symptom. Re-keyed on initial_query_id, summed over the query's fragment rows, with an existence guard and a demonstrated failing direction.
21 ⚠️ The 50-run evidence predates the final revision of the new test DISAGREE (evidence) The commit timestamp is when the round committed, not when the file was written. The limited-table blocks were calibrated 70 minutes before the 50-run batch (their bucket-count mutation was run through the real test in the same round), nothing edited that file afterwards, and the batch's per-run durations match the shipped content rather than the previous revision. A fresh batch on the exact head is cheap and was run anyway.
22 💡 04656's settings probe relied on task rows sharing the initiator's id, so it now covers the main fragment alone and its comment is false AGREE, fixed Correlated through initial_query_id so every fragment stays covered, comment corrected to the per-task ids.
23 💡 05047_cascades's rationale for reading text_log instead of ProfileEvents is falsified by this change AGREE, fixed Its premise was that a local fragment's counters reach no query_log entry, which is exactly what this change ends. The text_log oracle is valid either way and is kept; only the sentence changed.
24 💡 The <plan uuid>::<task id> identity is spelled out at both the in-process and dispatched sites Noted, not changed A helper would grow the diff into a dispatch path this PR otherwise leaves alone, and both new tests key on that shape, so a drift reddens a test instead of passing silently.
25 💡 04515's CPU-slot arm stands aside on both arms, so only its fragments > 0 conjunct is live Noted, not changed Worth knowing rather than fixing here: the arm was live when it merged and was silenced by aaba436b9eae0 ("Disable use_concurrency_control with make_distributed_plan"), so every row of both arms now reports zero slots. Reviving it means changing that quirk, which is not this PR's scope; the comment states the measurement instead.
26 ❌ A client can send a secondary query itself (--query_kind secondary_query), which carries no initial_query_id, so the re-keyed guard falls back to the per-fragment id and one plan rejects itself after all AGREE, fixed Row 19's answer was wrong, and row 1 was therefore only fixed for clients that send an initial query. The kind is accepted in a Query packet, the server derives initial_query_id only for an initial query and never fills it afterwards, so it stays empty and each fragment keys the table's single slot on its own id. Master serves that statement, so the local arm was a regression and the dispatched arm stayed broken for this class; the task rows also carried no lineage, which is the correlation the changelog promises. Resolved once on the initiator, before the in-process and dispatched paths split, so the worker inherits it; the guard itself is untouched. Two arms added, each requiring the statement to be served and at least two of its fragments to report parts read from the limited table.
27 💡 The description claimed the 140 make_distributed_plan tests were unchanged bar one AGREE, fixed Five of them move to the new row shape, two of those materially. Enumerated instead at review time.
28 ⚠️ Round 7, raised independently of row 14: the re-key lets a client collapse the table's throttle by sending several secondary queries under one initial_query_id, a field the server does not verify DISAGREE (evidence) validateClientInfo returns early for a secondary query and setCurrentQueryId fills the field only for an initial one, so the premise holds. It is refuted as a change: initial_query_id is already the identity every table-lock owner uses, at 13 lockForShare/tryLockForShare call sites including the ordinary SELECT and INSERT paths, and RWLockImpl::owner_queries is already a refcounted map keyed the same way whose fast path grants a colliding second holder re-entrantly. ProcessList's "initial one is passed by client" warning is about initial_user for user-scoped limits, and its next sentence gives the opposite reason for current_query_id there: one logical query deliberately runs several secondary queries on one server. Same exposure as today's read lock, one layer over, and stated in the description.
29 💡 Round 7: the local regression batch reported one error DISAGREE (harness artifact) 04824_parquet_lazy_materialization_distributed_plan fails on InvalidAccessKeyId / HTTP 403 against localhost:11111, at the fixture's INSERT INTO FUNCTION s3(...) before any plan code runs: no object storage on the repro host. The diff touches no S3 or credential path; 130 of the batch's other 131 pass, 1 skipped by build flavor.
30 💡 Round 7: this log's own verdict cells named a commit through a placeholder that nothing substitutes AGREE, fixed The comment is posted verbatim, so the placeholder would have shipped 19 times. Resolved to the plain verdict; the fixes are in the branch, which is the only reference a reader needs.

Also checked and found sound rather than changed: is_internal = true folds into the unlimited-query
path, so it skips every admission counter and the workload slot but no duplicate-id or logging check;
a null AST is equivalent to the dispatched arm's stub; the per-task id is built by the same expression
as the dispatched path's; the entry's stopwatch shares its clock domain with every other
ProcessList::insert caller; of all getCurrentQueryId() and query_kind readers in src/, the only
ones a deserialized fragment reaches are the limit fixed above, index analysis under
distributed_index_analysis_only_on_coordinator (named in the description) and telemetry that moves
with this change; a fragment takes only share locks, so a distinct lock owner id cannot turn a
deadlock check into a wait; the runtime-filter lookup is per context, not per query id; and every
statement of the diff reddens the suite when removed. The reference count added to the id set is
contained by measurement rather than by assumption: the public insertQueryIdOrThrow has no caller
outside its own translation unit, the release side is reached only from QueryIdHolder's destructor,
that holder is non-copyable and shared by pointer, so one holder is exactly one release, and the
failure path releases the reference it just took.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding.

Session id: cron:clickhouse-review-slot-8:20260919-011200

@clickhouse-gh clickhouse-gh Bot closed this Sep 19, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [77fc3c9]

Summary: ✅


AI Review

Summary

This PR makes in-process make_distributed_plan fragments look like remote worker fragments in system.query_log and system.processes: each task gets its own query_id and its own row, and the new stateless coverage checks that row shape. The final code still has two material issues: local fragments now get separate max_memory_usage budgets instead of sharing one logical-query budget, and the public read_rows / read_bytes descriptions still document requester-side totals that the new local rows no longer provide.

Findings

❌ Blockers

  • [src/QueryPipeline/DistributedPlanExecutor.cpp:966-987] Creating a fresh query context, QueryScope, and ProcessList entry for every in-process fragment also creates a separate query-level memory tracker for every fragment. ProcessList::insert installs max_memory_usage on the current thread group (src/Interpreters/ProcessList.cpp:336-338), and there is no aggregate tracker tying those fragment groups back to the initiator. In distributed_plan_execute_locally = 1, one logical query can therefore use roughly fragment_count * max_memory_usage on a single server as long as each fragment stays under the limit. That is a resource-limit regression unrelated to logging.
    Suggested fix: keep fragment rows separate for observability, but root max_memory_usage in shared initiator state (or otherwise aggregate fragment memory against one logical-query budget) and add a focused regression for local execution.

⚠️ Majors

  • [src/QueryPipeline/DistributedPlanExecutor.cpp:983] The change intentionally moves fragment progress off the initiator row, but the public source-of-truth docs still promise requester-side totals for read_rows / read_bytes (src/Interpreters/QueryLog.cpp:78-79, src/Storages/System/StorageSystemProcesses.cpp:64-66, mirrored in the published query_log / user_query_log / processes reference pages). After this PR, the initiator row of an in-process distributed plan reports only its own exchange work while the task rows carry the table-read volume, so those descriptions are no longer accurate for the rows users will inspect.
    Suggested fix: update the structured docs and mirrored reference text in the same change so read_rows / read_bytes / total_rows_approx explain the per-task rows and the new initiator semantics for make_distributed_plan.
Tests
  • ⚠️ The new stateless coverage exercises query attribution and some system.processes visibility, but nothing currently proves that local distributed-plan fragments still respect one logical max_memory_usage budget. That limit change is therefore untested.
Final Verdict

Changes requested: the observability change itself looks coherent, but the PR still ships a real local-memory-limit regression and leaves the user-facing read_rows / read_bytes documentation stale.

LLVM Coverage Report

Measured on commit 77fc3c9.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 79.50% 79.50% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand, no timing component: 05231 fails on base build 9f36b72d3b8ac and passes on shipped 5a3f77b7f6f5; 05232 passes 50/50 shipped and fails 10/10 on a build of this branch without the reference count; one statement over a max_concurrent_queries = 1 table fails 10/10 with Code: 202 before the checkLimits change, in both arms, including when the client sends it with --query_kind secondary_query.
b Root cause explained? Yes, four linked causes: (1) a row's ProfileEvents come from context->getProcessListElement()'s thread group, and executeTask gave a task its own context and thread group but no entry, while createCopy copies process_list_elem and makeQueryContext() does not reset it, so the row was built from the initiator's QueryStatus (introduced by 448b09a25b131); (2) checkLimits keyed the table's slot on getCurrentQueryId(), i.e. per fragment; (3) insertQueryIdOrThrowNoLock deduplicated the id, so only the first fragment held it and freed the slot while its siblings still read; (4) a client-sent secondary query keeps an empty initial_query_id, so the fallback resolved per fragment again.
c Fix matches root cause? Yes, each at its own source: the task gets its own secondary-query identity and process-list entry (completing 448b09a25b131); the slot is re-keyed to the logical query; the id set counts holders instead of deduplicating them, so the last fragment releases it; the logical id is resolved once on the initiator, before the two task paths split. No guard, no widened bound, no counters relocated, and the throttle is not weakened (measured: with 12 fragments of one plan reading, an independent query is still refused Code: 202).
d Test intent preserved / new tests added? Two new stateless tests: 05231 asserts per-task attribution in both modes, the lineage of a plan whose initiator is itself a secondary query, that the initiator's row no longer reports its tasks' reads, and that two fragments really reached the limited table; 05232 that an unrelated query is still refused while any fragment of a plan reads, and that parallel-replica and client-sent-secondary statements are served through several fragments. 04335's system.processes probe was strengthened, not weakened; 05021, 04656, 05047, 04515 and 01666 were repaired rather than weakened; nothing retagged or slowed, and the 140 make_distributed_plan tests are verdict-identical to the pre-repair run.
e Both directions demonstrated? Yes, every claim one binary swap apart: attribution base 0 task rows against fix 12 rows with 12 distinct ids and SelectedParts 6; initiator read_rows 300185 (10/10) against 1 (10/10); nested lineage 0 of 12 task rows rooted at the client's query against all 12; slot lifetime 7/10 and 4/5 wrong admissions against 0/10 and 0/5; parallel replicas 4/10 and 5/10 rejections against 0/20; client-sent secondary Code: 202 on both arms against served on both; repaired 05021 prints 1 on the fix, 0 on base and 0 when its bound is lowered to 1000.
f Fix is general across code paths? The dispatched worker task was already correct and is the reference this mirrors; both initiator sites that stamp a task's logical query (executeTask, startStage) go through one helper, and the shipped test reddens each separately on the pre-fix build. The slot fix is at the single shared site (getQueryIdHolder has one caller, and every reference to the id set lives in MergeTreeData.{h,cpp}), so it covers a plan's fragments, the dispatched arm's worker tasks and parallel replicas at once. Fixed at the source, not guarded at the failure site.
g Fix generalizes across inputs (params/datatypes/wrappers)? Both changes are per-query state and identity, independent of data types, wrappers and values; covered by the 140-test stateless batch, 28 integration cases (joins, aggregation, broadcast/shuffle/persisted exchanges, read-in-order, FINAL, error propagation, cancellation), 50 randomized-settings runs each of 05231 and 05232, and the existing throttle tests 01666, 02346, 00980 and 03353.
h Backward compatible? (maintainer-approved exception only) Yes: no setting added, removed or re-defaulted, so no SettingsChangesHistory.cpp entry, and no serialized format change. system.query_log row counts are unchanged, only the values become each row's own, and a table's max_concurrent_queries keeps its documented meaning: several reads belonging to one query no longer count separately, and an independent query is still refused.
i Invariants and contracts preserved? process_list_entry is a local held across the whole synchronous doExecuteTask call (the context keeps only a weak_ptr), so it cannot outlive or predecease the task, including on error and early-return paths; the logical id is resolved before current_query_id is overwritten; client info is set before QueryScope::create and the entry inserted after it, as on the worker path, because ProcessList::insert calls CurrentThread::attachQueryForLog and needs the thread group; a null AST is this file's existing idiom; cancellation still reaches tasks through the executor's is_cancelled callback; the id set stays balanced on every path and reaches zero exactly when the last holder is destroyed (01666's warning-absence guard passes); and X-ClickHouse-Summary still reports 300185 while the initiator's row reports 1.

Session id: cron:clickhouse-impl-slot-6:20260919-003100

auto query_scope = QueryScope::create(task_context);
setThreadName(ThreadName::DISTRIBUTED_QUERY_TASK);

/// A query's log row reports the profile counters of its process-list entry's thread group.

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.

This shifts fragment progress off the initiator row, but the public source-of-truth docs still promise requester-side totals for read_rows / read_bytes (src/Interpreters/QueryLog.cpp and src/Storages/System/StorageSystemProcesses.cpp). Because those strings drive the published reference and system.documentation, they should be updated in the same change or users will misread the new rows.

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.

Fact confirmed and intended: the in-process arm's initiator row no longer reports the rows its tasks read (measured 300185 to 1). The description states it and 05231 asserts it in both arms.

I checked both strings you name rather than reusing my earlier answer about query_log alone. Each describes the replica-progress path: "Each replica sends it's read_rows value, and the server-initiator of the query summarizes all received and local values" (QueryLog.cpp:78-79), and "For distributed processing, on the requestor server, this is the total for all remote servers" (StorageSystemProcesses.cpp:64-65). That path is RemoteQueryExecutor -> ReadProgressCallback -> QueryStatus::updateProgressIn (ReadProgressCallback.cpp:62), and this diff touches no file in it, so both sentences hold as before for every shape that aggregates replica progress. A plan fragment is not a replica and sends no progress packet, and a dispatched task's reads have never reached the initiator's entry.

No client-facing total is lost either: doExecuteTask still hands a fragment the initiator's progress callback (untouched here), which is what feeds TCP progress and X-ClickHouse-Summary, and both tables expose initial_query_id for correlating the rows.

That leaves a wording call on two descriptions shared by every query shape, which the description already puts to the reviewers ("read_rows documents a sum over all replicas no make_distributed_plan arm delivers"). I would rather not rewrite published reference text on my own reading, the two strings plus their mirrors in docs/reference/system-tables/ (query_log.mdx, user_query_log.mdx, processes.mdx); say the word and a sentence goes into both here.

@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

See the job log for details.

…t read rows

05232's parallel-replicas arm asserted fan-out over `system.query_log` rows with
`type = 'QueryFinish'`. That misses the replicas the reading coordinator cancels:
a replica takes the table's `max_concurrent_queries` slot in
`ReadFromMergeTree::AnalysisResult::checkLimits` (ReadFromMergeTree.cpp:5115),
seven lines after `SelectedParts` is incremented (:5108) and before the
coordinator hands out any mark range, so a replica whose ranges another one
covers has already held the slot and then reports `QUERY_WAS_CANCELLED_BY_CLIENT`
instead of a finished query.

Whether a second replica also reads rows is a race the test cannot pin. The
coordinator serves the first announcement without waiting for the others
(ParallelReplicasReadingCoordinator.cpp:226-243) and one request covered the
whole table: `2 parts, 147 marks, mark_segment_size: 128,
min_marks_per_request: 160` in all 138 attempts of the red job, the 160 being
`merge_tree_min_rows_for_concurrent_read / index_granularity`. So the first
replica to ask drained it, and only 44 of those 138 attempts (31.9%) satisfied
the old assertion. The arm retried up to ten times, each retry rebuilding a
200k-row table at a measured 13.3 s, which made the failure
0.681^10 = 2.15% per run - against 4 observed failures in ~240 runs of
`Stateless tests (amd_asan_ubsan, flaky check)`, three exiting 1 after the tenth
attempt and one killed by the 180 s cap.

Counting distinct replicas that selected parts reads 3 for every one of those
138 attempts, so the retry loop and its nine spare tables go. The assertion is
strictly stronger: it now counts the replicas that prove slot sharing rather
than the subset that happened to win mark ranges, and it still tracks the real
replica count (measured 0 / 2 / 3 at `max_parallel_replicas` 1 / 2 / 3, and the
test fails with "fewer than two replicas of the statement selected parts" when
only one replica answers).

50/50 local runs pass with randomization on, p50 5.03 s and max 5.43 s against
the previous 5.34 s and 6.13 s on the same box.
`SelectedParts` is incremented at ReadFromMergeTree.cpp:5108, seven lines before
`checkLimits` acquires the slot at :5115 and can throw
TOO_MANY_SIMULTANEOUS_QUERIES, so a replica the limit refuses reports its
selected parts exactly like one that holds the slot. Counting those rows would
have let the arm pass while the self-rejection this change fixes was still
happening: the coordinator can finish through the one surviving replica, so the
statement is served and the count still reaches three.

Count only replicas that did not fail on the limit, and fail on any that did.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Flaky check fixed: 05232 no longer retries a race it cannot win

Stateless tests (amd_asan_ubsan, flaky check) was red on 863c78c2b: 4 of ~240 runs of my own
new test 05232_distributed_plan_max_concurrent_queries failed, three with return code: 1 and
one killed by the 180 s cap. Pushed 8023713ed.

The cause is the parallel-replicas arm's fan-out oracle, not the runtime its durations suggest. It
counted system.query_log rows with type = 'QueryFinish', which misses the replicas the reading
coordinator cancels. A replica takes the table's max_concurrent_queries slot in
ReadFromMergeTree::AnalysisResult::checkLimits (ReadFromMergeTree.cpp:5115), seven lines after
SelectedParts is incremented (:5108) and before any mark range is handed out, so a cancelled
replica has held the slot and reports QUERY_WAS_CANCELLED_BY_CLIENT instead of a finished query.

Whether a second replica also reads rows is a race. The coordinator serves the first announcement
without waiting for the others, and one request covered the whole table: 147 marks, mark_segment_size: 128, min_marks_per_request: 160 in all 138 attempts of the red job, that 160
being merge_tree_min_rows_for_concurrent_read / index_granularity. Only 44 of those 138 attempts
(31.9%) satisfied the old assertion, so the arm retried up to ten times at a measured 13.3 s each,
which puts the failure at 0.681^10 = 2.15% per run against the 1.7% observed.

Counting distinct replicas that selected parts reads 3 for all 138 of the same attempts, so the
retry loop and its nine spare tables are gone. It also excludes replicas refused with 202, without
which the arm would pass on a broken build: with the re-keying reverted the statement is still
served while two replicas are refused, and the unguarded count read 3. 50/50 local runs pass with
randomization on, p50 5.03 s and max 5.58 s.

One measurement worth having before this merges

A client-declared secondary query fanned out to parallel replicas can still be refused by the
table's limit, and this branch makes that a good deal more likely:

-- table: max_concurrent_queries = 1, min_marks_to_honor_max_concurrent_queries = 1
-- clickhouse-client --query_kind secondary_query
SELECT count() FROM t WHERE k < 150000
SETTINGS enable_parallel_replicas = 1, max_parallel_replicas = 3,
    cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost',
    parallel_replicas_for_non_replicated_merge_tree = 1, parallel_replicas_local_plan = 0
-- Code: 202. TOO_MANY_SIMULTANEOUS_QUERIES
arm re-keying reverted this branch
as above, n=10 0/10 refused 2/10 refused
plus AND NOT sleepEachRow(0.0002), so the replicas overlap, n=6 1/6 refused 5/6 refused

The path is therefore already broken before this change, and this change aggravates it. I have not
pinned down the mechanism behind the change in likelihood, so I am not claiming one. The remedy
points at the logical-query-id propagation question the description already raises, which I am not
self-authoring here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - db195e8

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
Performance Comparison (arm_release, master_head, 6/6) CI harness, not this diff: the shard is red only on the confirmed regression(s) on the performance dashboard verdict, a gate that reds unrelated PRs with a regression which does not reproduce on a re-run of the same head (here: 4 too long, 1 slower, 1 unstable; 1 confirmed regression(s)) #121090 (mine, open), with #121189 (mine, open)

The single red is the dashboard verdict alone: the other five shards of this same run report
too long and unstable queries too and are GREEN, so query runtime is not the failing
criterion. 134 checks succeeded and 39 were skipped; Mergeable Check and PR are the
praktika aggregators reflecting the one red above, not separate failures.

Session id: cron:our-pr-ci-monitor:20260923-163416

@antoniofilipovic

Copy link
Copy Markdown
Member

@groeneai the part with max_concurrent_queries fix looks correct to me but I would separate it in a different PR. Can you stack that change on top of this one, as it is unrelated to reporting distributed-plan's task metrics in system.query_log.

Also, the fix for that approach is correct, however, once again it does not belong in this branch.

Comment on lines +76 to +102
SELECT
-- A scalar subquery with no matching row yields the type default, and the row filter below would
-- then degenerate into one that matches unrelated traffic.
throwIf(initiator = '', 'dispatched execution: the initiator row was not found'),
-- The initiator reads only what the exchanges hand it, one aggregate state per reader bucket, so
-- its own row must stay far below the 150000 rows the tasks read (measured: 1).
throwIf(initiator_read_rows > 1000, 'dispatched execution: the initiator row also reports the rows its tasks read'),
-- The other half of that contract: the volume has to be reported somewhere, and the task rows are
-- where it now is (measured: 150187 dispatched, 300184 in-process, 8 for a plan matching no row).
throwIf(sum(read_rows) < 75000, 'dispatched execution: the task rows do not report the rows the query read'),
throwIf(count() = 0, 'dispatched execution logged no task row for the query'),
throwIf(uniqExact(query_id) != count(), 'task rows do not carry a query_id of their own'),
-- Three reader buckets, each selecting the fixture's two parts.
throwIf(sum(ProfileEvents['SelectedParts']) != 6, 'the parts a task read are not reported in its own row'),
throwIf(sum(ProfileEvents['DistributedPlanWorkerPartsReceived']) = 0,
'the parts the coordinator assigned a task are not reported in its own row'),
throwIf(sum(ProfileEvents['DistributedPlanWorkerPartsReceived'])
!= sum(ProfileEvents['DistributedPlanWorkerPartsScanned'])
+ sum(ProfileEvents['DistributedPlanWorkerPartsPruned']),
'a task read or pruned a number of parts other than the number it was assigned')
FROM system.query_log
WHERE event_date >= yesterday() AND type = 'QueryFinish' AND is_initial_query = 0
AND initial_query_id = initiator
-- The rows being counted are the measurement, so they are read locally rather than through a
-- distributed reader over a concurrently written system table.
SETTINGS enable_parallel_replicas = 0, automatic_parallel_replicas_mode = 0
FORMAT Null;

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.

Can we fix this that we record values in the reference files instead throwIf?

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.

Done in ad6b449. The block is recorded values now, one line per execution path:

active parts	2
dispatched initiator	1	0	1
dispatched tasks	1	3	[2,2,2]	3	3	0
in-process initiator	1	0	1
in-process tasks	1	3	[2,2,2]	3	3	0

After the label, an initiator line carries: such a row exists, the parts it reports, and that its own read_rows stays under 1000. A task line carries: the task rows have distinct query_ids, how many of them were assigned parts, the parts each of those selected, then the assigned, scanned and pruned totals.

It still reddens without the fix: against a master build today the two in-process lines come out 1 0 0 and 1 0 [] 0 0 0, so the reference mismatch is the failure rather than a thrown message.

Comment on lines +45 to +54
-- A plan whose own initiator is a secondary query: the shard read below builds a plan of its own,
-- and its tasks belong to the query the client sent, not to the shard query. Reading a local
-- address in place leaves no nested initiator at all, so prefer_localhost_replica = 0 is what makes
-- the shard read a query of its own.
SELECT count() FROM remote('127.0.0.1', currentDatabase(), t_dp_task_metrics) WHERE k < 150000
SETTINGS make_distributed_plan = 1, distributed_plan_execute_locally = 0, prefer_localhost_replica = 0,
enable_parallel_replicas = 0, automatic_parallel_replicas_mode = 0, max_rows_to_group_by = 0,
distributed_plan_max_rows_to_broadcast = 0, distributed_plan_default_reader_bucket_count = 3,
use_query_condition_cache = 0, log_comment = '05231_nested'
FORMAT Null;

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.

Please remove this test case, I think it is not necessary as we have distribution case and local case above and it is enough to prove the point

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 ad6b449, with its assertion block.

One consequence you should have rather than discover later: that was the only case where the initiator's current and initial query ids differ, so the inherited root at the dispatched task-creation site (task_description.initial_query_id) is now covered by no test. The code still inherits it. If you want that kept in some form, say so and I will add it back as a probe of its own.

throwIf(initiator_read_rows > 1000, 'dispatched execution: the initiator row also reports the rows its tasks read'),
-- The other half of that contract: the volume has to be reported somewhere, and the task rows are
-- where it now is (measured: 150187 dispatched, 300184 in-process, 8 for a plan matching no row).
throwIf(sum(read_rows) < 75000, 'dispatched execution: the task rows do not report the rows the query read'),

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.

I think this may be volatile for the future so I would rather try to find some other stat, maybe DistributedPlanWorkerPartsScanned is enough. I am not sure though if you can guarantee that each task will always get the same files to scan if so, we can just assert on that, without read rows

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.

Measured, and the instinct holds on both halves.

Per-task read_rows is not stable: the three reader buckets of one plan split 150176 rows as 50176 / 49824 / 50176, and that split moves between runs.

The part assignment is stable: each of the three buckets is assigned one batch holding the fixture's two parts, scans both and prunes none, identically on both execution paths. The reference records [2,2,2] for the parts the assigned tasks selected and 3 3 0 for the assigned, scanned and pruned totals, which held over 22 randomized-settings runs (the other 8 of 30 died before the test body on this box's own Invalid time zone: zoneinfo/UTC artifact, which reproduces on SELECT 1).

So the assertion is on the parts now, with no read_rows on the task side. read_rows stays on the initiator's row as a bound, because that is the half that reddens without the fix: 1 row against 300185.

It counts a distributed-plan query's fragments as one query against a
table's max_concurrent_queries limit, which is unrelated to reporting a
task's metrics in system.query_log. It goes into a PR of its own, stacked
on this one, with its content unchanged: the ReadFromMergeTree and
MergeTreeData change, 05232 and 01666's comment.

Measured on master today, so it is a fix of its own and not a
consequence of this branch: a dispatched distributed-plan query over a
table with max_concurrent_queries = 1 already fails with Code 202, while
the same query with distributed_plan_execute_locally = 1 succeeds. This
branch alone extends that refusal to the in-process arm, because each
task now has a process-list entry and so a query id of its own.
Three review asks on the test:

- the checks are recorded values in the reference file now, so a run
  reports what it measured rather than a thrown message;
- the case whose initiator is itself a secondary query is gone, the
  dispatched and in-process cases prove the point;
- a task's rows are no longer asserted on. How a reader bucket's rows
  divide between the buckets is not fixed (measured over one plan:
  50176, 49824, 50176), while the parts a task is assigned are: each of
  the three buckets receives one batch holding the fixture's two parts,
  scans both and prunes none, on both execution paths and over 22
  randomized runs.

The initiator's row keeps a bound on its own read_rows, which is the
half of the contract that reddens without the fix: with the tasks
unattributed each of them logs a row of its own that claims to be the
initial query and reports the whole query's 300185 rows.
A task family that reports no read volume sums to 0 and passed the upper
bound alone, whether it was empty or held only the aggregation fragments
of the plan. Measured 1020 rows, so the band is 500 to 2000, and the test
stays green over 8 randomized runs.
@groeneai

groeneai commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

Split out: #122056, stacked on this branch. The change is byte-identical to what was here (git diff db195e80 377f0ec -- src/ 01666 05232 is empty), and this branch keeps only the system.query_log attribution.

Two measurements before you pick the merge order. On master today, a dispatched distributed-plan query over a table with max_concurrent_queries = 1 already fails with Code: 202, and so does a plain SELECT with enable_parallel_replicas = 1 over that table, while the identical query with parallel replicas off is served. Both refusals need the readers of one statement to meet on ONE server process, which is how those clusters are defined here (three loopback entries, one process) and how a plan dispatches several fragments to one worker: query_id_set is a MergeTreeData member, so a statement that reaches each process once cannot collide with itself (measured: 0 failures in 80 parallel-replica runs with one entry per process, against 6 in 120 with one process listed three times). So #122056 is a fix of its own, and it goes in as an Improvement rather than a bug fix. This branch alone extends that refusal to distributed_plan_execute_locally = 1, since each task now has a query id of its own, which is why the stack should land in order. If you would rather have the limit fix first, it does not depend on this branch: only its 05232 in-process arm does, because that arm needs the per-task process-list entries to see two fragments reading. Say so and I will re-base it on master.

I also corrected the changelog category here to Improvement: make_distributed_plan is PRIVATE_PREVIEW, so this is not user-visible misbehavior in a stable release. #122056 is an Improvement too, for the scope reason above.

(Edited a few minutes after posting: tightened the scope of the #122056 claim, and its changelog category with it, after re-checking where the readers of one statement can actually meet.)

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ad6b449

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

@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.

Please fix last batch of comment

-- for all of them.
SELECT 'dispatched initiator', count() > 0, max(ProfileEvents['SelectedParts']), max(read_rows) < 1000
FROM system.query_log
WHERE event_date >= yesterday() AND current_database = currentDatabase()

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.

Should you use here event_date >= start time of this test?

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.

Done in c4877c6.

event_date is a Date, so it can only carry the partition bound; the start time goes on event_time:

CREATE TEMPORARY TABLE start_ts AS (SELECT now() AS ts);
...
WHERE event_date >= yesterday() AND event_time >= (SELECT ts FROM start_ts) AND ...

Applied to all six lookups in the file, not only this one. Same idiom as 14 other stateless tests (04097, 04049, 03772 among them).

Your question turned up something I had wrong: the comment I deleted here claimed a failed run is retried in the same database. It is not. configure_testcase_args runs once per attempt and creates a fresh test_<random> database each time (tests/clickhouse-test:2554, called from the per-attempt path at :4179), so those columns were never aggregating over retries. The explicit bound is what makes the scope hold without depending on runner internals at all.

Values are unchanged, so the reference is untouched: 14 of 20 randomized runs green with 0 reference mismatches, the other 6 dead before the test body on my box's Invalid time zone: zoneinfo/UTC artifact. The master snapshot still reds 5 of 5 on the in-process lines.

event_date is a Date, so it carries the partition bound and cannot carry a
start time; the bound goes on event_time, captured once before the measured
queries. This is the idiom of 16 other stateless tests, 04097 among them.

The comment this removes claimed a failed run is retried in the same
database. It is not: configure_testcase_args runs once per attempt and
creates a fresh test_<random> database each time, so the columns were never
aggregating over retries.

Values are unchanged, so the reference is untouched: 14 of 20 randomized
runs green with 0 reference mismatches, the other 6 dead before the test
body on this box's zoneinfo/UTC artifact. The master snapshot still reds
5 of 5 on the in-process lines.
@groeneai

Copy link
Copy Markdown
Collaborator Author

On "please fix last batch of comment": all three comments of 2026-09-24 are in ad6b449, each answered in its own thread. Recorded values instead of throwIf (r4096606995), the nested remote() case removed (r4096607237), the determinism question and the part-based assertion (r4096607467). Today's event_date ask is in c4877c60.

The only read-rows assertion left is the initiator's max(read_rows) < 1000. Measured on master today, that is the one initiator column that moves (1 against 0), so it is what makes the line red without the fix; the per-task read-rows sum you flagged is gone.

If something in that batch is still open, point at it and I will fix it.

@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 25, 2026

@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.

looks better now

setThreadName(ThreadName::DISTRIBUTED_QUERY_TASK);

/// A query's log row reports the profile counters of its process-list entry's thread group.
Stopwatch task_watch(CLOCK_MONOTONIC);

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.

Do we need the stopwatch here?

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.

The timestamp is needed, the object was not. ProcessList::insert takes the start as its watch_start_nanoseconds argument and QueryStatus resumes it as its own watch (ProcessList.cpp:527), which is what the task's max_execution_time check (ProcessList.cpp:682) and its system.processes.elapsed (ProcessList.cpp:937) read. Nothing in executeTask reads elapsed time off the stopwatch, so I dropped the object and read the clock directly in 77fc3c9. The value is the same: Stopwatch(CLOCK_MONOTONIC) resolves to clock_gettime_ns_adjusted(0, CLOCK_MONOTONIC), which for a non-raw clock is clock_gettime_ns(CLOCK_MONOTONIC). The clock stays CLOCK_MONOTONIC because QueryStatus rebuilds the stopwatch on it, so the Stopwatch default of CLOCK_MONOTONIC_RAW would skew every elapsed time it reports.

05231's in-process arm still matches its reference on the rebuilt binary.

ProcessList::insert needs a start timestamp: QueryStatus resumes it as its own
watch, which is what the task's max_execution_time check, its
system.processes.elapsed and the output format's start time read. Nothing in
executeTask ever reads elapsed time off the Stopwatch, so the object added
nothing over the clock read it wrapped.

clock_gettime_ns(CLOCK_MONOTONIC) returns the same value: Stopwatch's
constructor calls clock_gettime_ns_adjusted(0, CLOCK_MONOTONIC), which for a
non-raw clock and a zero previous reading is that call. The clock stays
CLOCK_MONOTONIC because QueryStatus rebuilds the stopwatch on that clock, so a
start taken on CLOCK_MONOTONIC_RAW (the Stopwatch default) would skew every
elapsed time it reports.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 77fc3c9

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
Performance Comparison (arm_release, master_head, 6/6) no query was judged: the shard reports performance dashboard verdict unavailable: dashboard did not serve this shard within 600s: HTTP 404 ... test comparison details not found, and the gate fails a shard it could not judge. Its own report reads only 5 too long. CIDB has the same message on 21 PRs and one master commit for jobs started 19:05-19:49Z today a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR rollup rows, red only because of the shard above a fix task is created (the same owner as the row above)

All 173 check runs completed (131 pass, 41 not selected, 1 red), Finish Workflow is green and
CH Inc sync passed on this head.

Session id: cron:our-pr-ci-monitor:20260925-230059

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison shards that failed with 'performance dashboard verdict unavailable' created: #122369

@antoniofilipovic
antoniofilipovic added this pull request to the merge queue Sep 28, 2026
@antoniofilipovic

Copy link
Copy Markdown
Member

@groeneai you created a stacked PR on top of this one. When this one gets merged, please rebase that one on top of this one.

Merged via the queue into ClickHouse:master with commit 3f3bb09 Sep 28, 2026
349 of 350 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 28, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 28, 2026
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

Copy link
Copy Markdown
Collaborator Author

Rebased #122056 on master, so its diff is back to its own change (head 74f0a73). The only other change is a test-only commit dropping a 05232 comment that no longer holds on the rebased tree.

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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

4 participants