Skip to content

Make Profile Events ±30x faster by using Per CPU atomics for server-wide and users - #105056

Merged
azat merged 4 commits into
ClickHouse:masterfrom
azat:shard-profile-events-per-cpu
Jul 3, 2026
Merged

azat merged 4 commits into
ClickHouse:masterfrom
azat:shard-profile-events-per-cpu

Conversation

@azat

@azat azat commented May 15, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Make Profile Events ±30x faster by using Per CPU atomics for server-wide and users. Guarded with "user_profile_events_per_cpu" server setting (uses ±640KiB per user on 64 cores, so in case of lots of users it may make sense to keep it disabled)

Benchmark
azat:.../clickhouse/build (shard-profile-events-per-cpu) {elapsed: 242s}$ src/Common/benchmarks/profile_events
2026-07-02T09:40:02+02:00
Running src/Common/benchmarks/profile_events
Run on (64 X 4561.83 MHz CPU s)
CPU Caches:
  L1 Data 32 KiB (x32)
  L1 Instruction 32 KiB (x32)
  L2 Unified 512 KiB (x32)
  L3 Unified 32768 KiB (x4)
Load Average: 2.74, 17.29, 17.43
***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead.
-----------------------------------------------------------------------------------------------------------------------------------------
Benchmark                                                                               Time             CPU   Iterations UserCounters...
-----------------------------------------------------------------------------------------------------------------------------------------
BM_ProfileEvents/1000/process_time/real_time                                        0.954 ms         25.9 ms          658 groups=50 items_per_second=523.846M/s ns/inc=1.90896ns threads=500 users=1
BM_ProfileEvents/10000/process_time/real_time                                        5.35 ms          201 ms           97 groups=50 items_per_second=934.66M/s ns/inc=1069.91ps threads=500 users=1
BM_ProfileEvents/100000/process_time/real_time                                       36.8 ms         1778 ms           17 groups=50 items_per_second=1.35935G/s ns/inc=735.645ps threads=500 users=1
BM_ProfileEventsConcurrentRead/1000/process_time/real_time                           1.01 ms         28.5 ms          651 global_scans=13.857k groups=50 items_per_second=494.135M/s ns/inc=2.02374ns read_us=0 threads=500 users=1
BM_ProfileEventsConcurrentRead/10000/process_time/real_time                          5.82 ms          227 ms           99 global_scans=10.744k groups=50 items_per_second=859.358M/s ns/inc=1.16366ns read_us=0 threads=500 users=1
BM_ProfileEventsConcurrentRead/100000/process_time/real_time                         43.5 ms         1868 ms           13 global_scans=9.062k groups=50 items_per_second=1.14917G/s ns/inc=870.192ps read_us=0 threads=500 users=1
BM_ProfileEventsPeriodicRead/iters:100000/read_us:100/process_time/real_time         37.1 ms         1817 ms           18 global_scans=1.288k groups=50 items_per_second=1.34718G/s ns/inc=742.29ps read_us=100 threads=500 users=1
BM_ProfileEventsPeriodicRead/iters:100000/read_us:1000/process_time/real_time        36.8 ms         1805 ms           18 global_scans=296 groups=50 items_per_second=1.35873G/s ns/inc=735.983ps read_us=1000 threads=500 users=1
BM_ProfileEventsPeriodicRead/iters:100000/read_us:10000/process_time/real_time       36.3 ms         1785 ms           19 global_scans=57 groups=50 items_per_second=1.3757G/s ns/inc=726.902ps read_us=10k threads=500 users=1
BM_ProfileEventsReadLatency/read_us:-1/batch:1/min_time:2.000/real_time              67.2 ns         66.6 ns     41701286 bg_threads=30 descheduled=884 global_scans=0 p50_ns=30 p9999_ns=150 p999_ns=60 p99_ns=41 read_us=-1
BM_ProfileEventsReadLatency/read_us:0/batch:1/min_time:2.000/real_time               69.8 ns         69.2 ns     39971938 bg_threads=30 descheduled=1.196k global_scans=64.365k p50_ns=40 p9999_ns=160 p999_ns=90 p99_ns=70 read_us=0
BM_ProfileEventsReadLatency/read_us:1000/batch:1/min_time:2.000/real_time            69.4 ns         68.2 ns     41663250 bg_threads=30 descheduled=1.289k global_scans=2.534k p50_ns=31 p9999_ns=721 p999_ns=150 p99_ns=50 read_us=1000
BM_ProfileEventsReadLatency/read_us:1000000/batch:1/min_time:2.000/real_time         67.5 ns         66.9 ns     41649125 bg_threads=30 descheduled=1021 global_scans=3 p50_ns=31 p9999_ns=140 p999_ns=61 p99_ns=50 read_us=1000k
BM_ProfileEventsReadAll/per_cpu:0/real_time                                          2.89 us         2.88 us       239444 events=1.339k ncpus=64
BM_ProfileEventsReadAll/per_cpu:1/real_time                                          27.7 us         27.6 us        26853 events=1.339k ncpus=64

