tracemalloc said 9.5 KB. macOS said 142 KB: why Python and Ruby profilers miss C heap?
tracemalloc.get_traced_memory() reported 9,457 B per compiled 500-item $in query rule on Python 3.14.5. Calling macOS malloc_zone_statistics around the exact same 1,000-instance loop reported 142,317 B per instance, 15x more RAM than Python admitted existed.
In Ruby 4.0.5 wrapping the same C99 library, ObjectSpace.memsize_of reported only a single wrapper slot while hiding over 137 KB of native heap underneath. If you profile or maintain C extensions in Python or Ruby, built-in memory profilers stay quiet about C heap unless both your benchmark and your binding wire up the allocator boundary.
Why Python and Ruby go blind at the C boundary
Python's tracemalloc hooks the interpreter's three allocator domains (PYMEM_DOMAIN_RAW, PYMEM_DOMAIN_MEM, and PYMEM_DOMAIN_OBJ). Any Python object allocated through PyObject_* or PyMem_* shows up cleanly. When a wrapped C library allocates AST nodes, hash tables, or scratch buffers with libc malloc or calloc, those calls skip Python's hooks completely, leaving only the thin Python shell visible.
Ruby has a similar blind spot. GC.stat(:heap_live_slots) and GC.stat(:total_allocated_objects) count Ruby RVALUE slots inside GC heaps. ObjectSpace.memsize_of(obj) can include underlying C allocations, but only when the extension sets .dsize on its rb_data_type_t descriptor and sums the buffers it owns. Leaving .dsize = NULL compiles without a warning, hides the native heap from ObjectSpace, and keeps Ruby's GC from noticing C memory pressure.
Measuring the real bytes from outside the VM
Until your C extension reports its native heap cleanly, pair VM profilers with OS allocator statistics and process RSS. On macOS (arm64), Python's standard library gives you both:
import ctypes import ctypes.util import resource class MallocStatistics(ctypes.Structure): _fields_ = [ ("blocks_in_use", ctypes.c_uint), ("size_in_use", ctypes.c_size_t), ("max_size_in_use", ctypes.c_size_t), ("size_allocated", ctypes.c_size_t), ] libc = ctypes.CDLL(ctypes.util.find_library("c")) libc.malloc_zone_statistics.argtypes = [ctypes.c_void_p, ctypes.POINTER(MallocStatistics)] libc.malloc_zone_statistics.restype = None def malloc_in_use() -> int: st = MallocStatistics() libc.malloc_zone_statistics(None, ctypes.byref(st)) return int(st.size_in_use) def max_rss_bytes() -> int: return int(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) Ruby 4.0 removed fiddle from default gems, so reading malloc_zone_statistics without adding gem dependencies takes a 23-line C probe:
#include <ruby.h> #include <malloc/malloc.h> #include <sys/resource.h> static VALUE rb_malloc_in_use(VALUE self) { malloc_statistics_t st; malloc_zone_statistics(NULL, &st); return ULL2NUM((unsigned long long)st.size_in_use); } static VALUE rb_max_rss(VALUE self) { struct rusage ru; if (getrusage(RUSAGE_SELF, &ru) != 0) { rb_sys_fail("getrusage"); } return LL2NUM((long long)ru.ru_maxrss); } void Init_rb_malloc_probe(void) { VALUE mod = rb_define_module("MallocProbe"); rb_define_singleton_method(mod, "malloc_in_use", rb_malloc_in_use, 0); rb_define_singleton_method(mod, "max_rss", rb_max_rss, 0); } On Linux with glibc 2.33+, mallinfo2().uordblks gives live malloc bytes and /proc/self/status (VmRSS and VmHWM) tracks RSS (ru_maxrss returns kilobytes on Linux and bytes on macOS).
Where the hidden 142 KB went (and when C arenas lose)
Running those probes on an Apple M3 (macOS arm64) while holding 1,000 compiled rule instances in memory showed how much C heap the VMs were ignoring:
| Rule (1,000 instances retained) | Python tracemalloc | Python malloc_zone_statistics | Ruby malloc_zone_statistics |
|---|---|---|---|
Simple (age >= 18) | 1,171 B | 5,646 B | 4,687 B (5 slots) |
Nested (profile.city == "taipei" + 2 ops) | 1,210 B | 9,740 B | 8,811 B (5 slots) |
500-item $in hash lookup | 9,457 B | 142,317 B | 137,372 B (6 slots) |
Each compiled matcher allocates two 2 KB bump-allocated arena pools: one for the compiled AST and lookup tables, and one reusable scratch pool for zero-malloc matching, adding binding metadata on top. That sets a ~5 KB floor per rule (pure C without binding wrappers uses 2,256 B standalone or 520 B when sharing one arena).
Measured against pure-VM peers (mongoquery 1.4.3 in Python, mongoid 9.1.3 in Ruby), the C arena design trades compile-time memory for hot-path speed and GC silence:
- In Ruby, loading the C-backed gem (
141.7 KBbinary, 0 runtime deps) adds+0.8 MiBRSS, then scans 10,000 hashes allocating2to7Ruby objects (0.0to0.1 KiBC alloc) insideGC.disable.mongoidloads 19 gems (+47.3 MiBRSS), wrapping 10,000 hashes inMongoid::Documentadds+2,361.6 KiBand+120,338slots, and scanning them creates113,202Ruby objects onage >= 18up to4,796,168objects (+5.6 MiBmalloc) on a 500-item$in. - In Python,
mongoquery(+0.2 MiBRSS) keeps64 Bto92 Bper rule and peaks at2.3 KiBto3.7 KiBacross 10,000 records because CPython refcounting frees per-record temporaries immediately, shifting the cost into9xto2,314xhigher CPU time (258,170 ns/recvs111.6 ns/recon 500-item$in).
Caching 500,000 tiny distinct rules flips that trade-off upside down: ~5 KB per rule consumes ~2.5 GB of C heap until the OS OOM-killer strikes. Pure GC ports avoid the 2 KB C chunk floor (640 B in Go, 834 B in JS for the simple rule), and one-off queries over small arrays are cheaper with a 327-line interpreter like mongoquery or a plain if check.
Fixing both extensions, and what I got wrong on the way
In Python, wiring the C library's allocator callbacks to PyMem_RawMalloc and PyMem_RawFree (which do not require holding the GIL and still return NULL on OOM) routed every C arena chunk into tracemalloc. Adding __sizeof__ exposed native pool totals to sys.getsizeof. One critical detail when wiring the hook: every pointer from that allocator must be freed with PyMem_RawFree, never libc free, or tracemalloc crashes on teardown. After connecting it, tracemalloc jumped from 9,457 B to 141,137 B per 500-item $in instance (97.8% of the 144,364 B malloc_zone_statistics total recorded in the same traced run), sys.getsizeof reported 4,408 B, 8,504 B, and 131,384 B, and match latency stayed identical (89.2 ns/rec vs 86.8 ns/rec on simple queries).
Ruby took three tries. Routing the C core through ruby_xmalloc was off the table immediately: ruby_xmalloc requires the GVL and raises NoMemoryError via longjmp on OOM, which would jump straight out of C locks and mid-build cleanup paths. Calling rb_gc_adjust_memory_usage(+bytes) inside malloc or pool growth was unsafe too, since positive adjustments can trigger Ruby GC while newly wrapped VALUEs sit on the C stack unregistered.
static inline void pool_sync_gc(my_pool_t *pool) { size_t current = my_pool_total_bytes(pool); if (current != pool->reported_bytes) { ssize_t delta = (ssize_t)current - (ssize_t)pool->reported_bytes; pool->reported_bytes = current; rb_gc_adjust_memory_usage(delta); } } static size_t my_ext_dsize(const void *ptr) { const my_wrapper_t *w = (const my_wrapper_t *)ptr; return w ? sizeof(*w) + my_wrapper_pool_bytes(w) : 0; } My first patch synced GC memory by walking every pooled scratch arena on each record release, and the 100,000-record Ruby benchmark caught an immediate regression (80.5 ns/rec slowed to 97.4 ns/rec). My second attempt put a one-shot boolean flag on each scratch pool so only the first match synced to GC, which restored speed (78.3 ns/rec), but missed two bugs: if record #1 was small and record #1,000 expanded the scratch buffer to 64 KB, GC would never hear about it; and if re-entrant matching checked out a scratch pool mid-list-walk, wrapper-level accounting drifted downward.
Moving reported_bytes onto each individual pool struct and comparing my_pool_total_bytes(pool) != pool->reported_bytes at GC safe points fixed all three issues together. ObjectSpace.memsize_of now reports 4,360 B, 8,456 B, and 131,336 B, re-entrant pools cannot drift, late chunk growth is reported cleanly, and three-run median latency held steady at 82.1 ns/rec vs 80.5 ns/rec before the patch.
Where these numbers came from
These measurements come from Mongory, a C99-backed in-memory MongoDB-style query engine I maintain across C, Ruby, Python, Go, and JS, with full per-language memory and speed tables on Mongory Central.
If you ship Python or Ruby C extensions with custom allocators or arena pools, how do you catch native heap regressions or leaks in CI before users hit OOM in production?