Skip to content

Optimization allocations/deallocations by caching sampling settings instead of traverse all memory tracker hierarchy - #101267

Merged
azat merged 6 commits into
ClickHouse:masterfrom
azat:memtrack-optimize-sampling
Apr 21, 2026
Merged

azat merged 6 commits into
ClickHouse:masterfrom
azat:memtrack-optimize-sampling

Conversation

@azat

@azat azat commented Mar 30, 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):

Optimization allocations/deallocations by caching sampling settings instead of traverse all memory tracker hierarchy

Version info

  • Merged into: 26.4.1.1112

@clickhouse-gh

clickhouse-gh Bot commented Mar 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2e8624f]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
02550_benchmark_connections_credentials FAIL cidb
Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel) FAIL
04078_native_protocol_input_validation FAIL cidb
03258_nonexistent_db FAIL cidb
Stateless tests (amd_llvm_coverage, 1/3) FAIL
03258_nonexistent_db FAIL cidb
Stress test (arm_asan_ubsan) FAIL
Logical error: Port is already connected, (header: [A]) (STID: 0996-3f3c) FAIL cidb

AI Review

Summary

This PR optimizes memory-sampling hot paths by caching effective sampling settings in ThreadStatus, centralizes tracker configuration via configureMemoryTrackerFromSettings, and updates tests to cover both flush and cached allocation paths. I did not find correctness, safety, or performance-regression issues that require changes.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 30, 2026
Comment thread src/Interpreters/ThreadStatusExt.cpp Resolved
@CheSema

CheSema commented Apr 2, 2026

Copy link
Copy Markdown
Member

It seems as MemoryTracker::getSampleProbability now has no ussage, is it correct?

@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@azat

azat commented Apr 17, 2026

Copy link
Copy Markdown
Member Author

It seems as MemoryTracker::getSampleProbability now has no ussage, is it correct?

Yes, thanks, removed

@azat
azat force-pushed the memtrack-optimize-sampling branch from 2e26caa to 709ad50 Compare April 19, 2026 09:20
Comment thread src/Interpreters/ThreadStatusExt.cpp Resolved
@azat
azat force-pushed the memtrack-optimize-sampling branch from 709ad50 to 37f4a99 Compare April 20, 2026 16:35
@azat

azat commented Apr 20, 2026

Copy link
Copy Markdown
Member Author

@CheSema mind taking a look?

@CheSema CheSema self-assigned this Apr 20, 2026
azat and others added 5 commits April 21, 2026 15:02
…traversal on every allocation

On the non-flush path (every alloc/free below the untracked limit),
`getSampleProbability` traversed the full `MemoryTracker` parent chain
(Thread → Process → User → Global) just to discover that sampling is
not enabled. This is the common case and it happened on every single
malloc/free call.

Cache the resolved sample probability and size bounds in `ThreadStatus`
during `applyQuerySettings`, and read them directly on the hot path.
Reduces the non-flush overhead from 2-4 pointer chases to a single
branch on a thread-local double.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…nged`

The squashed commit relied on resolver semantics that treated a zero
`sample_probability` as "not configured" so that the query-level default
would fall through to `total_memory_tracker_sample_probability`. That
silently removed the ability to disable server-wide sampling at the
query level with an explicit zero.

Restore the original `sample_probability >= 0` semantics in
`getResolvedSampleConfig` and push the query-level sample settings onto
the group tracker only when the user actually changed them from the
default. Applied consistently in `configureMemoryTrackerFromSettings`
(used by `ThreadGroup::create` and by `applyQuerySettings` for the
initiator master thread) and in `ProcessList::insert`.

With this:
- default case (no query override): group tracker stays at -1; cache
  resolves up to `total_memory_tracker` and samples consistently on
  every thread without any attach-vs-insert ordering window.
- explicit query-level value (including zero): pushed to the group
  tracker and wins over the total setting, matching the pre-cache
  behavior.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Expose the helper via `ThreadStatus.h` (moved out of the anonymous namespace
in `ThreadStatusExt.cpp`) and call it from `ProcessList::insert` instead of
duplicating the sample/fault/soft-limit setup. Keeps the `.changed`-guarded
sample-setting push consistent between the thread-attach path and the
process-list registration path.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
With the caching-based sampling now inheriting `total_memory_tracker_sample_probability`
consistently across the whole query (no attach-vs-insert race on the initiator),
a single pass produces all expected trace-log rows. Drop the 15-iteration retry
loop and the `time.sleep(1)` between attempts.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@azat
azat force-pushed the memtrack-optimize-sampling branch from 37f4a99 to 232f309 Compare April 21, 2026 13:45
Comment thread src/Interpreters/ThreadStatusExt.cpp Resolved
@azat
azat force-pushed the memtrack-optimize-sampling branch from 232f309 to d2389d8 Compare April 21, 2026 15:06
…erFromSettings`

Gating `setProfilerStep` on `.changed` meant queries using the default
`memory_profiler_step` (4 MiB) left `profiler_limit == 0`, so
`MemoryTracker::allocImpl` stopped emitting `TraceType::Memory` events on the
default path — a behavior change vs the pre-cache `ProcessList::insert`, which
always called `setProfilerStep` when trace collection was enabled.

Restore the unconditional call. The `.changed` optimization stays only for
`memory_profiler_sample_*` settings, where it is needed so the group tracker's
`sample_probability` is left at -1 and inherits from `total_memory_tracker`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Apr 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.00% -0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 100.00% (54/54) · Uncovered code

Full report · Diff report

@azat

azat commented Apr 21, 2026

Copy link
Copy Markdown
Member Author

@azat
azat enabled auto-merge April 21, 2026 20:16
@azat
azat added this pull request to the merge queue Apr 21, 2026
Merged via the queue into ClickHouse:master with commit ec40452 Apr 21, 2026
156 of 161 checks passed
@azat
azat deleted the memtrack-optimize-sampling branch April 21, 2026 20:52
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 21, 2026
azat pushed a commit to azat/ClickHouse that referenced this pull request Apr 23, 2026
PR ClickHouse#101267 removed the 15-iteration retry loop with the claim that the new
caching-based sampling ensures a single pass produces all expected trace-log
rows. After the PR was merged to master, the test began failing on both
master (`Integration tests (amd_binary_excluded_from_llvm)`) and several
unrelated in-flight PRs (ClickHouse#98727, ClickHouse#101434, ClickHouse#103307), each at different
assertion lines in the single-pass test:

- `get_trace_events('Unknown', 'Global', 'JemallocSample') > 0`
- `get_trace_events('Unknown', 'Max', 'MemorySample', query_id) > 0`
- `get_trace_events('Global', 'Max', 'Memory'/'MemoryPeak') > 0`

The reason these events are not guaranteed in a single pass — even with
fully-propagated `sample_probability` — is that two of the trace types are
genuinely probabilistic relative to this test's workload:

- `JemallocSample` is emitted by `jemalloc`'s own profile sampler
  (`lg_prof_sample=20` ≈ one sample per 1 MiB). Ten `logTrace('foo')` calls
  plus a `SELECT * FROM numbers(100000) ORDER BY number` are not guaranteed
  to allocate enough `jemalloc`-tracked memory to trigger a sample inside a
  `MemoryTrackerBlockerInThread(Global)` scope.
- `Memory`/`MemoryPeak` with `memory_context = 'Global'` are only emitted
  when `total_memory_tracker` crosses its `total_memory_profiler_step`
  watermark (4 MiB default). Whether this happens inside a given test
  query depends on cumulative server-wide allocations including background
  activity, not just the query's own allocations.

The retry loop bounds the test runtime at ~15 s while letting these
events accumulate reliably. Restore it, and add a comment explaining
why it is required so it is not dropped again.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=fa205863ba68f05b529e2073defb5cf5df7cc832&name_0=MasterCI&name_1=Integration%20tests%20%28amd_binary_excluded_from_llvm%29

Session: cron:clickhouse-ci-task-worker:20260421-224500

Co-Authored-By: Claude Opus 4.7 <[email protected]>
alexey-milovidov added a commit to azat/ClickHouse that referenced this pull request Jun 29, 2026
Resolve conflicts after ~6 months of master drift:

- src/Common/MemoryTracker.cpp: take master's version. The PR's change to
  allocImpl/free (avoiding global total_memory_profiler_* overriding
  per-query memory_profiler_sample_*) is superseded by the author's own
  merged PR ClickHouse#101267, which reworked sampling into getResolvedSampleConfig
  plus the .changed gating in configureMemoryTrackerFromSettings.

- src/Core/ServerSettings.cpp: master split the list into
  LIST_OF_SERVER_SETTINGS_WITHOUT_PATH / _WITH_PATH and renamed the second
  declarator parameter to ALIAS. Adapt the total_memory_tracker_sample_probability
  alias to use master's ALIAS macro slot (same 6-arg signature as
  DECLARE_WITH_ALIAS) and keep the alias-loading loop in loadSettingsFromConfig.

- tests/queries/0_stateless/01526_max_untracked_memory.sh: combine the PR's
  memory_profiler_sample_min/max_allocation_size=0 reset with master's
  retry loop for HTTP trace_log entries.

Co-Authored-By: Claude Opus 4.8 (1M context) <[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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants