Repository navigation
Conversation
|
Workflow [PR], commit [7188fd4] Summary: ❌
|
f03af92 to
8be7156
Compare
8be7156 to
13e7182
Compare
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 701/743 (94.35%) · Uncovered code |
…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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes139 object files changed (+93.52 KiB total), 1 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units1941 translation units recompiled, 11354 s compile time in total, 1930 of them have a recent master baseline. |
…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)}, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🕵 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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🕵 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.
… 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`).
…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]>
`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)
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Profile events in
system.part_logforMergeTreepart 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 asMergeTotalMillisecondsandMergeExecuteMillisecondsare now cumulative thread time across all participating threads and can exceed the wall-clockduration_msof the operation. The settingos_threads_nice_value_materialized_viewis now obsolete: materialized-view background work no longer has a separate nice-value knob. Thesystem.trace_logcolumnsmemory_contextandmemory_blocked_contextgain a newScopevalue betweenProcessandThread; because these are exposed asEnum8, the numeric values ofThreadandMaxshift by one (Threadfrom3to4,Maxfrom4to5).Documentation entry for user-facing changes
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_logprofiling accuracy by switching part/merge/mutation logging from per-threadProfileEventsScope/Stopwatchto per-ThreadGroupcounters and elapsed time, so events include work done in thread pools and nested tasks.Adds a new
VariableContext::Scopeand expandsThreadGroupto 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, andSystemLogflush execution.Cleans up obsolete
ProfileEventsScope, updates thread naming for new background scopes, and adjusts tests to derive log correlation viasystem.query_logquery_id(plus adds coverage ensuring S3-related profile events appear insystem.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]