Repository navigation
Correct the global memory tracker from a measurement by default - #118094
Conversation
`memory_worker_correct_memory_tracker` has been `0` since it was introduced in #75714, which leaves the global `MemoryTracker` a pure counter: `MemoryWorker` refreshes only `rss` on its tick and rewrites `amount` on its first tick and whenever the tracker goes negative. An upward drift is therefore permanent for the lifetime of the process — the memory it describes has already been freed, so no later deallocation can work it off. Once the drift alone exceeds `max_server_memory_usage`, every allocation fails, down to the zero-byte `CurrentMemoryTracker::check` at the start of a connection, and the server rejects every query while using a fraction of its limit. That is not hypothetical: it accounts for 10 of the 21 hung-check failures carrying a memory-limit message in the last 30 days of `default.checks`, and for two open issues. In `Stress test (arm_release)` on master `75247055068ba70941661c930840ee625a991adc` the tracker read `164.75 GiB`, unchanged for the six minutes until the process was killed, while `current RSS` was `7.16 GiB` against a limit of `47.64 GiB`. The measurement the correction uses is the same quantity the hard-limit check already enforces through its `will_be_rss > current_hard_limit` branch, so making `amount` agree with it cannot reject an allocation that is accepted today; it can only stop rejecting allocations that no memory justifies. The drift stays observable: `MemoryTrackingUncorrected` keeps the uncorrected value, so its difference from `MemoryTracking` is the drift accumulated so far.
|
Workflow [PR], commit [a0ebc8f] Summary: ✅
AI ReviewSummaryThis PR flips Missing context / blind spots
Findings
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit a0ebc8f.
Changed lines: Changed C/C++ lines covered: 37/53 (69.81%) · Uncovered code |
Build profile diff (arm_release)Commit See the job log for details. |
…r-correct-memory-tracker
With `memory_worker_correct_memory_tracker` enabled by default, the value of the global memory tracker is no longer a plain count of allocations: the background memory worker rewrites it on every tick from a measurement of the memory the process really uses. The user-visible descriptions and diagnostics still called it "allocated memory", which would mislead anyone reading `system.metrics`, `system.metric_log`, an alert built on them, or the log lines of `SYSTEM ALLOCATE MEMORY` / `SYSTEM FREE MEMORY` and of the Keeper soft memory limit. Say "tracked" instead, and point at `MemoryTrackingUncorrected` - which is the value with no corrections applied - for the raw counter, so that the difference between the two metrics is documented as the accumulated accounting drift. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`tests/integration/test_MemoryTracking` checks that the global memory tracker is an exact counter of allocations, so it depends on nothing rewriting the tracker from the measured memory usage. Correcting it on every tick is now the default, which is why the test started failing: pin `memory_worker_correct_memory_tracker` to `0` there, so it keeps checking the counter-only path explicitly rather than by relying on a default. Add a sibling instance with the correction enabled and a test for the new default: `MemoryTracking` follows the measurement (its value changes even between two identical samples of the workload), while `MemoryTrackingUncorrected` keeps the raw counter and returns to its baseline between the queries. The test skips itself when the memory worker has no source of memory usage information, because then it does not start and there is nothing to correct. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…r-correct-memory-tracker
`MemoryTrackingUncorrected` was only written by `MemoryTracker::updateAllocated`, so with `memory_worker_correct_memory_tracker = 0` (or on any tick that does not correct the tracker) the metric stopped moving after the first tick instead of being the plain counter of allocations its description promises. The worker now calls the new `MemoryTracker::updateUncorrected` on the ticks that do not correct the tracker, so the metric is a snapshot of the plain counter that is at most one tick old in both modes. The descriptions of the metric and of the setting say so explicitly. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The previous check `len(set(tracking)) > 1` could be satisfied by background allocations on the counter-only path as well. The test now relies on two events that never go through the memory tracker: jemalloc retaining the pages a query freed as dirty pages, and `SYSTEM JEMALLOC PURGE` giving them back to the OS. Only the correction can make `MemoryTracking` follow them, so the gap `MemoryTracking - MemoryTrackingUncorrected` has to grow by more than 64 MiB after the query and shrink by more than 64 MiB after the purge, while `MemoryTrackingUncorrected` stays within 16 MiB of its baseline. Measured with the correction enabled: `MemoryTracking` 168 MB -> 846 MB -> 169 MB across the query and the purge, `MemoryTrackingUncorrected` 113 MB throughout. Control run with the correction disabled on the same instance: the gap stays constant to within 64 bytes and `MemoryTracking` ignores the purge, so the test fails exactly on the intended assertion. The check of the raw counter is a separate test, `test_uncorrected_counter_is_preserved`, which runs in every build; the measurement check skips itself without jemalloc or on a low memory system where jemalloc does not retain freed pages. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…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]>
# Conflicts: # src/Common/MemoryWorker.cpp
…r-correct-memory-tracker
…sh without correction The difference between `MemoryTracking` and `MemoryTrackingUncorrected` is not only accounting drift once `MemoryTracking` follows a measurement: it also includes memory that never went through the counter, such as pages retained by the allocator. Add `test_uncorrected_counter_is_refreshed_without_correction` on `node`, where the correction is disabled, so the `MemoryTracker::updateUncorrected` path of `MemoryWorker` is exercised: a `Memory` table holds about 200 MiB, and `MemoryTrackingUncorrected` must move together with `MemoryTracking`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…re_external_order_group_by_for_server` With `memory_worker_correct_memory_tracker` enabled by default, the unspilled `ORDER BY` in `test_max_bytes_ratio_before_external_sort[server]` did not hit `max_server_memory_usage` on `arm_binary`: the query tracked 11.92 GiB of allocations, but the worker corrected the global tracker down to the measured usage, which stayed below 10 GiB. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118094&sha=27ebea1f2f526af9d784895959bd4e491d477c95&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%202%2F4%29 #118094 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
|
||
| The global memory tracker is a counter: allocations add to it and deallocations subtract from it. Any accounting asymmetry stays in it for the lifetime of the process, because nothing else lowers it, and an upward drift is never worked off — the memory it describes has already been freed. Once the drift alone exceeds `max_server_memory_usage`, every allocation fails, down to the zero-byte check at the start of a connection, and the server rejects all queries while using a fraction of its limit. Correcting from a measurement bounds the lifetime of such a drift to one tick of the worker (`memory_worker_period_ms`, by default 50 ms when reading from cgroups and 100 ms when reading from jemalloc). | ||
|
|
||
| The correction does not hide the drift. `MemoryTrackingUncorrected` keeps the value the tracker would have had with no corrections applied (a snapshot of the plain counter, refreshed on every tick of the worker), so `MemoryTrackingUncorrected - MemoryTracking` is the drift accumulated so far. |
There was a problem hiding this comment.
CurrentMetrics.cpp was fixed to describe this as the current gap between the raw counter and measured usage, but the setting text here still says MemoryTrackingUncorrected - MemoryTracking is "the drift accumulated so far". That is no longer the contract: the gap also includes memory that never went through the counter at all, such as allocator-retained pages, and test_correction_follows_measurement relies on exactly that. Leaving this wording here will publish the old meaning through system.server_settings / generated docs and mislead operators. Please mirror the CurrentMetrics wording and describe it as the current gap, not pure drift.
| # move at all (the metric is refreshed only by the worker, so a value that never changes | ||
| # between samples would go unnoticed here, see the next test) or run away by hundreds of | ||
| # megabytes. Allow a few megabytes for what the server allocates in the background. | ||
| assert spread < 16 * MiB |
There was a problem hiding this comment.
This still does not positively prove that MemoryTrackingUncorrected is refreshed in the default-on path. If MemoryTracker::updateAllocated stopped updating that metric and left it frozen at the first tick, both checks on node_corrected would still pass: spread < 16 * MiB accepts a constant series here, and test_correction_follows_measurement only asserts that the metric does not react to retained pages / purge. The new node test covers updateUncorrected, but there is still no sibling assertion that on node_corrected the metric rises and falls with a live tracked allocation. Please add one positive check for that path as well (for example by holding a Memory table live on node_corrected and asserting MemoryTrackingUncorrected moves with it).
azat
left a comment
There was a problem hiding this comment.
@alexey-milovidov I am not sure that this is a good idea
I looked though the refs, and:
- #117681 - I am not sure that it is correct - #117681 (comment)
- #113060 - is about
max_memory_usage_for_user - others not related to incorrect accounting for total tracker
And even if there are issues with tracking, it is better to fix them, since this correction can also create problems, like this one #127054. Sure we can fix it, but I would prefer to remove/disable this correction instead.
Resolve the conflicts in `MemoryWorker.cpp` and `ServerSettings.cpp`. 26.8 lacks #118094: `getMemoryUsage` returns a plain resident value (no `MemoryUsage` struct) and `memory_worker_correct_memory_tracker` is off by default. The fix is adapted inline: whenever the memory worker corrects the global memory tracker in a jemalloc build, it uses the maximum of the measured resident memory and jemalloc `stats.allocated`, refreshing the jemalloc `epoch` when the measurement came from cgroups. The setting description gets the same note as in the original PR. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #117681
Related: #113060
Related: #117738
Related: #117995
Related: #75714
Related: #83981
Change the default of
memory_worker_correct_memory_trackerfrom0to1, so thebackground memory worker re-baselines the global memory tracker from a measurement on every
tick instead of only on its first tick and when the tracker goes negative.
What goes wrong today
The global
MemoryTrackeris a counter.MemoryTracker::allocImpladds the allocation sizeto
amount,MemoryTracker::freesubtracts it, and nothing else lowers it.MemoryWorkerrepublishes
rsson every tick (MemoryTracker::updateRSS) but rewritesamountonly intwo cases:
A drift downwards is therefore self-healing (the tracker goes negative and gets
re-baselined), and a drift upwards is permanent for the lifetime of the process: the
memory it describes has already been freed, so no later deallocation will ever work it off.
Once the drift alone exceeds
max_server_memory_usage, every allocation fails — down to thezero-byte
CurrentMemoryTracker::checkat the start of a connection — and the serverrefuses every query while using a fraction of its limit.
The case
Stress test (arm_release)on master75247055068ba70941661c930840ee625a991adc(report),
which is what #117995 is about:
Reading the artifacts of that run:
current RSSstayed between7.12and7.87 GiBagainstmaximum: 47.64 GiBfor thewhole six minutes until the process was killed. The machine was never near its limit.
metric_log.tsvsamplesCurrentMetric_MemoryTrackingonce a second:0.7 – 1.2 GiBfor the whole stress phase, last row
03:10:29 → 0.733 GiB— the last one the servermanaged to flush before the wedge.
MemoryTrackerUtils: Lower number of threads for query to Nishard_limit - total_memory_tracker.get(), so it samples the tracker for free:10 (16 requested)continuously up to03:10:50.704548, then1 (16 requested)from03:10:52.070325on — and1meansfree_memory <= 0. The first step landed inside a1.4 s window.
03:10:52.275727, already readswould use 100.84 GiB. At03:11:00.407895it reads164.78 GiB— one step of63.99 GiBbetween two messages220 ms apart, with
current RSSunchanged.1 GiB, and there is nobad_allocorCANNOT_ALLOCATE_MEMORYanywhere in the server log. Nothing was allocated, and nothingfailed to be allocated.
164.75 – 164.79 GiBin all 181 connection attempts ofthe hung check, while
current RSSkeeps moving underneath it. The onlyCorrecting the value of global memory trackerline in the whole log is thefirst_runone at server start.
This is not a one-off. It accounts for 10 of the 21 hung-check failures carrying a
memory-limit message in the last 30 days of
default.checks, always with the same shape —the tracked value far above both the real usage and, in several cases, the memory of the
machine:
Outside CI the same failure is reported in
#117681 (378 consecutive queries refused over
three minutes,
38.45 GiBtracked against7.4 GiBresident, recovering on its own onlywhen the dynamic hard limit finally rose above the stale value) and, for the per-user
tracker, in #113060 (
162.62 GiBtracked fora user whose queries were using
1.17 GiB).Why the correction cannot make the limit stricter
The global hard-limit check is an
ORover two quantities:if (unlikely(current_hard_limit && (will_be > current_hard_limit || (level == VariableContext::Global && will_be_rss > current_hard_limit))))will_becomes fromamount,will_be_rssfromrss— andrssis already the measuredresident memory, published by the same
MemoryWorkertick that would now also publishamount(updateRSS(speculative_rss),speculative_rss >= resident). Both counters aremoved by exactly the same increments between ticks: the
Globalbranches ofallocImplandfreeadd to and subtract from both.So after this change
amount == resident <= rss, and the second operand of theORalreadycovers everything the first one could now trigger. The change cannot reject an allocation
that is accepted today. It can only stop rejecting allocations that no memory justifies.
What it does change is the meaning of the reported number:
MemoryTrackingbecomes themeasured usage (
anon + sock + non-reclaimable kernelfrom the cgroup, or jemalloc'sstats.residentwithout cgroups) rather than an accumulated count of allocations, and thesame goes for everything reading
total_memory_tracker.get()— the "would use" side of theerror message,
getMostStrictAvailableSystemMemory(query thread autoscaling), theovercommit ratio. In every one of those the measured value is the one you actually want.
The correction does not hide the drift either:
MemoryTrackingUncorrected(added for thispurpose in #75935) keeps the value the tracker
would have had with no corrections applied, so
MemoryTrackingUncorrected - MemoryTrackingis the accumulated drift — a number you can graph and alert on, instead of a server that
stops answering.
The cost is one
exchangeplus twoCurrentMetrics::setper tick — 50 ms with cgroups,100 ms with jemalloc; with the correction disabled, one
loadand oneCurrentMetrics::set.Tests and the meaning of the metric
tests/integration/test_MemoryTrackingchecks that the global tracker is an exact counter ofallocations, so it now pins
memory_worker_correct_memory_trackerto0and keeps checkingthat path explicitly. A sibling instance with the default configuration checks the other one
with two events that never go through the tracker: jemalloc retaining the pages a query freed
as dirty pages, and
SYSTEM JEMALLOC PURGEgiving them back to the OS. Only the correctioncan make
MemoryTrackingfollow them (measured:168 MB -> 846 MB -> 169 MBacross thequery and the purge), while
MemoryTrackingUncorrectedkeeps the raw counter (113 MBthroughout). A control run with the correction disabled on the same instance fails exactly
on that assertion: there the gap between the two metrics stays constant to within 64 bytes.
MemoryTrackingUncorrectedused to be written only when the tracker was corrected, so withthe correction disabled it stopped moving after the first tick. The worker now refreshes it
on every tick in both modes, so it is a snapshot of the plain counter that is at most one
tick old, and its description says so.
Because the value stops being a count of allocations, the strings that described it as
"allocated memory" are updated as well: the descriptions of
MemoryTrackingandMemoryTrackingUncorrected(and thereforesystem.metricsandsystem.metric_log), and thediagnostics that print
total_memory_tracker.get()inSYSTEM ALLOCATE MEMORY/SYSTEM FREE MEMORYand in the Keeper soft memory limit warning. They now say "tracked" andpoint at
MemoryTrackingUncorrectedfor the raw counter.What this does not do
It does not fix whatever produces the drift, and it should not be read as a reason not to.
Where the phantom bytes come from is still unknown: they arrive suddenly, in one or two very
large steps, with no matching RSS movement and no failed allocation, and across 40 days of
default.checksthe values cluster at real usage plus a multiple of about32 GiB.#117681 tracks it, and with this change the
size of the drift finally becomes a metric rather than an anecdote.
It is also independent of #117738, which fixes
the one-shot correction (the
first_run/ negative-tracker path) to use jemallocstats.allocated, because a one-shot re-baseline toresidentgets stuck on jemalloc's notyet decayed dirty pages. The continuous correction is re-applied every tick and cannot get
stuck, which is why it keeps using
resident. The two touch different files and can bemerged in either order.
A note for @azat
You did not choose this default — the setting was born as
0in#75714 and has never been changed — but you own
most of what has been done since to make the tracker exact
(#84946,
#106055,
#83607), and
#83981 is the reason the correction reads the
cgroup rather than jemalloc
allocated, which is exactly the property the argument aboverelies on. The claim of this PR is only that the counter is not exact in practice, and that
when it is wrong there is currently nothing to bring it back, so the server stays broken
until it is restarted.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The background memory worker now corrects the global memory tracker from the real memory usage on every tick (server setting
memory_worker_correct_memory_tracker, enabled by default). Previously the tracker was a pure counter that was re-baselined only at startup and when it went negative, so any accounting drift upwards was permanent: servers were observed refusing every query withMEMORY_LIMIT_EXCEEDED, reporting more than 100 GiB in use while actually using 7 GiB, until they were restarted. The drift itself remains visible as the difference between theMemoryTrackingUncorrectedandMemoryTrackingmetrics.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/118094]
Version info
26.10.1.864-master(included in26.10and later)