Skip to content

Improve memory tracking accuracy and coverage - #98915

Merged
antonio2368 merged 30 commits into
masterfrom
memory-tracking-improv
Mar 19, 2026
Merged

antonio2368 merged 30 commits into
masterfrom
memory-tracking-improv

Conversation

@antonio2368

@antonio2368 antonio2368 commented Mar 6, 2026 •

Copy link
Copy Markdown
Member
  • Rollback memory 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 value.
  • Fix nallocx(0) undefined behavior causing negative drift from malloc(0)/free asymmetry.
  • Extend tracking coverage to io_uring ring buffers.
  • Add isTotalMemoryTrackerInitialized to allow tracking before MainThreadStatus initialization and prevent use-after-destruction.
  • Merge memory tracking into allocImpl (renamed from allocNoTrack), eliminating the try/catch in Allocator::alloc. Rename freeNoTrack to freeImpl.
  • Use __real_* macros from AllocationInterceptors.h in memory.h instead of duplicated #if USE_JEMALLOC branches, and replace throwing newImpl with non-throwing newNoExcept in operator new overloads.
  • Replace unlikely(/likely( with [[unlikely]]/[[likely]] in touched files.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

  • Fix memory tracking drift caused by failed allocations not being rolled back, nallocx(0) undefined behavior, and off-by-one in global peak tracking. Extend tracking to cover io_uring ring 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 and SYSTEM ALLOCATE MEMORY, fixing realloc failure to preserve the original allocation’s tracked size, correcting an off-by-one in global MemoryTracker::allocImpl, and avoiding jemalloc nallocx(0) undefined behavior (reducing negative drift in malloc(0)/free loops).

Extends tracking coverage by wrapping additional libc APIs (strdup, strndup, getaddrinfo, freeaddrinfo) in non-sanitizer non-musl builds, and by attributing io_uring ring buffer memory to the global tracker with proper cleanup on init/destruction. Adds isTotalMemoryTrackerInitialized() to allow safe early/late use of total_memory_tracker, updates CMake wrapping rules accordingly, and expands gtest_allocation_interceptors with new drift/regression tests (including determinism checks for addrinfo size estimation).

Written by Cursor Bugbot for commit 4830e7e. This will update automatically on new commits. Configure here.

Version info

  • Merged into: 26.3.1.841

antonio2368 and others added 3 commits March 5, 2026 20:37
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]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cbb1d9f]

Summary: ✅

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 6, 2026
@antonio2368
antonio2368 requested a review from azat March 6, 2026 11:52
antonio2368 and others added 3 commits March 6, 2026 13:50
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]>
…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]>
Comment thread src/Common/AllocationInterceptors.cpp Resolved
Comment thread src/Common/AllocationInterceptors.cpp Resolved
@azat azat self-assigned this Mar 6, 2026
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]>
Comment thread src/Common/AllocationInterceptors.cpp Resolved
antonio2368 and others added 2 commits March 6, 2026 20:32
`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]>
Comment thread CMakeLists.txt Resolved
antonio2368 and others added 4 commits March 8, 2026 21:43
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]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/Common/AllocationInterceptors.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

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]>
@antonio2368

Copy link
Copy Markdown
Member Author

@alexey-milovidov these are the places Claude/GPT found:
https://pastila.nl/?0008e0fd/31bf8ea686e82ccba8fd8d72f45c2adc#ZD0P3/XvK89dBhL9uoqnQQ==GCM

antonio2368 and others added 6 commits March 9, 2026 10:18
…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]>
Comment thread src/Common/AllocationInterceptors.cpp Resolved
Comment thread src/Common/AllocationInterceptors.cpp Resolved
Comment thread src/Common/AllocationInterceptors.cpp Resolved
Comment thread src/Common/MemoryTracker.cpp Resolved
Comment thread src/Common/AllocationInterceptors.cpp Resolved
@azat

azat commented Mar 12, 2026 •

Copy link
Copy Markdown
Member

I also have another idea, more general, maybe we can compile jemalloc with je_ prefix, and then, replace malloc and friends to our own implementation that will do all our bookkeeping, that way, we should not need override for stdup and others, and that way it should work for in all other OSes

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

Copy link
Copy Markdown
Member

I also have another idea, more general, maybe we can compile jemalloc with je_ prefix, and then, replace malloc and friends to our own implementation that will do all our bookkeeping

Yes, it's a good idea, and it will make it compatible with LD_PRELOAD=shit_that_overrides_malloc.

@antonio2368 antonio2368 reopened this Mar 16, 2026
antonio2368 and others added 5 commits March 16, 2026 14:35
… 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]>
@antonio2368
antonio2368 requested a review from azat March 16, 2026 14:19
Comment thread src/Common/Allocator.cpp Outdated
void * ptr = nullptr;
try
{
ptr = allocNoTrack<clear_memory_, populate>(size, alignment);

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.

Let's avoid extra try/catch here and move this into allocNoTrack (and rename it, and also rename freeNoTrack)

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.

This is probably minor, but I think it still make sense

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry didn't push the changes...

Comment thread src/Common/memory.h Resolved
@azat

azat commented Mar 16, 2026

Copy link
Copy Markdown
Member

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]>
@antonio2368
antonio2368 requested a review from azat March 17, 2026 08:11

@azat azat 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.

Looks good, except for one minor thing - #98915 (comment)

@clickhouse-gh

clickhouse-gh Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.70% 83.70% +0.00%
Functions 23.90% 23.90% +0.00%
Branches 76.20% 76.30% +0.10%

PR changed lines: PR changed-lines coverage: 71.05% (243/342, 1 noise lines excluded)
Diff coverage report
Uncovered code

@antonio2368
antonio2368 added this pull request to the merge queue Mar 19, 2026
Merged via the queue into master with commit e74b65b Mar 19, 2026
159 checks passed
@antonio2368
antonio2368 deleted the memory-tracking-improv branch March 19, 2026 09:02
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default 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