Skip to content

Report the stack trace of a large charge to the global memory tracker - #119527

Merged
alexey-milovidov merged 21 commits into
ClickHouse:masterfrom
groeneai:groeneai/memtracker-drift-origin-117681
Sep 19, 2026
Merged

alexey-milovidov merged 21 commits into
ClickHouse:masterfrom
groeneai:groeneai/memtracker-drift-origin-117681

Conversation

@groeneai

@groeneai groeneai commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117681
Related: #118434 (comment)
Related: #118094
Related: #117738
Related: #117995

Changelog category (leave one):

  • Improvement

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

Added a server setting min_allocation_size_to_log_stack_trace. When a single charge to the global memory tracker reaches it, the stack trace is written to the server log and to system.trace_log with trace type MemoryLargeAllocation. This attributes a global tracked total that has grown far beyond real memory usage, a state in which the server refuses every allocation while far below its limit. Default 0 keeps it off.

Description

Requested by @ alexey-milovidov on #118434: the hung check never gets a usable server, every connection being answered with a bogus (total) memory limit exceeded: would use 160.98 GiB (attempt to allocate chunk of 0.00 B), current RSS: 1.71 GiB.

This does not fix the drift. #118094 and #117738 correct the counter, #117995 stops the harness calling it a deadlock, and #118094 states the remaining gap itself: where the phantom bytes come from is still unknown. This change makes the next occurrence say where.

On one such run, no artifact can name the site, for two structural reasons:

  • the blocked-Global branch of MemoryTracker::allocImpl adds to amount and rss, updates the peak and the metric, then returns without reaching commitAllocation - so no limit check, no trace, no ProfileEvent;
  • everything that does reach commitAllocation reports into system.trace_log, the sink the wedge breaks (Failed to flush system log system.trace_log x109 in that run).

The log file is the one channel that survives; it carried all 31,310 refusals. So both global write paths now send a TraceType::MemoryLargeAllocation through TraceSender, and TraceCollector symbolizes it and writes one LOG_WARNING before the trace_log insert. Unsymbolized at the send site: e7a58e703cb81 removed direct logging from MemoryTracker because it can deadlock. The pipe record is unchanged.

Only the global tracker is instrumented; per-query drift is already in query_log.memory_usage. adjustOnBackgroundTaskEnd and updateAllocated are excluded by measurement: both write amount, never rss. Best-effort: a full pipe drops the trace, and an allocation on the collector thread is not traced.

Validated by the new test_memory_tracker_large_allocation_trace (both deliveries, the setting, and a stack resolving past the tracker) and 14 gtest cases; removing either detect site, or either half of either site's threshold guard, reddens a different one.


Workflow [PR]
Sync PR [sync-upstream/pr/119527]

Version info

  • Merged into: 26.10.1.229-master (included in 26.10 and later)

groeneai and others added 13 commits September 11, 2026 12:34
…obal memory tracker

A server whose global MemoryTracker::amount has drifted far above its real
memory usage refuses every allocation, down to the zero-byte
CurrentMemoryTracker::check() at connection start, while using a fraction of
its limit. In CI this lands as "Hung check failed, possible deadlock found",
so a real deadlock in the same run is invisible. ClickHouse#118094 and ClickHouse#117738 correct
the counter and ClickHouse#117995 stops the harness calling it a deadlock, but as
ClickHouse#118094 says itself, where the phantom bytes come from is still unknown.

Nothing records the add, for two structural reasons rather than bad luck.
The blocked-Global branch of allocImpl does amount.fetch_add, rss.fetch_add,
updatePeak and CurrentMetrics::add, then returns without ever reaching
commitAllocation, so it emits no hard-limit check, no trace, no ProfileEvent.
Everything that does reach commitAllocation is reported by
incrementAllocationWithoutCheck, whose payload lands in system.trace_log,
the sink the wedge itself breaks: in the measured run, 109 failed trace_log
flushes, 112 metric_log, 109 query_log, and not one memory trace of 1 GiB or
more in the whole run. The one channel that survives is the log file, which
carried all 31,310 refusal messages through the full 14-minute wedge.