Version info

  • Merged into: 26.7.1.470 (included in 26.7 and later)

@clickhouse-gh

clickhouse-gh Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ed38f7a]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug) FAIL
Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-1bfa) FAIL cidb
Performance Comparison (amd_release, master_head, 5/6) ERROR Performance dashboard
Download datasets ERROR

AI Review

Summary

This PR rewrites ProfileEvents to use per-CPU sharded storage for global counters and, by default, for newly-created per-user counters, then updates the main reader/exporter paths and adds a signal-handler-specific increment entrypoint. Most of the early counter-correctness bugs were fixed during review, but the current head still has one new safety gap in the async-signal-safe path and two previously-discussed operational problems that remain unresolved in the code.

PR Metadata
  • Changelog category: Performance Improvement is not well supported by the current evidence. The PR description only benchmarks a 500-thread synthetic hotspot, while the current cloud perf report on the PR still shows more representative regressions than improvements.
  • Changelog entry: the sentence Guarded with "user_profile_events_per_cpu" server setting is inaccurate. Only newly-created User counters respect that setting; global_counters are always sharded.
  • Suggested replacement: Reduces write-side contention in heavily contended ProfileEvents workloads by sharding counters per CPU. The user_profile_events_per_cpu server setting controls sharding for newly-created per-user counters; global counters are always sharded. This can improve high-contention workloads, but increases per-user memory usage.
Findings

