Repository navigation
Report a distributed-plan task's own metrics in system.query_log - #120949
antoniofilipovic merged 28 commits into
Conversation
…d-plan-task-query-log-attribution
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]>
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
Also checked and found sound rather than changed: Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260919-011200 |
|
Workflow [PR], commit [77fc3c9] Summary: ✅
AI ReviewSummaryThis PR makes in-process Findings❌ Blockers
Tests
Final VerdictChanges requested: the observability change itself looks coherent, but the PR still ships a real local-memory-limit regression and leaves the user-facing LLVM Coverage ReportMeasured on commit 77fc3c9.
Changed lines: Changed C/C++ lines covered: 23/23 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Commit 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.
Flaky check fixed:
|
| 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.
CI finish ledger - db195e8Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The single red is the dashboard verdict alone: the other five shards of this same run report Session id: cron:our-pr-ci-monitor:20260923-163416 |
|
@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. |
| 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; |
There was a problem hiding this comment.
Can we fix this that we record values in the reference files instead throwIf?
There was a problem hiding this comment.
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.
| -- 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; |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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'), |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
|
Split out: #122056, stacked on this branch. The change is byte-identical to what was here ( Two measurements before you pick the merge order. On master today, a dispatched distributed-plan query over a table with I also corrected the changelog category here to (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.) |
CI finish ledger - ad6b449Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260924-210057 |
antoniofilipovic
left a comment
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
Should you use here event_date >= start time of this test?
There was a problem hiding this comment.
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.
|
On "please fix last batch of comment": all three comments of 2026-09-24 are in The only read-rows assertion left is the initiator's If something in that batch is still open, point at it and I will fix it. |
| 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); |
There was a problem hiding this comment.
Do we need the stopwatch here?
There was a problem hiding this comment.
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.
CI finish ledger - 77fc3c9Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 173 check runs completed (131 pass, 41 not selected, 1 red), Session id: cron:our-pr-ci-monitor:20260925-230059 |
|
Fixing PR for the Performance Comparison shards that failed with 'performance dashboard verdict unavailable' created: #122369 |
|
@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. |
3f3bb09
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]>
Related: #115514
Related: #122056
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
system.query_logandsystem.processesnow 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 ownquery_id, correlated to the statement that started it byinitial_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 = 1logged oneQueryFinishrow per fragment, all of them claiming to be the initial query and each reporting the whole query'sread_rows: measured 13 such rows,read_rows = 300185on every one, and the parts reported nowhere.Root cause: a row's counters come from its process-list entry's thread group, and
executeTaskgave 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_idis 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 noinitial_query_idat all (setCurrentQueryIdfills 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-Summarystill totals the whole query. Memory limits become per task in local mode, stricter than master; read, time and temporary-data limits are unchanged.05231records 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_queriespart of the earlier revision is #122056 now, stacked on this branch.Workflow [PR]
Sync PR [sync-upstream/pr/120949]
Version info
26.10.1.923-master(included in26.10and later)