So detect a single allocation at or above the new server setting
min_allocation_size_to_log_stack_trace on the two places where the global
amount grows and is not reverted, report it through TraceSender as a new
TraceType::MemoryLargeAllocation, and let TraceCollector symbolize it and
mirror one LOG_ERROR before the trace_log insert, so the stack survives when
the insert does not. This follows the pattern azat established in
e7a58e7, which added MemoryAllocatedWithoutCheck to trace_log and
deliberately removed direct logging from MemoryTracker because it can
deadlock: the send site captures an unsymbolized stack, since
StackTrace::toString takes the symbolizer cache mutex and allocates.

The wire format is deliberately untouched. The record is already 510 of the
512 bytes that keep the pipe write atomic, so the tracker total is read by
the collector at log time and labelled as such rather than carried in the
record, and no field is repurposed.

Traces are budgeted at 10 because symbolizing is expensive and the trigger
repeats. The budget refills only when the setting transitions from 0 to a
nonzero value: the config-reload callback calls the setter on every reload,
so refilling per call would have left no bound at all on a server that
reloads periodically.

The setter refuses a nonzero threshold when no trace collector is running
and warns once, because the collector only exists when trace_log is
configured and clickhouse-local never creates one; without it the setting
could only capture a stack and discard it. It is registered in
collectChangeableServerSettings through its getter so system.server_settings
reports the effective value after such a refusal.

Only the global tracker is instrumented. Process, User and Thread trackers
die with their query and their drift is already visible in
query_log.memory_usage, so instrumenting them would fire once per large
query. adjustOnBackgroundTaskEnd and updateAllocated are left alone because
measurement excludes them: both write amount and never rss, so neither can
produce the inflated rss reading these reports carry.

Default 0 keeps the diagnostic off; 8Gi under tests/config so CI gets it.
This does not fix the drift. It makes the next occurrence carry the stack,
which is the input issue ClickHouse#117681 is missing.

Related: ClickHouse#117681

Co-Authored-By: Claude Opus 5 <[email protected]>
Three corrections to the record TraceCollector writes for
TraceType::MemoryLargeAllocation.

show_addresses_in_stack_traces is an explicit security control, and the new
formatter was the one server-log path that ignored it. Reading it needs a
public accessor: the file-static shouldShowAddress cannot be reused, because
its addr < 4096 carve-out is about fault addresses from a signal handler and a
normalized file offset is not one. With addresses off the frame index and the
symbol are still printed, so the record stays useful.

The symbol lookup was gated on ELF only, while the identical lookup in
TraceLog.cpp allows OS_DARWIN as well and SymbolIndex documents macOS support
(absolute virtual addresses, which is what the trace carries there, since the
normalization in TraceCollector::run is ELF-only). Every frame rendered "?" on
macOS. The guard now matches its sibling verbatim.

MemoryTrackerBlockerInThread::level defaults to VariableContext::Max, which
trace_log documents as meaning "inactive", so the common case printed "Max" to
the one audience this line has. It now prints "none". The old
MEMORY_CONTEXT_UNKNOWN comparison was unreachable for this trace type, because
traceLargeAllocation always passes an engaged optional.
setMinAllocationSizeToLogStackTrace published the new threshold with an
exchange and reset the counter afterwards, so a concurrent allocation could
read the new threshold against the old counter: with the old budget spent the
first traces after activation were dropped, and with it partly spent the
ten-trace bound was exceeded.

Resetting while the threshold is still 0 costs nothing, because the reset only
fires on a 0 -> nonzero transition and no thread can spend budget while the
threshold is 0. A reload that leaves the value unchanged is still not a
transition and still refills nothing.
The memory_context column said "only for Memory/MemoryPeak", which was true
before the new trace type and is not now, since MemoryTracker sets that field
for it as well.

The new trace_type sentence was an adjacent string literal starting with a
backtick, so it concatenated with the previous one.
The gtest cases assert ProfileEvents::MemoryLargeAllocationTraced, which is
incremented upstream of the TraceSender::send, and their fixture never calls
TraceCollector::initialize(), so getTraceLog() is null throughout. Deleting
the symbolize-and-log block left every one of them green, which is the part
the changelog entry promises, and the server-settings plumbing was never
traversed at all.

This automates the end-to-end demonstration instead: the setting as
system.server_settings reports it, the symbolized server-log record, and the
system.trace_log row. A frame is asserted by shape rather than by function
name, since inlining makes a named frame brittle, and the frame text is sliced
to the first record so unrelated log content can neither satisfy nor break the
address assertions.

show_addresses_in_stack_traces is applied at startup only, so the arm that
turns addresses off is a second instance rather than a reload. An integration
test is the right vehicle because it sets server settings by design and needs
only the 256 MiB one PODArray doubling already allocates; a stateless test
could do neither.
Resetting the budget before publishing the threshold fixed program order
only. Both variables were still accessed with memory_order_relaxed, which
orders neither against the other, so on a weakly ordered machine a second
core could observe the new threshold together with the pre-reset budget: on
a 0 -> nonzero re-activation after an earlier activation spent the budget,
such a thread reads large_allocations_traced >= max_large_allocations_traced
and drops the trace. The dropped one is the first, which is the one worth
having, and the class this diagnostic exists for is observed on arm_debug
and arm_release.

The reset store is sequenced before the release store, so a thread that
acquires the new threshold necessarily sees the reset. That pairing is the
whole fix: fetch_add on the budget stays relaxed, since the acquire is what
orders the reset ahead of it, and the getter stays relaxed because its only
caller reports the value rather than synchronizing on it.
It is the only path that reaches traceLargeAllocation without going through
commitAllocation, which is why the detect site is there, but it is not the
only place that can report the allocation: the same branch returns
AllocationTrace(_sample_probability), whose onAlloc sends a MemorySample for
that same allocation whenever total_memory_tracker_sample_probability is set.
The comment claimed the stronger, false thing.
The system.trace_log arm asserted count(), memory_context and max(size) and
never read the trace column, so a row delivered with an empty trace array
satisfied it, while the changelog promises the stack trace is written there.
The server-log arm required only some resolved frame, which
StackTrace::StackTrace or MemoryTracker::traceLargeAllocation satisfies on
its own, and naming the allocation site is the whole point of the diagnostic.

So the existing query now also counts rows whose trace is empty, asserted to
be none, and both instances require a resolved frame outside the tracker's
own frames. That stays a shape assertion rather than a function name, since
inlining makes a named frame brittle; the trigger resolves
Allocator::realloc, PODArrayBase::realloc and GroupArrayNumericImpl::add
past the four tracer frames.

Counts and sizes are deliberately left as bounds: the trigger is a PODArray
doubling sequence, so an exact number would encode the allocator's growth
policy rather than anything this test is about.
The budget's lifetime is the collector's: a trace can only be delivered while
one exists, so refilling it belongs in that object's constructor rather than in
the threshold setter.

Resetting it in setMinAllocationSizeToLogStackTrace put a write to the budget on
the same concurrent path as the detections that spend it. The decision
(size >= threshold) and the spend (fetch_add) are two operations on two words, so
no memory ordering can stop a thread preempted between them from carrying a stale
activation's decision into a freshly refilled budget. Removing the reset from
that path makes the two words never race, which is smaller than making them
coherent.

It also restores the intended bound. The server constructs exactly one collector,
at startup, before the configuration-reload callback can publish any threshold,
so the bound is 10 traces per server run again instead of 10 per switch-on, and
switching the setting off and on no longer yields another 10. The gtest fixture
builds one collector per case, so the suite's exact-count assertions keep working
and --gtest_repeat stays clean.

BudgetRefillsOnlyWhenSwitchedOn becomes BudgetIsNotRaisedByReconfiguration, with
its last expectation inverted: neither re-applying the value (what a reload does)
nor an off/on cycle raises the bound.
min_allocation_size_to_log_stack_trace is documented as the minimum size of an
allocation for which a stack trace is captured, and both detect sites implement
that as size >= threshold. Nothing held them to it: every firing case charges
128 MiB against a 64 MiB threshold, and the only boundary case charges
threshold - 1, so changing both comparisons to a strict one left all nine cases
green. A later cleanup of either comparison would have changed user-visible
behaviour with no test to notice.

The two cases charge exactly the threshold, one per site, because the sites hold
independent copies of the comparison: the blocked-Global branch of allocImpl
returns before commitAllocation, so a single case cannot cover both. Mutating
one comparison at a time confirms the partition is exact -- the allocImpl site
reddens only FiresAtExactlyTheThresholdOnTheBlockedGlobalPath and the
commitAllocation site reddens only FiresAtExactlyTheThreshold, 23 of 24 cases
staying green in each arm.
TraceSender::send only writes the pipe record; the log line and the trace_log
row are produced later by the collector thread. Nothing ordered the query's
return before that thread had run: grep_in_log is a one-shot zgrep, and SYSTEM
FLUSH LOGS flushes what is already enqueued, so a row the collector has not
pushed yet is simply absent from the count. The module passed only because the
trigger reallocates early in a query that then aggregates 30M rows, which is a
timing accident rather than an ordering guarantee, and the flaky check re-runs
new integration tests repeatedly.

The log side now waits for the marker, and the trace_log side re-flushes until
the row appears or a deadline passes. The deadline is what keeps the failure
legible: the loop exits on it too, so a genuinely missing row still fails on
assert int(count) > 0 rather than on a timeout exception.

grep_in_log is narrowed to the live log because the wait tees into
<log>.wait_for_log_line, which the default clickhouse-server.log* glob would
also match; a multi-file zgrep prefixes every line with its filename, and the
frame patterns are anchored at the frame index, so all three log assertions
would stop matching. Narrowing loses nothing here: the record was produced by
the query this test just ran, and the module never restarts a server.

Making the collector's log write unreachable now fails both log-based cases at
the wait itself rather than at an empty grep, so the wait is load-bearing.
The Upgrade check fails a job on any <Error> line in the server log that it
does not explicitly excuse: upgrade_runner.sh filters
clickhouse-server.upgrade.log through 73 fixed-string and 24 BRE exclusions
into grep -Fa "<Error>", and a non-empty result writes the "Error message in
clickhouse-server.log" failure row. This record matches none of those 97
exclusions, and the threshold that arms it is installed unconditionally by
tests/config/install.sh, which both of the upgrade job's configure calls run.
So one qualifying global allocation during the post-upgrade phase would have
reddened the check, here and on master. The trigger is a single large add
rather than a cap breach, and the sub-cap population is the larger one, so the
absence of CIDB rows for the cap-breaching form does not bound it.

Warning is also the level-correct choice: the server is healthy, an operator
has asked to be told when a threshold they set is crossed. Visibility is
unchanged, since the shipped logger level is trace and Poco orders Warning
above Information and Trace, and no <Warning> gate exists in the CI scripts -
the single <Warning> occurrence there is itself an exclusion.

An exclusion line in upgrade_runner.sh was the alternative. It was rejected:
it would grow a hand-maintained list maintainers already carry, and it would
not survive a future generic <Error> gate.

No test changes: the integration module keys on the message text and a
timestamp prefix, never on the level, and no gtest reads the log.
The integration module located the "Single allocation of" marker line and then
iterated the lines below it, so it never read the token carrying the log level.
Mutating the record back to LOG_ERROR therefore left all 3 integration cases and
all 24 gtest cases green, while restoring a record that reddens the Upgrade check
on every PR and on master: tests/config/install.sh installs the threshold
unconditionally, and upgrade_runner.sh greps for <Error> after 97 exclusions,
none of which match this line. ServerSettings.cpp documents the record as written
at Warning level, so the level is part of this change's published contract and
owed an oracle. It is asserted in the shared helper, so one line covers both
instances.

Verified by mutation: with LOG_WARNING at TraceCollector.cpp:260 changed back to
LOG_ERROR and the committed test left unmodified, both log-reading cases fail at
the new assertion and report the offending line, while the case that does not
read the log stays green.

Two comments were also wrong. The one above symbolizeNormalizedTrace claimed that
trace holds addresses already normalized to physical file offsets and that
SymbolIndex::findSymbol expects that form. Neither holds universally: run()
normalizes only frames inside the main object, and only on ELF non-FreeBSD, while
findSymbol documents that it accepts either representation. And
resetLargeAllocationTraceBudget said "Refills", which invites a caller to top the
budget up, the shape BudgetIsNotRaisedByReconfiguration exists to forbid; it
resets, once per collector.

No functional change: the rebuilt binary's Build ID is unchanged.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (6 rounds)

An independent model reviewed this diff cold in six rounds alongside my own review: 17 findings agreed and fixed before publication, the rest declined with evidence, two dropped once measurement showed there was no defect. The ones that changed behaviour or coverage:

Finding Verdict
❌ The new formatter emitted frame addresses even with show_addresses_in_stack_traces disabled, the one path not honouring that control agreed, fixed (new StackTrace::showAddresses())
❌ Tests asserted only the ProfileEvent, incremented before the send, so neither the server-log record nor the system.trace_log row was covered; and the trace_log arm never read trace, so a row without a stack would have passed agreed, fixed (integration test asserting a non-empty stack that resolves past the tracker, every arm proven live)
⚠️ The trace budget was reset inside the setter, so a detection that had read the previous threshold could spend the freshly reset budget: two atomics, two operations, ordering alone could not close it agreed, fixed (reset moved into TraceCollector's constructor, restoring a per-server-run bound)
⚠️ The record was emitted at Error while this change also arms it in shared test configuration, and the upgrade check fails a job on any unexcused <Error> line: 0 of its 97 exclusions match this message agreed, fixed (emitted at Warning; visibility unchanged, the shipped logger.level is trace and nothing gates on <Warning>), then the level itself pinned by an assertion
⚠️ No test distinguished the threshold comparison from a strict one, and the module read an asynchronous collector's outputs one-shot agreed, fixed (an exactly-at-threshold case per detect site; wait for the record, then a bounded re-flush)
💡 Budget exhaustion is silent: the ProfileEvent saturates at 10, so it cannot separate "10 occurred" from "10 traced, N dropped" noted, not blocking (the 8Gi test threshold designs pre-exhaustion out, and when the drift fires the ten traces are the drift)

Also agreed and fixed: symbol lookup gated on ELF only (unnamed frames on macOS), the memory_context column description, and two comments that overstated their scope. Declined with evidence: an exact record count for the trigger (it is a PODArray doubling sequence, so the count would track the allocator's growth policy, not this change).

Session id: cron:clickhouse-review-slot-8:20260911-183900

@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0d32db3]

Summary: ✅


AI Review

Summary

This PR adds the server setting min_allocation_size_to_log_stack_trace, captures unsymbolized stacks for large charges to the global memory tracker on both global-growth paths, mirrors them into the server log, and records them as MemoryLargeAllocation in system.trace_log. Re-reviewing the current head against the full PR diff and prior discussion, I did not find any remaining blocker or major issue; the earlier gaps around startup seeding, charge wording, and system.trace_log documentation are fixed in the current code.

Final Verdict

✅ No new review findings in the current head.

LLVM Coverage Report

Measured on commit 0d32db3.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 217/218 (99.54%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @vitlibar, could you review this? It adds an opt-in server setting min_allocation_size_to_log_stack_trace that reports the stack of a single large allocation charged to the global memory tracker, sent from both paths that grow the global amount (the blocked-Global branch of allocImpl returns before commitAllocation, so that one had no reporter at all), and mirrored to the server log because system.trace_log stops flushing in exactly the wedged state this is meant to diagnose. It follows the pattern of e7a58e7.

@clickhouse-gh clickhouse-gh Bot added the comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... label Sep 11, 2026
Comment thread programs/server/Server.cpp Resolved
min_allocation_size_to_log_stack_trace was applied only from the main config
reloader's updater callback. The ConfigReloader constructor runs that callback for
the first time long after createTraceCollector() has opened the trace pipe, so
everything in between ran with the threshold at 0: the ZooKeeper-include config
reload, the MergeTree metadata arena pool, the file cache factory's default caches
and the DNS cache updater. A runaway global charge on that path could not be
reported by the diagnostic whose only purpose is to attribute it.

Seed the threshold from the startup server settings inside the existing
has_trace_collector block, where the three sibling trace-collector diagnostics
(total_memory_profiler_step, total_memory_tracker_sample_probability,
total_memory_profiler_sample_min_allocation_size) are already armed, and keep the
reloader callback for runtime changes. The remaining blind window is the part of
startup that precedes the collector, where a trace could only be discarded.

Measured on a debug build with the threshold at 1Mi: before this change the first
"Single allocation of" record appears after ConfigReloader's "Config reload
interval set to" line and none precede it; after it, eight of the ten budgeted
records precede that line, the largest 5.05 MiB, coming from MemoryWorker's cgroup
reads, the asynchronous metrics sensors and the config processor's name pool. With
the 8Gi threshold tests/config installs, startup makes no qualifying allocation,
so CI behaviour is unchanged.

Two consequences are documented rather than left implicit. A threshold low enough
to catch ordinary allocations can now spend the per-run budget during startup, and
a trace the collector processes before initializeTraceCollector() attaches the
table reaches the server log only, which already held for the window between the
first reload and that call.

Since startup now applies the threshold, the settings assertion no longer fails
when the reloader's application is deleted, so the integration module gets an
explicit runtime reload case, in both directions. Verified by mutation: with the
reloader call removed, that case fails on the unchanged value while the other
three stay green.
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0d32db382 with master 817a2afd1 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

15 object files changed (+37.38 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/TraceCollector.cpp.o 84.28 KiB 109.21 KiB +24.93 KiB (+29.58%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

424 translation units recompiled, 2915 s compile time in total, 424 of them have a recent master baseline.

Job report

MemoryTrackerLargeAllocationTrace.SilentBelowTheThreshold failed on
Unit tests (amd_llvm_coverage): the counter had gained a record the case
never asked for.

The cases charge through CurrentMemoryTracker. When the running thread has
a ThreadStatus, that batches the charge into untracked memory and flushes a
whole batch as one add, so the tracker sees `pending remainder + size`: a
charge of TRACE_THRESHOLD - 1 reaches the detect site as at least
TRACE_THRESHOLD and traces. gtest_allocation_interceptors.cpp attaches a
MainThreadStatus to the main thread, is compiled only outside sanitizer
builds (`#if !defined(SANITIZER)`) and registers before this fixture, so
the coverage lane charges through the batch while asan/msan/tsan do not.
That makes the failure deterministic per lane rather than flaky.

Flushing the pending remainder before every charge makes the add exactly
`size` whether or not the thread has a ThreadStatus.

Measured with AllocationInterceptors.* added to the filter, which
reproduces the lane locally: before, one spurious record inside
SilentBelowTheThreshold and CI's failure text exactly; after, none there,
with every positive case still firing its own count unchanged.
Comment thread src/Interpreters/TraceCollector.cpp Resolved
groeneai and others added 2 commits September 12, 2026 03:57
The threshold is compared against the size that arrives at the global
tracker's detect sites, and that is one tracker call, not one allocation.
CurrentMemoryTracker::allocImpl accumulates into the thread's
untracked_memory and flushes the whole deferral as a single
MemoryTracker::allocImpl call once it passes untracked_memory_limit
(min of max_untracked_memory and memory_profiler_step), so the reported
size can be a sum attributed to whichever site tipped the batch. The
in-tree note at CurrentMemoryTracker.cpp:97 already records that the
flushed size may not match the original allocation size.

Measured, with the threshold at 64Mi and the per-CPU bound disabled, on
INSERT ... SELECT number FROM numbers(20000000) into a Memory table with
4096-row blocks: at max_untracked_memory = 4Mi the workload traces
nothing, and at 64Mi it emits two records of 67115944 and 67111016 bytes
whose attributed frame is a 32 KiB ColumnVector<UInt64> construction.
Since a flush fires above the limit, reported - limit lower-bounds the
tipping allocation: 7080 and 2152 bytes reported as 64 MiB. The excess is
bounded by untracked_memory_limit in the other direction, so a threshold
well above max_untracked_memory keeps it immaterial; the defect is in the
words, not in the detection.

Reporting an original allocation size instead was rejected: the
diagnostic attributes a step in the global tracked total, which the
charge is what moves, and the individual sizes are already gone at the
detect sites. The setting name is kept for symmetry with
min_allocation_size_to_throw_on_memory_limit.

No behaviour change. The setting description now states the batching and
its bound, and the integration test's log marker follows the new text.
Its rationale no longer says blocked allocations are untraced either,
which is what this setting exists to stop being true; it names the limit
check they skip instead. The symbolizer's comment loses a universal it
never had: normalization applies to main-object frames on ELF platforms
other than FreeBSD, not everywhere.

Co-Authored-By: Claude Opus 5 <[email protected]>
Each detect site carries its own copy of `threshold && size >= threshold`,
and the negatives only covered one of them, so three of the four possible
mutants survived the suite. Measured, each mutant applied to one site
only and run as AllocationInterceptors.*:MemoryTrackerLargeAllocationTrace*:

  blocked site, size comparison dropped  -> 1 failed / 26 passed
  blocked site, enabled check dropped    -> 1 failed / 26 passed
  commitAllocation, size dropped         -> 7 failed / 20 passed (was covered)
  commitAllocation, enabled check dropped-> 2 failed / 25 passed

The three added cases are the sole killers of the first, second and fourth.
IsInertByDefault looked like it covered the fourth and does not: the trace
budget is a process-wide counter that only a new TraceCollector refills,
so by the time the Defaults suite runs the fixture has spent it and
nothing can trace whatever the guard says. That case is alive only when
run in isolation, which is why the two disabled-path cases live in the
fixture and switch the threshold off themselves rather than relying on
the default.

Filter matters: MemoryTracker* alone excludes the suite that installs a
MainThreadStatus, and without one CurrentMemoryTracker does not batch, so
the charges are not the ones CI makes.

Co-Authored-By: Claude Opus 5 <[email protected]>
The comment said normalized offsets are what StackTrace::toString cannot
resolve. That was never measured, and it is not obvious: forEachFrame
treats each entry as a virtual address, finds the containing object and
subtracts its base before calling SymbolIndex::findSymbol, so whether a
file offset survives that depends on where the main object is mapped.
What the reader needs is true either way, and is what is left: the frames
may already be offsets, and findSymbol takes either representation.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai changed the title Report the stack trace of a single large allocation charged to the global memory tracker Report the stack trace of a large charge to the global memory tracker Sep 12, 2026
Comment thread src/Interpreters/TraceLog.cpp Resolved
groeneai and others added 3 commits September 12, 2026 05:37
The table takes rows from every producer named in its trace_type column,
and this branch adds one more (MemoryLargeAllocation), but the table's own
description still named the sampling query profiler alone. The per-column
documentation was updated for the new type; the higher-level descriptions
were not.

Three surfaces carried that claim, all hand-maintained:

- SystemLog.h, whose string becomes the system.tables comment for the table
  and seeds a newly generated documentation page;
- the description frontmatter and the "## Description" body of
  trace_log.mdx, which utils/generate-system-tables-docs leaves alone on an
  existing page: update_doc_file only replaces the block between the
  AUTOGENERATED markers, which is the column list;
- the "See Also" entry for the table on the stack_trace.mdx page.

The new wording points at trace_type instead of enumerating the producers,
so the next trace type does not make it stale again. The generated column
list is deliberately untouched: the nightly docs job runs that generator
against a built binary and picks the new enum value up from there.

Measured on a fresh server, SELECT comment FROM system.tables WHERE
database = 'system' AND name = 'trace_log':

  master (build id c1396c04a6abd5a15c32b14c3416201348533577)
    Contains stack traces collected by the sampling query profiler.
  this branch (build id 100d1b613f4847cd6b47960c0cf044f3c4e23da6)
    Contains stack traces collected by the sampling query profiler and by
    the other sources named in the trace_type column.

Co-Authored-By: Claude Opus 5 <[email protected]>
The comment named Memory and MemorySample. MemoryPeak and
MemoryAllocatedWithoutCheck already set the field as well, and this branch
adds MemoryLargeAllocation, whose value is a charge to the global memory
tracker rather than one allocation's size. An enumeration inside the struct
drifts every time a trace type is added, so it is replaced by the property
that does not: the memory trace types set it and the others leave it zero.
The authoritative per-type list stays where it is published from,
getColumnsDescription.

Co-Authored-By: Claude Opus 5 <[email protected]>
The sentence this branch extends claimed "for other trace types is 0", which
is false for JemallocSample, and it called MemoryPeak's value the amount of
memory allocated, which it is not. Every sender that fills the field:

  Memory                       MemoryTracker.cpp  .size = size
  MemoryAllocatedWithoutCheck  MemoryTracker.cpp  .size = size
  MemorySample                 MemoryTracker.cpp  .size = size, and -size on free
  JemallocSample               Jemalloc.cpp       .size = usize, and -usize on free
  MemoryPeak                   MemoryTracker.cpp  .size = will_be, the value just
                                                  accepted by updatePeak, so the
                                                  tracker's new total, not one
                                                  allocation
  MemoryLargeAllocation        MemoryTracker.cpp  .size = size, one charge to the
                                                  global tracker
  ProfileEvent                 ProfileEvents.cpp  fills increment, not size

Real, CPU and Instrumentation never fill it, so zero stays correct for the
rest.

Co-Authored-By: Claude Opus 5 <[email protected]>

@alexey-milovidov alexey-milovidov 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.

Good idea.

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit 71e0247 Sep 19, 2026
175 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
@azat

azat commented Sep 21, 2026

Copy link
Copy Markdown
Member

@alexey-milovidov do we really need this, maybe better to replace it with already existing MemoryAllocatedWithoutCheck, but allow to collect those trace events with blocked MemoryTracker as well?

Or another option is to add an option to log stacks when MemoryPeak for total_memory_tracked is increased, and/or allow to write those trace events even with blocked memory tracker.

Plus I am not sure how helpful it is, i.e. how often do we have one huge allocation, instead of small many.

And also we have jemalloc_flush_profile_on_memory_exceeded (though works only with jemalloc, i.e. sanitizers are not covered)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Measurements, from one debug server (26.10.1.1) with min_allocation_size_to_log_stack_trace=64Mi, total_memory_profiler_step=1Mi.

MemoryAllocatedWithoutCheck / MemoryPeak. Both are sent from MemoryTracker::commitAllocation, and the blocked-Global branch of allocImpl returns before reaching it (it bumps amount and rss, calls updatePeak(..., log_memory_usage=false) and the metric, then returns). So collecting them "with blocked MemoryTracker as well" is not a flag that is off, it is the plumbing this PR added at that site. Three further gaps:

  • The populations are nearly disjoint: incrementAllocationWithoutCheck runs only when the charge skipped the check (memory_limit_exceeded_ignored || !enforce_memory_limit), so the enforced 64 MiB to 1 GiB charges below cannot reach it. Same run: 6 MemoryLargeAllocation rows, 0 MemoryAllocatedWithoutCheck rows, while its ProfileEvents counted 207,432 charges / 19.23 GiB, mean 97 KiB. Its threshold is a hardcoded 16 MiB.
  • Its trace is suppressed under MemoryTrackerUntrackedAllocationsBlockerInThread, i.e. on the system-log enqueues (SystemLogBase.h:148).
  • It reaches only system.trace_log, the sink that fails in the state this targets: in the run that motivated it, Failed to flush system log system.trace_log x109 while the log file carried all 31,310 refusals. Hence the one LOG_WARNING before the insert.

MemoryPeak additionally requires allocation_traced, i.e. a total_memory_profiler_step crossing in the same call.

jemalloc. Beyond sanitizers: jemalloc_enable_global_profiler defaults to false, so prof.active is false and the flush is a no-op unless enabled beforehand. And a heap profile attributes live allocations, while that run had 160.98 GiB tracked against 1.71 GiB RSS, so there is nothing for it to attribute. Those bytes are accounting, not memory.

One huge allocation vs many small. Your doubt holds for distributed growth:

query peak single global charges >= 64 MiB
GROUP BY over 20M keys 1.85 GiB 0 (largest charge seen 17.75 MiB)
uniqExact over 40M 1.89 GiB 0
groupArray(number) over 80M 2.00 GiB 6: 64, 128, 256, 512 MiB, 1 GiB, 1 GiB

Charges arrive as per-thread batches (max_untracked_memory, 4 MiB), so many-small comes in 4 MiB pieces and never trips 64 MiB; one geometrically growing buffer does, and the stack names it (GroupArrayNumericImpl::add -> PODArrayBase::realloc -> Allocator::realloc). The scope is one call site charging a big block at once, nothing wider.

No attachment to the extra trace type: happy to fold it into MemoryAllocatedWithoutCheck with a configurable threshold and drop MemoryLargeAllocation, or to add stacks on a total_memory_tracked peak increase instead, whichever you prefer.

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

Labels

can be tested Allows running workflows for external contributors comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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