Repository navigation
Fix the global memory tracker getting pinned at the previous peak after a one-shot correction to resident memory - #117738
alexey-milovidov wants to merge 51 commits into
Conversation
…, not resident memory `MemoryWorker` corrects the global `MemoryTracker` once on its first tick and whenever the tracker goes negative (memory allocated before the tracker was initialized and freed later). Since #83981 that one-shot correction used `resident` (jemalloc `stats.resident` or the cgroup memory usage). Right after a large query finishes, `resident` is still close to the query's peak, because jemalloc keeps the freed pages dirty until they decay, so the tracker got pinned at that peak. Nothing lowers it afterwards with the default `memory_worker_correct_memory_tracker = 0`, so every allocation, including the zero-byte check at connection start, failed with `MEMORY_LIMIT_EXCEEDED` until the (dynamic) hard limit rose above the stale value. The `rss` side of the check is refreshed on every tick, which is why only the "would use" side of the message was frozen. Use jemalloc `stats.allocated` for the one-shot corrections, which is the quantity the tracker accumulates. The continuous correction enabled by `memory_worker_correct_memory_tracker` keeps using `resident`, as it is re-applied on every tick and cannot get stuck. Add a gtest that frees a lot of memory, drives the tracker negative and checks that the worker re-baselines it near the live allocations rather than near the resident memory. Closes: #117681
|
Workflow [PR], commit [4bdd095] Summary: ❌
AI ReviewSummaryThe change prevents one-shot Missing context / blind spots
Final VerdictStatus: ✅ Approve |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units23 translation units recompiled, 145 s compile time in total, 23 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
…mory-usage-in-total-limit-check
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117738&sha=d0ba6cd869c7df8a833bc583459b26c11969dd46&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%206%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. The job failed with
|
|
The tree that failed predates the fix, so there is nothing new to author here. Placement. The job's own log records The two The leak arm is named by the interval rather than by victim identity: the two Rate, measured now on On the master history. With So the answer to the conditional is a link and not a PR: #117564, merged 2026-09-03T13:07:47Z. There is still no open issue for the class, and I have not filed one because the fix is merged and post-fix trees are at zero; say so if you would rather have one on the record. |
…mory-usage-in-total-limit-check
…the cgroup-backed source The one-shot re-baseline of the global `MemoryTracker` now goes through `MemoryWorker::getJemallocAllocated`, which always advances the jemalloc statistics epoch before reading `stats.allocated`, instead of doing so only when the memory usage source is not jemalloc. The previous test used `use_cgroup = false`, so it exercised only the `MemoryUsageSource::Jemalloc` path, where `getMemoryUsage` refreshes the epoch anyway; the shipped cgroup-backed configuration was uncovered. The test body is now shared by two tests, one per memory usage source. The cgroup one is skipped where no cgroup memory controller is available. The last epoch refresh done by the test itself happens while the memory is still live, so a worker that does not refresh the epoch re-baselines the tracker to the stale peak snapshot and the cgroup test fails (verified with the refresh removed: corrected to 654 MiB instead of 152 MiB). Dirty-page decay is disabled per arena for the duration of the test, because jemalloc's background threads purged the freed pages within the test's runtime often enough to break the resident-vs-allocated premise. 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]>
…mory-usage-in-total-limit-check Conflict in `src/Common/MemoryWorker.cpp` with f4e7b31 (`MemoryUsage{resident, allocated}`): the one-shot re-baseline keeps `getJemallocAllocated` with jemalloc, and falls back to master's `memory_usage.allocated` (sanitizer allocator bytes, otherwise resident) in builds without jemalloc.
`CurrentMemoryTracker::free` on the gtest main thread (which has a `MainThreadStatus`) also charged the thread's own tracker, and the worker only re-baselines `total_memory_tracker`, so the thread tracker stayed negative for later tests in `unit_tests_dbms`. Adjust the global tracker from a helper thread without `ThreadStatus`, where `CurrentMemoryTracker` accounts to `total_memory_tracker` directly. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 Merged About the previous reds: |
…mory-usage-in-total-limit-check
…n builds without jemalloc Builds without jemalloc and without a sanitizer (`ENABLE_JEMALLOC=0`, LoongArch) have no counter of live allocations: `memory_usage.allocated` is `resident` there, so correcting a negative tracker to it could pin the tracker near the RSS peak of a finished query. Reset a negative tracker to zero instead; keep `resident` only for the first run at startup. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…acker in builds without jemalloc `updateResidentMemoryThread` sleeps for one `rss_update_period_ms` before its first tick, so memory can be allocated and freed before the first run; in builds without jemalloc and without a sanitizer `memory_usage.allocated` is `resident`, which could still pin the tracker at a stale peak. Do not re-baseline on the first run there; a negative tracker is still reset to zero. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged master and addressed the remaining review thread (the non-jemalloc, non-sanitizer path no longer re-baselines the tracker to About the red |
The started `MemoryWorker` publishes the fixture's resident memory (which deliberately includes hundreds of MiB of dirty freed pages) via `MemoryTracker::updateRSS`. Nothing refreshes it after the worker is destroyed in the gtest binary, and `MemoryTracker::resetCounters` does not reset it, so the stale RSS could fail the hard limit check in `MemoryTracker::allocImpl` in later tests. Restore the previous value with a scope guard declared before the worker and the allocations, so it runs on every exit path, including skips and failed assertions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 The red |
|
🕵 Merged the latest The red checks on
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117738&sha=c565a8cc94a9dd0a5261b8d2a40994f2b3540acf&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. |
|
This is the row-policy route again (#112891): with From this run (tree
It is the same shape as the 2026-10-23 master run of this test. #114955 covers it in |
|
🕵 Thanks, @groeneai. The On |
|
🕵 Merged the latest The only red check on |
|
🕵 Merged the latest |
|
🕵 Merged the latest On |
|
🕵 Merged the latest Red checks on
|
|
🕵 Merged the latest The only red check on |
|
🕵 Merged the latest Red checks on
There are no unresolved review threads. The PR is waiting for a human review and merge decision. |
|
🕵 Merged the latest The only red check on |
|
🕵 Merged the latest Red checks on
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117738&sha=a07b289ad8179d88c10552564e08a39f4f7d2ca4&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29 ( There are no unresolved review threads, and the PR is approved by the bot review. It still needs a human to merge it and to accept the inconclusive bugfix validation. |
|
Acknowledged. I'm investigating the |
|
Dear @azat, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
This is a real regression on macOS: since #125794 the watcher no longer records the unlink of a name whose file keeps another link, so |
05319_file_log_rename_in_reused_inode timed out in Fast test (arm_darwin) of ClickHouse#117738: one macOS scan saw a.csv gone and b.csv, moved in from a hard link outside the directory, with the same inode, diffed them as MOVED_FROM a.csv + MOVED_TO b.csv, and StorageFileLog kept a.csv's offset, skipping rows of b.csv. ClickHouse#123593 made is_rename refuse a name in deleted_files as a rename source. Before ClickHouse#125794 every NOTE_DELETE of a watched descriptor put its name there; ClickHouse#125794 (4d75ef8) returns early while the file still has links, because kqueue reports an unlink of any name to every descriptor of the file and the scan has to find which name went away (hidden excluded aliases of 05316_file_log_globs). When the remaining link is outside the directory, nothing recorded the unlink any more. Record the inode in that branch (unlinked_inodes), and in is_rename refuse the pair when the inode's current name matches the path: the scan lists every matching name and is_rename requires one listed name per side, so such a name was not a link of the file at the last scan and the file came back, i.e. it is new here, as on Linux (an IN_MOVED_TO without its IN_MOVED_FROM is ADDED). An excluded current name can be a hidden alias and keeps ClickHouse#125794's behaviour. The set lives next to deleted_files: kept across discarded and failed passes, cleared after a committed one, the first snapshot included (its listing already reflects every unlink recorded before it, and it pairs nothing). The unlink is drained before the diff (scanFilesAndUpdateWatches drains before syncFileWatches closes descriptors), so the decision does not depend on scan timing. The test gains the same steps in one process so a macOS scan sees the unlink and the move-in together; the new content is longer than c.csv's offset, so a carried- over offset gives wrong rows (checked on Linux with a same-inode rename, which keeps the offset: only 110 is read). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #117681
Related: #83981
MemoryWorkercorrects the globalMemoryTrackeronce on its first tick and whenever the tracker goes negative (memory allocated before the tracker was initialized and freed later). Since #83981 that one-shot correction usedresident(jemallocstats.residentor the cgroup memory usage). Right after a large query finishes,residentis still close to the query's peak because jemalloc keeps the freed pages dirty until they decay, so the tracker got pinned at that peak, and with the defaultmemory_worker_correct_memory_tracker = 0nothing lowers it afterwards. Every allocation, including the zero-byte check at connection start, then failed withMEMORY_LIMIT_EXCEEDEDuntil the dynamic hard limit rose above the stale value. This is the picture from the issue: the "would use" side of the message frozen at the previous peak, whilecurrent RSSandmaximumkept moving, because therssside is refreshed on every tick.The one-shot corrections now use jemalloc
stats.allocated, which is the quantity the tracker accumulates (this is also what the code did before #83981). The continuous correction enabled bymemory_worker_correct_memory_trackerkeeps usingresident, as it is re-applied on every tick and cannot get stuck.Builds without jemalloc and without a sanitizer (
ENABLE_JEMALLOC=0, LoongArch) have no counter of live allocations, so there the first-tick correction is skipped and a negative tracker is reset to zero; the description ofmemory_worker_correct_memory_trackersays so.A gtest frees a lot of memory, drives the tracker negative and checks that the worker re-baselines it near the live allocations rather than near the resident memory. Without the fix it fails with the tracker corrected to 658 MiB while live allocations were 1.6 MiB.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix the server rejecting all queries with
MEMORY_LIMIT_EXCEEDEDfor minutes after a large query: when the global memory tracker went transiently negative, the background memory worker re-baselined it to the resident memory, which right after a large query is still close to the query's peak, and nothing lowered it afterwards. The tracker is now re-baselined to jemalloc's live allocations.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/117738]