Skip to content

Add MemoryThreadStacks* async metrics for pthread stack accounting - #106230

Merged
Algunenano merged 25 commits into
masterfrom
add-thread-stack-rss-metric
Jun 17, 2026
Merged

Algunenano merged 25 commits into
masterfrom
add-thread-stack-rss-metric

Conversation

@Algunenano

@Algunenano Algunenano commented Jun 1, 2026 •

Copy link
Copy Markdown
Member

Exposes resident and virtual memory used by pthread stacks as three new async metrics, so the contribution of thread stacks to process RSS is no longer lumped into the catch-all anonymous-memory bucket and can be inspected from system.asynchronous_metrics.

Each named thread tags its own stack VMA via prctl(PR_SET_VMA_ANON_NAME, addr, size, "clickhouse_stack") from setThreadName, so the kernel attaches [anon:clickhouse_stack] to the matching record in /proc/self/smaps. At every heavy-metrics scrape the smaps file is walked allocation-free, summing Size: / Rss: of the tagged VMAs into a cached struct that is re-emitted on every async-metrics tick.

Three previously-anonymous thread entry points (HTTPServerConnection::run, SSHPtyHandler::run, SignalListener::run) now call setThreadName so they get tagged too.

The smaps walk is gated behind asynchronous_metrics_enable_heavy_metrics. The constructor only opens /proc/self/smaps when heavy metrics are enabled, so a default server that did not opt into the feature does not hold the fd or log anything. When the feature is enabled but the host cannot provide the data — either Linux older than 5.17 (PR_SET_VMA_ANON_NAME unsupported) or a restricted container that cannot read /proc/self/smaps — the three metrics are absent rather than reporting zero, and a one-shot MEMORY_THREAD_STACKS_METRIC_UNAVAILABLE row appears in system.warnings.

Changelog category (leave one):

  • Improvement

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

Added three Linux-only async metrics — MemoryThreadStacksCount, MemoryThreadStacksVirtual, and MemoryThreadStacksResident — that report pthread stack memory separately from the rest of anonymous memory. Enabled via asynchronous_metrics_enable_heavy_metrics. Requires Linux 5.17+ (prctl(PR_SET_VMA_ANON_NAME)) and readable /proc/self/smaps; otherwise the metrics are absent and the limitation is reported in system.warnings.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.910

Each OS thread registers its pthread stack base in a process-wide
registry on first call to setThreadName or ThreadStatus construction;
the thread-local destructor removes it on thread exit. AsynchronousMetrics
snapshots the registry, walks /proc/self/smaps once via a persistent fd
in fixed stack buffers, and sums Size/Rss of VMAs whose start address
matches the snapshot. Snapshotting up front bounds the result against
concurrent allocator churn that would otherwise inflate the smaps content
mid-walk.
…ic test

More precise: the metric is only available where /proc/self/smaps exists.
@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8423eb1]

Summary: ✅


AI Review

Summary

This PR adds MemoryThreadStacksCount, MemoryThreadStacksVirtual, and MemoryThreadStacksResident by tagging named Linux thread stack VMAs with PR_SET_VMA_ANON_NAME and scraping /proc/self/smaps on the heavy async-metrics cadence. The current implementation addresses the earlier registry and availability issues, but I still would not approve while the focused test can skip the supported-host publication contract.

PR Metadata
  • 💡 Improvement is a reasonable category.

  • 💡 The changelog entry is required and mostly specific, but it overstates availability: current code also requires Linux 5.17+ support for PR_SET_VMA_ANON_NAME and readable /proc/self/smaps; otherwise the MemoryThreadStacks* rows stay absent.

  • Suggested replacement:

    Added three Linux 5.17+ async metrics, available when asynchronous_metrics_enable_heavy_metrics is enabled and /proc/self/smaps is readable, that report pthread stack memory separately from the rest of anonymous memory: MemoryThreadStacksCount, MemoryThreadStacksVirtual, and MemoryThreadStacksResident.

Findings

