Repository navigation
Add MemoryThreadStacks* async metrics for pthread stack accounting - #106230
Conversation
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.
|
Workflow [PR], commit [8423eb1] Summary: ✅
AI ReviewSummaryThis PR adds PR Metadata
Findings
Final VerdictStatus: 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` 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`
`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.
…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]>
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)
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
azat
left a comment
There was a problem hiding this comment.
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
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.
…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)
…to add-thread-stack-rss-metric
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 153/177 (86.44%) | Lost baseline coverage: none · Uncovered code |
|
Hi @Algunenano — a couple of suggestions to make this PR easier for reviewers and the changelog reader. Description (currently
Ignore this if the current title/body is intentional. |
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")fromsetThreadName, 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, summingSize:/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 callsetThreadNameso they get tagged too.The smaps walk is gated behind
asynchronous_metrics_enable_heavy_metrics. The constructor only opens/proc/self/smapswhen 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_NAMEunsupported) or a restricted container that cannot read/proc/self/smaps— the three metrics are absent rather than reporting zero, and a one-shotMEMORY_THREAD_STACKS_METRIC_UNAVAILABLErow appears insystem.warnings.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added three Linux-only async metrics —
MemoryThreadStacksCount,MemoryThreadStacksVirtual, andMemoryThreadStacksResident— that report pthread stack memory separately from the rest of anonymous memory. Enabled viaasynchronous_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 insystem.warnings.Documentation entry for user-facing changes
Version info
26.6.1.910