Repository navigation
Improve memory tracking accuracy and coverage - #98915
Conversation
Fix several sources of tracking drift: rollback accounting on failed allocations in `operator new`, `Allocator::alloc`, `AllocatorWithMemoryTracking`, and `SystemAllocatedMemoryHolder`; fix `realloc` failure losing old allocation accounting; fix off-by-one in global `MemoryTracker::allocImpl` where `fetch_add` return value was used as post-addition; fix `nallocx(0)` UB causing negative drift from `malloc(0)`/`free` asymmetry. Extend tracking coverage to `strdup`/`strndup`, `getaddrinfo`/`freeaddrinfo`, `io_uring` ring buffers, and `mmap`/`munmap` in `MMappedFileDescriptor`. Add `isTotalMemoryTrackerInitialized` to allow tracking before `MainThreadStatus` init and prevent use-after-destruction. Add `CAllocationTrackingBlocker` to prevent recursion in C allocation wrappers. Restructure CMake wrapping: `getaddrinfo`/`freeaddrinfo` wrapped in all Linux builds including sanitizer builds; `malloc`/`free` family and `strdup`/`strndup` only in non-sanitizer builds. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Mapped pages are backed by the page cache and don't consume RSS the same way heap allocations do. Charging the full mapped length against `max_memory_usage` causes false `MEMORY_LIMIT_EXCEEDED` exceptions (e.g. `01548_parallel_parsing_max_memory` maps a 1 GiB file with a 50 MiB limit). Co-Authored-By: Claude Opus 4.6 <[email protected]>
…wrapper The empty catch block is intentional — exceptions cannot propagate through C library callbacks. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98915&sha=31fe4fca8415862f6f70bb512f40cb8e9e6cf8eb&name_0=PR Co-Authored-By: Claude Opus 4.6 <[email protected]>
…nitizer builds On Linux with sanitizers, the `--wrap=getaddrinfo`/`--wrap=freeaddrinfo` linker flags are active (they are intentionally outside the sanitizer guard in CMakeLists.txt), but the header only defined `__real_getaddrinfo`/ `__real_freeaddrinfo` macros for Darwin/FreeBSD/SunOS within the sanitizer preprocessor branch. On Linux, neither macros nor extern declarations existed, causing a compile error. Add `extern "C"` declarations in the `#else` branch. Macros mapping to `::getaddrinfo` would cause infinite recursion through the linker wrap. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Wrap the `getaddrinfo` tracking mutex and map in a struct guarded by an `std::atomic_bool` flag, matching the `isTotalMemoryTrackerInitialized` pattern used by `total_memory_tracker`. The flag is declared before the struct so it outlives it, preventing undefined behavior if `__wrap_freeaddrinfo` is called during static destruction. Co-Authored-By: Claude Opus 4.6 <[email protected]>
`allocNoThrow` and `onAlloc` were called unconditionally in `__wrap_getaddrinfo`, but the tracked size was only stored in the map when `getaddrinfo_tracking_initialized` was true. When the map was unavailable (during early init or late shutdown), the memory tracker was incremented but the size was never stored, so `__wrap_freeaddrinfo` could not find the entry and never called `CurrentMemoryTracker::free`, creating permanent positive tracking drift. Move both calls inside the `if (getaddrinfo_tracking_initialized)` guard to keep tracking symmetric with untracking. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Sanitizer runtimes (TSan, MSan) define their own `operator new`/`operator delete`. When the linker resolves `__wrap_getaddrinfo` from `AllocationInterceptors.cpp` in the `clickhouse_new_delete` archive, it pulls in the entire object — including our `new`/`delete` overrides — which then collide with the sanitizer definitions, causing a duplicate-symbol link error. Guard the `getaddrinfo`/`freeaddrinfo` wrappers and their helper state with `!defined(SANITIZER) && !defined(SANITIZE_COVERAGE)`, and move the `--wrap` linker flags inside the existing sanitizer guard in CMakeLists.txt. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Move `c_allocation_tracking_disabled`, `isCAllocationTrackingDisabled`, and `CAllocationTrackingBlocker` inside the existing `#if !defined(SANITIZER) && !defined(SANITIZE_COVERAGE)` guard. The previous commit (`cd90ff26170`) moved all users of these symbols behind the sanitizer guard but left the definitions unconditionally compiled, causing `-Wunused-member-function` errors in sanitizer builds (ASan, TSan, MSan, UBSan on both amd64 and arm64). https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98915&sha=cd90ff26170a2c84f51246377146fd752a864378&name_0=PR Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add `// Ok` suppression comment to `catch (...)` in `__wrap_getaddrinfo` to satisfy the `catch_all` style check. Guard `GetAddrInfoFreeAddrInfoDoesNotCauseNegativeDrift` test with `#if !defined(SANITIZE_COVERAGE)` to match the implementation guard on the `__wrap_getaddrinfo`/`__wrap_freeaddrinfo` interceptors, which are excluded from coverage builds. Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Add `NOLINT(bugprone-empty-catch)` to the empty catch in `memory.h` that clang-tidy flagged after our changes invalidated the tidy cache for translation units including this header. - Fix `GetAddrInfoFreeAddrInfoDoesNotCauseNegativeDrift` unit test: call `CurrentThread::flushUntrackedMemory` before checking tracker counters. The `getaddrinfo` allocation (~hundreds of bytes) was below the 4 MB `untracked_memory_limit` threshold, so it stayed in the per-thread buffer and never flushed to the tracker counters visible via `memory_tracker.get`. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98915&sha=latest&name_0=PR Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
|
Interesting, what are the libraries that use strdup? Also, what are the libraries that use getaddrinfo (we use c-ares)? |
…ailable in all builds The previous commit f81db8f moved the `#if !defined(SANITIZER)` guard to also cover `isCAllocationTrackingDisabled` and `CAllocationTrackingBlocker`, but the `__wrap_malloc`/`__wrap_free`/etc. functions are not guarded by this preprocessor check and reference `isCAllocationTrackingDisabled`. Move the guard down so it only covers the getaddrinfo tracking infrastructure. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98915&sha=latest&name_0=PR Co-Authored-By: Claude Opus 4.6 <[email protected]>
…izer builds The previous fix (a30b780) moved `CAllocationTrackingBlocker` out of the `#if !defined(SANITIZER) && !defined(SANITIZE_COVERAGE)` guard unconditionally. However, the class is only used by `__wrap_strdup`, `__wrap_strndup`, `__wrap_getaddrinfo`, and `__wrap_freeaddrinfo` — all of which are inside the guard. In sanitizer builds the class was defined but never instantiated, triggering `-Werror,-Wunused-member-function`. Keep `c_allocation_tracking_disabled` and `isCAllocationTrackingDisabled` unconditional (needed by `__wrap_malloc`/`__wrap_free`), but move `CAllocationTrackingBlocker` back inside the guard. Co-Authored-By: Claude Opus 4.6 <[email protected]>
1. Attribute `IOUringReader` ring memory to `total_memory_tracker` instead of `CurrentMemoryTracker`. The io_uring ring is a process-wide singleton lazily initialized from query context, so the first query that triggers it would be permanently charged for the ring memory and could hit its own memory limit. Use `MemoryTrackerSwitcher` to redirect to the global tracker, consistent with `HTTPConnectionPool`, `HostResolvePool`, etc. 2. Add `__real_strdup` / `__real_strndup` macro fallbacks in `AllocationInterceptors.h` for sanitizer/Darwin/FreeBSD/SunOS builds. The `__wrap_strdup` / `__wrap_strndup` wrappers compile on all non-sanitizer builds but `__real_strdup` / `__real_strndup` were only declared in the Linux non-sanitizer branch, causing a compile break on other platforms. Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Move `<netdb.h>` include and `__real_getaddrinfo`/`__real_freeaddrinfo` `extern "C"` declarations from `AllocationInterceptors.h` to `AllocationInterceptors.cpp`. The header is transitively included in virtually every TU via `memory.h`; the getaddrinfo declarations are only needed in the .cpp. The `#define` fallbacks for non-`--wrap` platforms (Darwin/FreeBSD/SunOS) are preserved in the header. - Replace dead retry loops in allocation interceptor tests with single-shot assertions. The memory tracker updates synchronously on the calling thread before `malloc`/`free` returns, so re-reading the same deterministic atomic up to 1000 times was dead code. Use `flushUntrackedMemory` + explicit `ASSERT_GE`/`ASSERT_LE` instead. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add NOLINT suppressions for: - `bugprone-empty-catch` in `SignalHandlers.cpp` (intentionally empty catch in terminate handler) - `bugprone-reserved-identifier` in `AllocationInterceptors.cpp` (`__real_*` names are mandated by the linker `--wrap` mechanism) https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98915&sha=latest&name_0=PR Co-Authored-By: Claude Opus 4.6 <[email protected]>
The NOLINT comments on `__real_getaddrinfo` and `__real_freeaddrinfo` declarations only suppressed `bugprone-reserved-identifier` but not the equivalent `cert-dcl37-c` and `cert-dcl51-cpp` checks, which also flag reserved identifiers. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98915&sha=6ec9c110a590cbb1ff87d7b30862399503629896&name_0=PR Co-Authored-By: Claude Opus 4.6 <[email protected]>
…info` declarations to header The `extern "C"` forward declarations for `__real_getaddrinfo` and `__real_freeaddrinfo` in the `.cpp` file collided with the function-like macros defined in the header on Darwin/FreeBSD/sanitizer platforms. The preprocessor expanded the declarations into `::getaddrinfo(...)` which is illegal C++ (`-Wextra-qualification`). Move the declarations into the `#else` block of `AllocationInterceptors.h`, alongside the existing `__real_strdup`/`__real_strndup` declarations. This follows the established pattern: on macro-branch platforms, the `__real_*` names are macros; on Linux non-sanitizer builds, they are real linker-`--wrap` symbols with `extern "C"` declarations. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
I also have another idea, more general, maybe we can compile jemalloc with Let me try |
…drinfo map Remove `CAllocationTrackingBlocker` and per-function `isCAllocationTrackingDisabled` checks — these are unnecessary since the wrapped C functions never recursively enter tracking code. Replace the mutex-protected `unordered_map` in `getaddrinfo`/`freeaddrinfo` tracking with a stateless approach: recalculate the size from the `addrinfo` linked list on free instead of storing it. The list is immutable (resolver-allocated, no mutation API), so `estimateGetAddrInfoSize` is deterministic — new tests verify this. Fix musl double-counting: `strdup`, `strndup`, `getaddrinfo`, and `freeaddrinfo` wrappers are now guarded with `!defined(USE_MUSL)` (along with linker wraps in CMakeLists.txt), because musl's static libc implements these using malloc/free which are already intercepted by `__wrap_malloc`/`__wrap_free`. For `strdup`/`strndup`, use `sallocx`/`malloc_usable_size` for accurate post- allocation size tracking instead of pre-estimating with `strlen`. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Yes, it's a good idea, and it will make it compatible with LD_PRELOAD=shit_that_overrides_malloc. |
… interceptors Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Use `newNoExcept` followed by an explicit null check instead of wrapping `newImpl` in try/catch. This removes the unnecessary exception-based control flow and eliminates the now-unused `newImpl` function from `memory.h`. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
# Conflicts: # src/Common/AllocationInterceptors.cpp # src/Common/memory.h
These linker-wrap based interceptors were replaced by direct symbol interposition via `malloc.cpp` and the `clickhouse_malloc` object. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
| void * ptr = nullptr; | ||
| try | ||
| { | ||
| ptr = allocNoTrack<clear_memory_, populate>(size, alignment); |
There was a problem hiding this comment.
Let's avoid extra try/catch here and move this into allocNoTrack (and rename it, and also rename freeNoTrack)
There was a problem hiding this comment.
This is probably minor, but I think it still make sense
There was a problem hiding this comment.
Sorry didn't push the changes...
|
And please don't forget to update PR description |
… replace `unlikely(`/`likely(` with `[[unlikely]]`/`[[likely]]` Address review feedback: - Move memory tracking + rollback-on-failure into `allocImpl` (renamed from `allocNoTrack`), eliminating the try/catch in `Allocator::alloc`. Rename `freeNoTrack` to `freeImpl`. - Use `__real_malloc`/`__real_aligned_alloc`/`__real_free` macros from `AllocationInterceptors.h` in `memory.h` instead of `#if USE_JEMALLOC` branches with `je_*`/`::*` calls. - Replace all `unlikely(`/`likely(` with `[[unlikely]]`/`[[likely]]` in the three touched files. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
azat
left a comment
There was a problem hiding this comment.
Looks good, except for one minor thing - #98915 (comment)
LLVM Coverage Report
PR changed lines: PR changed-lines coverage: 71.05% (243/342, 1 noise lines excluded) |
operator new,Allocator::alloc,AllocatorWithMemoryTracking, andSystemAllocatedMemoryHolder.reallocfailure losing old allocation accounting.MemoryTracker::allocImplwherefetch_addreturn value was used as post-addition value.nallocx(0)undefined behavior causing negative drift frommalloc(0)/freeasymmetry.io_uringring buffers.isTotalMemoryTrackerInitializedto allow tracking beforeMainThreadStatusinitialization and prevent use-after-destruction.allocImpl(renamed fromallocNoTrack), eliminating the try/catch inAllocator::alloc. RenamefreeNoTracktofreeImpl.__real_*macros fromAllocationInterceptors.hinmemory.hinstead of duplicated#if USE_JEMALLOCbranches, and replace throwingnewImplwith non-throwingnewNoExceptin operator new overloads.unlikely(/likely(with[[unlikely]]/[[likely]]in touched files.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
nallocx(0)undefined behavior, and off-by-one in global peak tracking. Extend tracking to coverio_uringring buffers.🤖 Generated with Claude Code
Note
Medium Risk
Touches low-level allocation interception and global memory tracker initialization/peak accounting, so mistakes could cause incorrect memory limits/metrics or hard-to-debug startup/shutdown issues. Changes are contained to memory tracking paths and add test coverage for common drift cases.
Overview
Improves memory tracking accuracy by rolling back accounting on failed allocations across C++
new/allocators andSYSTEM ALLOCATE MEMORY, fixingreallocfailure to preserve the original allocation’s tracked size, correcting an off-by-one in globalMemoryTracker::allocImpl, and avoidingjemallocnallocx(0)undefined behavior (reducing negative drift inmalloc(0)/freeloops).Extends tracking coverage by wrapping additional libc APIs (
strdup,strndup,getaddrinfo,freeaddrinfo) in non-sanitizer non-musl builds, and by attributingio_uringring buffer memory to the global tracker with proper cleanup on init/destruction. AddsisTotalMemoryTrackerInitialized()to allow safe early/late use oftotal_memory_tracker, updates CMake wrapping rules accordingly, and expandsgtest_allocation_interceptorswith new drift/regression tests (including determinism checks foraddrinfosize estimation).Written by Cursor Bugbot for commit 4830e7e. This will update automatically on new commits. Configure here.
Version info
26.3.1.841