⚠️ Majors

  • [tests/integration/test_memory_thread_stacks_metric/test.py:48] [dismissed by author -- https://github.com/Add MemoryThreadStacks* async metrics for pthread stack accounting #106230#discussion_r3405282020] The test still treats presence != "3" as an unsupported-host skip even after checking that no MemoryThreadStacks* warning exists. On a supported host, SYSTEM RELOAD ASYNCHRONOUS METRICS should force the heavy update and publish all three rows; if a regression stops updateThreadStackStats from emitting them without adding an unavailable warning, this test passes without checking the new metric contract. Please skip only after a positive unavailable signal and otherwise assert presence == "3".
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: make the supported-host metric presence an assertion instead of a broad skip, and update the changelog entry to include the Linux 5.17+ and /proc/self/smaps availability constraints.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 1, 2026
Comment thread src/Common/AsynchronousMetrics.cpp Resolved
`/proc/self/smaps` forces the kernel to walk page tables for every VMA
to compute per-VMA `Rss`/`Pss`, so running it on every async metrics
scrape (1s by default) is too expensive on servers with many mappings.

Move the smaps parsing out of `AsynchronousMetrics::update` and into
`ServerAsynchronousMetrics::updateHeavyMetricsIfNeeded`, alongside the
other heavy work like detached-parts and mutation scans. The file
handle moves with it. When heavy metrics are disabled the metric is
simply not published; the stateless test is removed accordingly.
`ThreadStackRegistry::ensureCurrentThreadRegistered` calls
`pthread_getattr_np`, which internally calls `realloc` to read
`/proc/self/maps` for guard-size detection. `ThreadPoolImpl::worker`
calls `setThreadName` from inside `DENY_ALLOCATIONS_IN_SCOPE` at the
top of the worker, so the previous hook in `setThreadName` triggered
the debug-build `Memory tracker: allocations not allowed.` logical
error.

Drop the hook and instead call `ensureCurrentThreadRegistered`
explicitly from the few thread entry points that do not create a
`ThreadStatus`:

  * `ThreadPoolImpl::worker` — right after `ALLOW_ALLOCATIONS_IN_SCOPE`
  * `OwnAsyncSplitChannel::runChannel` / `runTextLog`
  * `SignalListener::run`
Comment thread src/Common/ThreadStackRegistry.cpp Resolved
@Algunenano Algunenano added the comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... label Jun 1, 2026
Comment thread src/Common/ThreadPool.cpp Resolved
@Algunenano
Algunenano marked this pull request as draft June 1, 2026 17:12
`registryInsert` is only referenced from the `OS_LINUX` branch of
`ThreadStackTracker`. Darwin and FreeBSD builds error out with
`-Werror,-Wunused-function`. Annotate both helpers with
`[[maybe_unused]]` so the warning is suppressed without making the
helpers themselves Linux-only (the registry / snapshot path is
compiled on all platforms; only the registration source is gated).

See #106230
- ServerAsynchronousMetrics now caches the smaps walk result in a
  `thread_stack_stats` member and re-emits the three `MemoryThreadStacks*`
  values on every scrape, instead of only on the heavy-cadence tick.
  Previously, with the defaults, the metrics disappeared for 119 of 120
  seconds. Use `UInt64` for the cached fields.

- `ThreadStackTracker` constructor is now `noexcept`, with RAII
  `pthread_attr_destroy` via SCOPE_EXIT, registry insert wrapped in
  try/catch so an unordered_set rehash under memory pressure can no
  longer skip cleanup or propagate out of thread-entry hot paths.
  `ensureCurrentThreadRegistered` is `noexcept` too.

- Explicit `ThreadStackRegistry::ensureCurrentThreadRegistered` calls
  added at every other named-thread entry point that was missing one:
  TCP / HTTP / Keeper / PostgreSQL / MySQL / SSH / gRPC listener
  handlers; Kafka, ZooKeeper send/recv, NuRaft commit/append, Keeper
  request/response/snapshot/S3-snapshot threads; DDL worker variants,
  AsynchronousInsertQueue, ClusterDiscovery, SystemLog flush,
  TraceCollector, Session cleanup, EmbeddedDictionaries, ExternalLoader,
  ConfigReloader, MemoryWorker, AsyncLoader, CacheDictionaryUpdateQueue,
  ArrowFlight, ClientEmbedded, DatabaseOnDisk, DatabaseMySQL,
  WorkloadEntityKeeperStorage, UserDefinedSQLObjectsZooKeeperStorage,
  IOUringReader, PlainRewritable metadata loader, BackgroundSchedulePool,
  BaseDaemon watchdog, Suggest, and ZooKeeperReplicator. Idempotent
  per OS thread (TLS access after the first call).
Runs a server with `asynchronous_metrics_enable_heavy_metrics=1` and a
1-second heavy-metrics period, forces a heavy refresh via
`SYSTEM RELOAD ASYNCHRONOUS METRICS`, then asserts that the three
metrics are present and that `Resident <= Virtual`, `Virtual >= Count * 16384`,
and `Count > 4`. Lives in tests/integration because heavy metrics are
disabled by default in stateless tests.
Tightens the per-stack lower bound from PTHREAD_STACK_MIN (glibc x86_64
16 KiB) to one OS page (4 KiB), which is the smallest page size on every
Linux architecture and the true minimum size of any VMA. Also bumps the
`rss` check from `>= 0` to `> 0`, since at least one stack page in
every registered thread should be paged in.
Algunenano and others added 2 commits June 3, 2026 19:01
…ss-metric

# Conflicts:
#	src/Common/ThreadStatus.cpp
Gate emission of the `MemoryThreadStacks*` async metrics on a successful
`/proc/self/smaps` sample. In environments where `smaps` cannot be read
(sandbox, restricted container) the metrics now stay absent instead of
reporting a fake zero stack footprint.

Also log one warning with the exception trace when the `vm_smaps` reader
cannot be opened, stating the metrics are disabled because access failed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@Algunenano
Algunenano marked this pull request as ready for review June 8, 2026 12:03
Address PR review feedback: `vm_smaps.emplace` was unconditional in the
constructor, but `updateThreadStackStats` only runs from the
heavy-metrics path. On a default server (`asynchronous_metrics_enable_heavy_metrics=false`)
the fd was opened and held for no purpose, and in restricted containers
the failure path also emitted a warning for a feature the user did not
enable. Skip the open entirely unless the heavy path is enabled.

See #106230 (comment)
@azat azat self-assigned this Jun 8, 2026
Comment thread src/Common/AsyncLoader.cpp Resolved

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

I guess it make sense the only thing to care about is the performace of reading smaps, but if you are doing it only under heavy gathering (AFAIR once every 120 seconds), then it should be fine, plus on fresh kernels there is some some of kind of rseq magic, that should not affect that writes (i.e. thread creation or jemalloc new vma creation) that match

Comment thread src/Common/ThreadStatus.cpp Resolved
Comment thread src/Common/ThreadStackRegistry.cpp Resolved
Switch the `MemoryThreadStacks*` async metric implementation from a
process-wide thread-stack registry (mutex + unordered_set + thread_local
RAII tracker, plus ~40 explicit `ensureCurrentThreadRegistered` calls at
every named thread entry point) to a single `prctl(PR_SET_VMA_ANON_NAME)`
call inside `setThreadName`. The kernel tags each thread's stack VMA
with `clickhouse_stack` and the smaps walker recognizes the tag instead
of matching VMA start addresses against a userspace snapshot.

Net delta: -270 lines, no synchronization primitives, no userspace
lifecycle bookkeeping, no snapshot/walk race window.

Trade-off: requires Linux 5.17 or newer (`PR_SET_VMA_ANON_NAME`). On
older kernels `prctl` returns EINVAL, the metric reports zero, and
`setThreadName` emits a one-shot process-wide warning. The metric
descriptions document the kernel requirement.

Three threads previously without a `setThreadName` call now have one so
the prctl hook fires on them too:

  * `HTTPServerConnection::run` -> `HTTP_SERVER_CONN`
  * `SSHPtyHandler::run` -> `SSH_HANDLER`
  * `SignalListener::run` -> `SIGNAL_LISTENER`
…tion calls

The previous commit removed all explicit `ensureCurrentThreadRegistered`
calls but the removal script left a residual whitespace tweak (a missing
blank line after `setThreadName`) in every file that previously had a
registration call immediately after the `setThreadName` line. Restore
those files verbatim from master. No behavior change.
When `prctl(PR_SET_VMA_ANON_NAME)` returns EINVAL on a pre-5.17 kernel,
`setThreadName` already emits a one-shot log warning. Also flip a
process-wide atomic flag exposed via `isThreadStackVMANamingUnsupported`
so `ServerAsynchronousMetrics::updateThreadStackStats` can publish a
`Context::WarningType::MEMORY_THREAD_STACKS_METRIC_UNAVAILABLE` entry in
`system.warnings`. Operators see one log line plus a row in the warnings
table, instead of having to grep the server log to learn why the metric
shows 0.

Returns `false` on non-Linux so any future caller without an OS_LINUX
guard does not publish a spurious warning.
Comment thread src/Common/setThreadName.cpp Resolved
Algunenano and others added 2 commits June 15, 2026 12:26
…est skip

Three follow-ups to the prctl(PR_SET_VMA_ANON_NAME) rewrite:

1. arm_tidy `bugprone-suspicious-stringview-data-usage` on the
   `prctl(..., THREAD_STACK_VMA_NAME.data())` call. The literal is
   NUL-terminated but tidy can't see that through `std::string_view`.
   Switch the constant to `inline constexpr const char *` and pass it
   directly to `prctl`.

2. `setThreadName` no longer logs the "kernel too old" warning. It
   only records the unsupported state silently via the atomic flag.
   On a default server (heavy metrics disabled) the user did not opt
   into the metric, so a startup-time log warning would be noise.
   `ServerAsynchronousMetrics::updateThreadStackStats` already runs only
   when heavy metrics are enabled; emit the one-shot `LOG_WARNING` and
   `system.warnings` row from there.

3. Integration test now `pytest.skip`s when the metric is unavailable
   (older kernel without PR_SET_VMA_ANON_NAME, or restricted container
   that cannot open /proc/self/smaps) by checking `system.warnings`
   first. Keeps invariant assertions for kernels where the metric is
   actually supported.

See #106230 (comment)
and #106230 (comment)
…osts, not zero

The prior wording said "older kernels report 0" but the implementation
intentionally skips publishing when `PR_SET_VMA_ANON_NAME` is unsupported
or `/proc/self/smaps` cannot be read. Update the descriptions and the
preceding comment to say "absent" and point users at the new
`system.warnings` entry, so the user-visible contract matches what the
code does.

See #106230 (comment)
@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.10% 85.10% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 153/177 (86.44%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@Algunenano
Algunenano added this pull request to the merge queue Jun 17, 2026
Merged via the queue into master with commit 742b4c3 Jun 17, 2026
327 of 328 checks passed
@Algunenano
Algunenano deleted the add-thread-stack-rss-metric branch June 17, 2026 10:48
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 17, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @Algunenano — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently misleading):

  • Why: The body describes the implementation as a 'process-wide registry' that 'tracks every OS thread's stack base address' via a 'thread_local whose destructor fires on thread exit', with threads entering from 'ThreadStatus::ThreadStatus()' or 'ThreadStackRegistry::ensureCurrentThreadRegistered()', and per-scrape it 'snapshots the registry' and matches 'each VMA's start address against the snapshot'. None of this exists in the diff: there is no ThreadStackRegistry, no ThreadStatus change, and no address-snapshot matching. The shipped mechanism instead tags each thread stack VMA via prctl(PR_SET_VMA_ANON_NAME, 'clickhouse_stack') in setThreadName and matches smaps headers by the '[anon:clickhouse_stack]' tag. The description appears to narrate an earlier, discarded design.

  • Suggested addition:

    Replace the registry/snapshot narrative with the actual mechanism: setThreadName tags the current thread's stack VMA with prctl(PR_SET_VMA_ANON_NAME, "clickhouse_stack") on first call per thread (Linux 5.17+); at each heavy-metrics scrape ServerAsynchronousMetrics walks /proc/self/smaps allocation-free and sums Size:/Rss: of VMAs whose header carries [anon:clickhouse_stack]. On kernels <5.17 prctl returns EINVAL, a one-shot system.warnings entry (MEMORY_THREAD_STACKS_METRIC_UNAVAILABLE) is emitted and the metrics stay absent.

Ignore this if the current title/body is intentional.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... 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