⚠️ Majors

  • [src/Common/ProfileEvents.cpp:1547-1552] The new async-signal-safe path is not actually proven signal-safe. incrementSignalSafe now depends on std::atomic_ref<Count>::fetch_add, but unlike other signal-handler atomics in the tree there is no static_assert(std::atomic_ref<Count>::is_always_lock_free). If a supported target/toolchain lowers this to libatomic or a hidden lock, the profiler/write-error handler can deadlock inside the signal path. Suggested fix: assert lock-freedom next to cell, or keep the signal-handler path on a proven lock-free primitive.

  • [src/Common/ProfileEvents.cpp:1890] The write path still pays sched_getcpu() on every ProfileEvents increment. The current cloud perf report on this PR still shows regressions on clickbench Q32/Q33/Q34 and TPC-H Q4/Q7/Q8 after the earlier double-lookup fix, so the remaining fixed CPU-id lookup cost is still violating the Performance Improvement contract for representative short-query workloads. Suggested fix: keep a cheap non-sharded fast path for the uncontended/global case, or gate the global per-CPU path until representative perf jobs stop regressing.

  • [dismissed by author -- https://github.com/Make Profile Events ±30x faster by using Per CPU atomics for server-wide and users #105056#discussion_r3296343390] [src/Interpreters/ProcessList.h:335, src/Common/ProfileEvents.cpp:1633] ProcessList::user_to_queries intentionally retains ProcessListForUser entries forever, so default-on per-CPU user_performance_counters still turn one-off usernames into permanent allocations of roughly getNumCPUs() * end * sizeof(Count) each. The new setting only helps before a user's first query and does not reclaim already-retained entries, so the resident-memory growth problem is still materially worse than before for deployments with many distinct usernames.

  • [dismissed by author -- https://github.com/Make Profile Events ±30x faster by using Per CPU atomics for server-wide and users #105056#discussion_r3506353004] [src/Common/PerCPU.cpp:14-20] getNumCPUs() sizes shards from get_nprocs_conf(), i.e. the host's configured CPU count, not the CPUs the ClickHouse process can actually run on. In cpuset/cgroup deployments this disconnects both per-user memory and global read-side scan width from the server's real CPU budget, so small containers on large hosts still pay the large-host cost forever.

Final Verdict

Request changes. The counter-accounting fixes look much healthier now, but the current head still has an unproven async-signal-safe path, unresolved representative performance regressions, and two operational tradeoffs around retained per-user memory and host-CPU sizing that remain real in the current code.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label May 15, 2026
Comment thread src/Common/ProfileEvents.cpp Resolved
Comment thread src/Common/ProfileEvents.h Resolved
Comment thread src/Common/ProfileEvents.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@azat
azat force-pushed the shard-profile-events-per-cpu branch from fd426da to 14ace03 Compare May 24, 2026 19:27
Comment thread src/Common/ProfileEvents.cpp Resolved
Comment thread src/Common/ProfileEvents.cpp Resolved
@azat

azat commented May 24, 2026 •

Copy link
Copy Markdown
Member Author

Switching user counters as well, significantly improves the throughput, almost 30x

Before using shared counter for users as well

Benchmark                                               Time             CPU   Iterations UserCounters...
---------------------------------------------------------------------------------------------------------
BM_ProfileEvents/1000/process_time/real_time         13.0 ms          604 ms           48 groups=50 incs/thread/step=20.8333 items_per_second=38.3318M/s ns/inc=26.088ns threads=500 users=1
BM_ProfileEvents/10000/process_time/real_time         128 ms         6280 ms            5 groups=50 incs/thread/step=2k items_per_second=39.1737M/s ns/inc=25.5273ns threads=500 users=1
BM_ProfileEvents/100000/process_time/real_time       1212 ms        70796 ms            1 groups=50 incs/thread/step=100k items_per_second=41.251M/s ns/inc=24.2418ns threads=500 users=1

After

Benchmark                                               Time             CPU   Iterations UserCounters...
---------------------------------------------------------------------------------------------------------
BM_ProfileEvents/1000/process_time/real_time        0.884 ms         22.9 ms          710 groups=50 incs/thread/step=1.40845 items_per_second=565.892M/s ns/inc=1.76712ns threads=500 users=1
BM_ProfileEvents/10000/process_time/real_time        4.56 ms          192 ms          144 groups=50 incs/thread/step=69.4444 items_per_second=1096.73M/s ns/inc=911.805ps threads=500 users=1
BM_ProfileEvents/100000/process_time/real_time       35.4 ms         1793 ms           18 groups=50 incs/thread/step=5.55556k items_per_second=1.41233G/s ns/inc=708.051ps threads=500 users=1

Comment thread src/Common/ProfileEvents.cpp Resolved
@azat azat changed the title Shard Profile Events Per CPU Optimize Profile Events by using Per CPU counters for server-wide and users May 27, 2026
@azat
azat force-pushed the shard-profile-events-per-cpu branch from 08b149a to afd8d1b Compare May 27, 2026 11:33
@azat
azat marked this pull request as ready for review May 27, 2026 11:33
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label May 27, 2026
@azat

azat commented May 27, 2026

Copy link
Copy Markdown
Member Author

As @vadimskipin pointed librseq does not gives a lot of benefits here (16% difference between librseq and just per-cpu atomic in peak, while the difference between one atomic vs per-cpu atomic is 30x), removed - 16ae75e

Maoyao233 pushed a commit to Maoyao233/ClickHouse that referenced this pull request Jun 8, 2026
`test_hedged_requests/test.py::test_stuck_replica` is chronically flaky
on heavily overcommitted ASan/UBSan integration shards. The failure shape
in CIDB is identical across 9 unrelated PRs in the past 30 days:

    pause_container('node_1') did not become observably effective within
    90.0s ... still succeed after ~890 probe iterations; last outcome:
    server replied (4 bytes)

The probe in `_wait_for_pause_effective` keeps receiving live ClickHouse
exception packets from `node_1` for the entire 90s budget, which proves
that `docker compose pause` returned success while the cgroup freezer
never actually froze the user-space tasks. The existing SIGSTOP fallback
in `ClickHouseCluster.pause_container` only fires when `docker compose
pause` raises an exception, not when it lies about success, so the
escalation path was never taken.

Switch this test to `cluster.pause_container_using_signal`, which uses
`SIGSTOP`/`SIGCONT` from the start. A signal cannot be silently lost the
way the cgroup freezer can, so the pause becomes observable on the very
first probe iteration. Same helper is already used by
`test_postgresql_replica_database_engine` for the same reason.

The change is local to one call site. The chronic flake hit
`Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/6)` in the
following PRs (CIDB, last 30 days): ClickHouse#103404, ClickHouse#106311, ClickHouse#105010, ClickHouse#105056,
ClickHouse#104830, ClickHouse#106025, ClickHouse#100391, ClickHouse#106571, ClickHouse#103229. All show the same
`server replied (4 bytes)` outcome, distinguishing this from generic
flakiness.

Related: ClickHouse#106571
@azat
azat force-pushed the shard-profile-events-per-cpu branch from b42ac74 to fb57ea0 Compare July 2, 2026 07:40
@azat
azat enabled auto-merge July 2, 2026 12:29
@azat
azat disabled auto-merge July 2, 2026 12:39
@azat
azat force-pushed the shard-profile-events-per-cpu branch from fb57ea0 to ed38f7a Compare July 2, 2026 12:39
@azat
azat enabled auto-merge July 2, 2026 12:40
@azat
azat disabled auto-merge July 2, 2026 13:19
Comment thread src/Common/ProfileEvents.cpp Resolved
Comment thread src/Common/ProfileEvents.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.60% 92.70% +0.10%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 220/237 (92.83%) · Uncovered code

Full report · Diff report

@azat
azat enabled auto-merge July 2, 2026 22:08
@azat
azat added this pull request to the merge queue Jul 3, 2026
@azat

azat commented Jul 3, 2026

Copy link
Copy Markdown
Member Author

Merged via the queue into ClickHouse:master with commit 2bf720f Jul 3, 2026
171 of 174 checks passed
@azat
azat deleted the shard-profile-events-per-cpu branch July 3, 2026 07:11
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 3, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…er-cpu

Make Profile Events ±30x faster by using Per CPU atomics for server-wide and users
pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Sep 29, 2026
`Regexps::LocalCacheTable::getOrSet` incremented `RegexpLocalCacheHit` or
`RegexpLocalCacheMiss` on every lookup, and `MatchImpl::matchOneRow` does
one lookup per row whenever the pattern of `LIKE`/`match` is not a
constant. `ProfileEvents::increment` does an atomic add at every level of
the counter chain. The user and global levels are per-CPU since ClickHouse#105056,
but the thread group level is a single row, so every thread of the query
wrote the same cache line on every row. The query was bound by that line:
`re2_regex_caching` `#3` took 91 ms at both 8 and 32 threads, and its cost
differed between server processes, which made `#3`, `#5` and `#6` of that
test noisy on the amd performance shards.

The table now counts hits and misses in two members and adds them to
ProfileEvents once, in its destructor. A table is a local of
`vectorVector`/`vectorFixedVector`/`constantVector`, so it lives for one
block on one thread: the totals per query are unchanged (a miss is still
counted before `createRegexp`, so a failed compile still reports it), and
the shared counter is written twice per block instead of once per row.
Tables that did no lookup report nothing, as before. With
`trace_profile_events = 1` these two events now give one `trace_log` row
per block (with the block total) instead of one per row.

Release build, 8 threads pinned to 8 physical cores, 10 server processes
per binary: `#3` and `#5` 90 -> 18 ms, `#6` 94 -> 34 ms, the other queries
of the test unchanged; user CPU at 8 threads over 1 thread for `#3` goes
from 5.2 to 1.0. At 32 threads `#3` goes from 91 to 15 ms.

The new test checks the exact hit and miss totals for the three callers
(String, FixedString and constant haystacks).

Related: ClickHouse#121795, ClickHouse#100759

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants