Skip to content

collect profiles event for part_log - #97302

Closed
CheSema wants to merge 90 commits into
masterfrom
chesema-part-log-events
Closed

CheSema wants to merge 90 commits into
masterfrom
chesema-part-log-events

Conversation

@CheSema

@CheSema CheSema commented Feb 18, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

Profile events in system.part_log for MergeTree part writes, merges, mutations, fetches, and partition operations now include the work done in child thread groups (thread-pool and nested-task threads), so the accounting is more precise and complete. As a consequence, the time-based merge profile events such as MergeTotalMilliseconds and MergeExecuteMilliseconds are now cumulative thread time across all participating threads and can exceed the wall-clock duration_ms of the operation. The setting os_threads_nice_value_materialized_view is now obsolete: materialized-view background work no longer has a separate nice-value knob. The system.trace_log columns memory_context and memory_blocked_context gain a new Scope value between Process and Thread; because these are exposed as Enum8, the numeric values of Thread and Max shift by one (Thread from 3 to 4, Max from 4 to 5).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Medium Risk
Touches core thread-group, memory-tracker parenting, and background MergeTree/replication execution paths to change how time and ProfileEvents are attributed, which could affect accounting and logging in production. Functional data paths are largely unchanged, but incorrect attachment/restore could skew metrics or memory tracking.

Overview
Improves system.part_log profiling accuracy by switching part/merge/mutation logging from per-thread ProfileEventsScope/Stopwatch to per-ThreadGroup counters and elapsed time, so events include work done in thread pools and nested tasks.

Adds a new VariableContext::Scope and expands ThreadGroup to support hierarchical parent linkage, nanosecond-precision elapsed accounting, and new helpers (createForBackgroundOps, createForScope, createForFlushAsyncInsertQuery) used across MergeTree merges/mutations, parts moves/attach/fetch/replace, async-insert flushing, and SystemLog flush execution.

Cleans up obsolete ProfileEventsScope, updates thread naming for new background scopes, and adjusts tests to derive log correlation via system.query_log query_id (plus adds coverage ensuring S3-related profile events appear in system.part_log).

Written by Cursor Bugbot for commit 585f7c7. This will update automatically on new commits. Configure here.


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

@clickhouse-gh

clickhouse-gh Bot commented Feb 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7188fd4]

Summary: ❌

job_name test_name status info comment
Style check FAIL
various FAIL cidb
Code Review DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_tsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Feb 18, 2026
@CheSema
CheSema force-pushed the chesema-part-log-events branch from f03af92 to 8be7156 Compare February 19, 2026 16:48
@CheSema
CheSema force-pushed the chesema-part-log-events branch from 8be7156 to 13e7182 Compare February 20, 2026 11:14
Comment thread src/Common/ThreadGroupSwitcher.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.60% 78.70% +0.10%

Changed lines: Changed C/C++ lines covered: 701/743 (94.35%) · Uncovered code

Full report · Diff report

…ents

# Conflicts:
#	docs/en/operations/system-tables/trace_log.md
The constructor's catch block restored the previous group and thread name
but not the saved query_id, so a post-attach failure on a thread with a
direct query_id (e.g. `BgSchPool::<uuid>`) left the thread with an empty
query_id, losing the `system.part_log` / log correlation this PR is meant
to preserve. Mirror the destructor's restore in the catch block and cover
the failure path in the `ThreadGroupSwitcher` unit test.
…s locally

`linkThreadImpl` links the whole parent chain before its own local step,
so an exception from `thread_ids.insert` (e.g. allocation failure) left
the ancestors with a phantom `active_thread_count` and inflated elapsed
time with no matching `unlinkThreadImpl`. Unlink the ancestor chain on a
local failure before rethrowing.
The `03916`, `03221` and `03166` regression tests could still pass on
stale log rows left by a previous attempt in the same test database:

- `03916_part_profile_events` and `03221_merge_profile_events` now filter
  `system.part_log` by `table_uuid` of the current table incarnation
  (`DROP`/`CREATE` gives a fresh UUID), and 03916 additionally asserts
  that the current insert produced a row at all (`count() > 0`).
- `03166_skip_indexes_vertical_merge_1/2` bound the outer
  `system.text_log` scan by the current `OPTIMIZE`'s
  `query_start_time_microseconds`, so the deterministic part-based
  `query_id` branch can no longer match rows from an older attempt.
@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing db5e6d120 with master 8627fa22f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

139 object files changed (+93.52 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/ThreadStatusExt.cpp.o 159.49 KiB 198.34 KiB +38.85 KiB (+24.36%)
src/CMakeFiles/dbms.dir/Interpreters/SystemLog.cpp.o 4.52 MiB 4.55 MiB +30.20 KiB (+0.65%)
src/CMakeFiles/dbms.dir/Interpreters/astContainsStatefulFunction.cpp.o new 26.29 KiB +26.29 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1941 translation units recompiled, 11354 s compile time in total, 1930 of them have a recent master baseline.

Job report

…ents

Conflicts resolved:
- `ThreadStatus.h` / `ThreadStatusExt.cpp`: master independently added a
  `parent` member to `ThreadGroup` (kept master's private declaration, dropped
  the duplicate from this branch) and a new `createForExplainAnalyze` factory,
  which is now implemented on top of this branch's parent-linking constructor.
  The two parent constructors stay public so the branch's `std::make_shared`
  call sites keep working.
- `gtest_borrowed_thread_group_lifetime.cpp`: master's new test borrowed a
  scope via `createForFlushAsyncInsertQueue`; this branch deliberately isolates
  the async-insert flush group's accounting from its parent (see
  `ThreadGroup::rollup_counters`), so the test now borrows via
  `createForExplainAnalyze`, which still exercises the lifetime regression.
- `StorageMergeTree.cpp` / `StorageReplicatedMergeTree.cpp`: include lists,
  kept both sides.
…rting in `~ThreadStatus`

The direct-query-id section of the test assigns `BgSchPool::test-query-id`
to a `ThreadStatus` that has no query context and never clears it, so
`~ThreadStatus` hit its `chassert` that a thread without a query context
carries no query id and the whole `unit_tests_dbms` binary aborted
(`Unit tests (asan_ubsan)`, `(tsan)`, `(msan)` on
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97302&sha=a4baed9dfb8f7f97e52ca1993e6f13a6046df5cb ).

Clear the query id at the end of the test.
{"Global", static_cast<Int8>(VariableContext::Global)},
{"User", static_cast<Int8>(VariableContext::User)},
{"Process", static_cast<Int8>(VariableContext::Process)},
{"Scope", static_cast<Int8>(VariableContext::Scope)},

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 adds the public Scope branch to system.trace_log, but I do not see committed regression coverage that ever emits a Scope-level memory trace and then selects it back. We already had one failure on this PR where forgetting to update the enum mapping made SELECT * FROM system.trace_log throw UNKNOWN_ELEMENT_OF_ENUM; without extending test_trace_log_memory_context (or similar) to force a scope-group allocation and assert memory_context = 'Scope', this new enum value is still unproven.

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.

🕵 Added tests/queries/0_stateless/05137_trace_log_memory_context_scope.sh in 7188fd4. It runs an INSERT with a small memory_profiler_step - writing the part happens under an accounting scope group (ThreadGroup::createForScope), whose memory tracker is at VariableContext::Scope - and then selects the rows back from system.trace_log with memory_context = 'Scope', so the new enum value is exercised end to end (both the emission and the Enum8 mapping that previously threw UNKNOWN_ELEMENT_OF_ENUM). Verified locally against a server built from this branch.

/// that means that flush async insert is called from some SYSTEM FLUSH ASYNC QUEUE query,
/// it is important to account profile events and other things correctly
query_scope = QueryScope::createForFlushAsyncInsert(insert_context, current_query_thread_group);
query_scope = QueryScope::createForFlushAsyncInsertQuery(insert_context, flush_query_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 fixes the flush-query/user-counter mixup by creating a nested async-insert query scope instead of reusing the outer SYSTEM FLUSH ASYNC INSERT QUEUE counter chain, but I do not see regression coverage for the cross-user case that made this necessary. A focused integration test that queues async inserts under one user, flushes them from another, and checks system.user_processes / the flush query counters would keep us from silently regressing to the old last-writer-wins attribution.

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.

🕵 Added tests/queries/0_stateless/05138_async_insert_cross_user_flush_counters.sh in 7188fd4. It queues an async insert as one user, runs SYSTEM FLUSH ASYNC INSERT QUEUE as another, and then asserts on system.query_log: the flushed insert (located through system.asynchronous_insert_log.flush_query_id) is still attributed to the inserting user and wrote its rows, while the flush query keeps its own user and nevertheless accounts the same InsertedRows - i.e. the counters are rolled up locally instead of the flush query being linked into the inserting user chain. system.user_processes itself is not usable for the assertion: it only shows counters of running queries, so the corrupted user parent from the old behavior is not observable once the flush has finished; the flush-query counters plus the per-user attribution of both queries cover the same regression deterministically. Verified locally against a server built from this branch.

`MergeTreeSink` and friends now run each part write under a `ThreadGroup::createForScope`
group, and `ThreadGroupSwitcher` moves the initiating thread into it and back. Every one of
those detach/attach pairs finalized the thread's per-query state, so a single
`INSERT ... FORMAT TSV` over HTTP produced five `system.query_thread_log` rows for one thread
instead of one: the real row, plus a `WritePart` row and a trailing `HTTPHandler` row per part,
all of them zeros. The reset that master's `initPerformanceCounters` performs per attach - it
exists to stop a pooled thread from reporting the running total of every query it ever served -
also discarded `progress_in`/`progress_out` mid-query, so which row carried the real
`written_rows` depended on where the scopes fell.

This is what makes `05023_query_thread_log_progress_per_query` fail on this branch: the INSERT
arm reports `20 1 2 4` where master reports `4 1 1 4`.

An accounting scope is a roll-up inside a query, not a separate thread of work, so the round
trip is now transparent to the thread's per-query state: `ThreadGroupSwitcher` marks the thread
as being inside one (`ThreadStatus::accounting_scope_depth`) for as long as it holds the scope
open, and while it is set the thread keeps its `performance_counters`, `progress_in`,
`progress_out` and `thread_attach_time`, and neither the detach that enters the scope nor the
one that leaves it writes a row. The scope's own counters are unaffected - they roll up into
the parent group as before, which is what `system.part_log` reads.

The scope is entered only when the group being attached is `is_accounting_scope` *and* was
created under the very group the thread is leaving (`ThreadGroup::isAccountingScopeOf`), so a
group belonging to a different query never merges its accounting into the borrowed thread's.
Materialized-view and `EXPLAIN ANALYZE` groups are not accounting scopes and keep reporting
their own rows, as they do on master.

Verified locally: `05023_query_thread_log_progress_per_query` fails before and passes after,
one `HTTPHandler` row per INSERT again with `written_rows` = `ProfileEvents['InsertedRows']` =
50000; `02262_column_ttl`, `03166_skip_indexes_vertical_merge_1`/`_2`,
`03221_merge_profile_events`, `03711_deduplication_blocks_part_log`,
`04498_async_insert_dedup_optimize_on_insert_merge_tree` and the `ThreadGroupSwitcher` gtests
pass.
@abashkeev abashkeev added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 3, 2026
… insert flush accounting

Two review threads asked for regression coverage of behavior this pull
request introduces.

`05137_trace_log_memory_context_scope`: writing a part of an `INSERT` runs
under an accounting scope group (`ThreadGroup::createForScope`) whose memory
tracker sits at `VariableContext::Scope`. The test forces the memory profiler
to sample it and selects the rows back with `memory_context = 'Scope'`, so the
new enum value of `system.trace_log` is exercised end to end - the earlier
failure on this pull request was exactly a stale enum mapping making
`SELECT * FROM system.trace_log` throw `UNKNOWN_ELEMENT_OF_ENUM`.

`05138_async_insert_cross_user_flush_counters`: an async insert queued by one
user and flushed by another must stay attributed to the inserting user, while
its profile events are rolled up into the enclosing
`SYSTEM FLUSH ASYNC INSERT QUEUE` query locally. The test checks both sides
via `system.query_log` (the flushed insert is located through
`system.asynchronous_insert_log`).
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ForMaterializedView`

Address review: ClickHouse#97302 (comment)

The setting `os_threads_nice_value_materialized_view` was never released,
so make it obsolete rather than keeping the separate nice-value path.

Keep `createForMaterializedView` as a dedicated factory method that
delegates to `createForScope` with a MV-specific memory tracker
description.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`ThreadGroup::getProfileCountersSnapshot` flushed the current thread's
pending rusage/taskstats deltas (via `updatePerformanceCounters`) before
snapshotting, but the hardware perf-event counters (`PerfCPUCycles`,
`PerfInstructions`, ...) enabled by `metrics_perf_events_enabled` were
flushed only at thread detach, by `PerfEventsCounters::finalizeProfileEvents`.
A `system.part_log` snapshot taken while the executing thread is still
attached to the operation's `ThreadGroup` could therefore miss those
counters.

`finalizeProfileEvents` could not be reused for a live snapshot because it
disables the perf events before reading. Split out the non-destructive
read/delta accounting into `PerfEventsCounters::updateProfileEvents` (no
disable), make `finalizeProfileEvents` = disable + `updateProfileEvents`,
and call `updateProfileEvents` from `getProfileCountersSnapshot` alongside
the existing rusage/taskstats flush, under the same parent-chain guard.

The `previous_values` delta bookkeeping makes a mid-flight flush followed by
the detach-time finalize non-double-counting. When `metrics_perf_events_enabled`
is off (or perf is unavailable, e.g. `perf_event_paranoid > 2`), all
descriptors are -1 and the call is a no-op.

Addresses the review thread on the live-snapshot `Perf*` gap:
ClickHouse#97302 (comment)
@CheSema CheSema closed this Sep 15, 2026

This branch was successfully deployed

1 active deployment
staging - docs — 7188fd43 Deployed Sep 8, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants