Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

diag: add a memory map that reports what it cannot see

Martin Vogel73a15f93ac52
diff --git a/src/foundation/diagnostics.c b/src/foundation/diagnostics.c
index 1971c0f1a..337531442 100644
--- a/src/foundation/diagnostics.c
+++ b/src/foundation/diagnostics.c
@@ -445,7 +445,29 @@ static void write_diagnostics(void) {
long long qmax = atomic_load(&g_query_stats.max_us);
long long qavg = qcount > 0 ? qtime / qcount : 0;
- char snapshot[CBM_SZ_1K];
+ /* Memory map: live allocator bytes on this thread's heap, a size-class
+ * histogram, and the residual the walk does NOT account for. The residual
+ * is what keeps this honest — see mem.h. */
+ cbm_mem_map_t map;
+ (void)cbm_mem_map_collect(&map);
+ size_t residual =
+ map.os_committed_bytes > map.live_bytes ? map.os_committed_bytes - map.live_bytes : 0;
+ char buckets[CBM_SZ_512];
+ int bucket_length = 0;
+ for (int i = 0;
+ i < CBM_MEM_MAP_BUCKETS && bucket_length >= 0 && (size_t)bucket_length < sizeof(buckets);
+ i++) {
+ int written =
+ snprintf(buckets + bucket_length, sizeof(buckets) - (size_t)bucket_length,
+ "%s{\"limit\": %zu, \"bytes\": %zu, \"blocks\": %zu}", i == 0 ? "" : ", ",
+ cbm_mem_map_bucket_limit(i), map.bucket_bytes[i], map.bucket_blocks[i]);
+ if (written < 0) {
+ break;
+ }
+ bucket_length += written;
+ }
+
+ char snapshot[CBM_SZ_2K];
int length = snprintf(snapshot, sizeof(snapshot),
"{\n"
" \"uptime_s\": %ld,\n"
@@ -460,10 +482,16 @@ static void write_diagnostics(void) {
" \"query_total_us\": %lld,\n"
" \"query_avg_us\": %lld,\n"
" \"query_max_us\": %lld,\n"
+ " \"mem_live_bytes\": %zu,\n"
+ " \"mem_live_blocks\": %zu,\n"
+ " \"mem_area_committed_bytes\": %zu,\n"
+ " \"mem_residual_bytes\": %zu,\n"
+ " \"mem_buckets\": [%s],\n"
" \"pid\": %d\n"
"}\n",
uptime, current_rss, peak_rss, current_commit, peak_commit, page_faults,
- fds, qcount, qerrors, qtime, qavg, qmax, (int)getpid());
+ fds, qcount, qerrors, qtime, qavg, qmax, map.live_bytes, map.live_blocks,
+ map.area_committed_bytes, residual, buckets, (int)getpid());
if (length <= 0 || (size_t)length >= sizeof(snapshot) ||
!diag_write_file(DIAG_SNAPSHOT_TMP_NAME, snapshot, (size_t)length, false) ||
!diag_native_rename(DIAG_SNAPSHOT_TMP_NAME, DIAG_SNAPSHOT_NAME)) {
diff --git a/src/foundation/mem.c b/src/foundation/mem.c
index 042fbd953..6828e1bdb 100644
--- a/src/foundation/mem.c
+++ b/src/foundation/mem.c
@@ -333,3 +333,86 @@ size_t cbm_mem_worker_budget(int num_workers) {
void cbm_mem_collect(void) {
mi_collect(true);
}
+
+/* ── Memory map (see mem.h for how to read the triple) ─────────────── */
+
+static const size_t MEM_MAP_BUCKET_LIMITS[CBM_MEM_MAP_BUCKETS] = {
+ 64, 256, 1024, 4096, 16384, 65536, 1048576, 0, /* 0 = open-ended tail */
+};
+
+size_t cbm_mem_map_bucket_limit(int bucket) {
+ if (bucket < 0 || bucket >= CBM_MEM_MAP_BUCKETS) {
+ return 0;
+ }
+ return MEM_MAP_BUCKET_LIMITS[bucket];
+}
+
+static int mem_map_bucket_of(size_t block_size) {
+ for (int i = 0; i < CBM_MEM_MAP_BUCKETS - 1; i++) {
+ if (block_size <= MEM_MAP_BUCKET_LIMITS[i]) {
+ return i;
+ }
+ }
+ return CBM_MEM_MAP_BUCKETS - 1;
+}
+
+/* Area visitor: visit_blocks=false means one call per area, so `used` (live
+ * block count) x `block_size` is the live byte total without touching blocks. */
+static bool mem_map_visit_area(const mi_heap_t *heap, const mi_heap_area_t *area, void *block,
+ size_t block_size, void *arg) {
+ (void)heap;
+ (void)block;
+ (void)block_size;
+ cbm_mem_map_t *map = arg;
+ if (!area || !map) {
+ return true;
+ }
+ size_t live = area->used * area->block_size;
+ int bucket = mem_map_bucket_of(area->block_size);
+ map->live_bytes += live;
+ map->live_blocks += area->used;
+ map->bucket_bytes[bucket] += live;
+ map->bucket_blocks[bucket] += area->used;
+ map->area_committed_bytes += area->committed;
+ map->area_reserved_bytes += area->reserved;
+ return true; /* keep walking */
+}
+
+bool cbm_mem_map_collect(cbm_mem_map_t *out) {
+ if (!out) {
+ return false;
+ }
+ memset(out, 0, sizeof(*out));
+
+ size_t elapsed_ms = 0;
+ size_t user_ms = 0;
+ size_t sys_ms = 0;
+ size_t current_rss = 0;
+ size_t peak_rss = 0;
+ size_t current_commit = 0;
+ size_t peak_commit = 0;
+ size_t page_faults = 0;
+ mi_process_info(&elapsed_ms, &user_ms, &sys_ms, &current_rss, &peak_rss, &current_commit,
+ &peak_commit, &page_faults);
+ out->os_rss_bytes = current_rss ? current_rss : cbm_mem_rss();
+ out->os_committed_bytes = current_commit;
+
+ /* Walk areas only (visit_blocks=false): O(areas), safe on a live heap from
+ * the diagnostics path. mi_heap_main() is the aggregate heap rather than
+ * just this thread's, so coverage is wider than a per-thread walk — but it
+ * is still not a guarantee of totality, which is exactly why the residual
+ * exists. A declined walk leaves live_bytes 0 so the residual owns the
+ * whole process: an unmeasured map must never read as an empty one.
+ * Abandoned pages (a known RSS-ratchet source, see cbm_mem_init) are
+ * folded in so they cannot hide from the map either. */
+ (void)mi_heap_visit_blocks(mi_heap_main(), false, mem_map_visit_area, out);
+ (void)mi_heap_visit_abandoned_blocks(mi_heap_main(), false, mem_map_visit_area, out);
+ /* mimalloc v3 splits the aggregate heap (mi_heap_t) from the per-thread
+ * heap (mi_theap_t), and overridden malloc traffic lands in the latter --
+ * walking only mi_heap_main() reported live=0/blocks=0 on Windows for a
+ * process demonstrably holding tens of MB. Walk this thread's theap too.
+ * Coverage is still not total (other threads' theaps stay unreachable),
+ * which the residual continues to expose rather than hide. */
+ (void)mi_theap_visit_blocks(mi_theap_get_default(), false, mem_map_visit_area, out);
+ return true;
+}
diff --git a/src/foundation/mem.h b/src/foundation/mem.h
index 58856f518..f0d73f801 100644
--- a/src/foundation/mem.h
+++ b/src/foundation/mem.h
@@ -78,4 +78,51 @@ size_t cbm_mem_worker_budget(int num_workers);
/* Return unused pages to the OS. Call between files to bound per-file peak. */
void cbm_mem_collect(void);
+/* ── Memory map: where does the process's memory actually live? ──────
+ *
+ * A growth diagnostic that is honest about what it cannot see. Walking the
+ * allocator reports live bytes for the CALLING thread's heap only, so a leak
+ * on another thread — or memory never routed through the allocator — would be
+ * invisible to a naive per-subsystem tally. Every consumer therefore gets
+ * three independent totals plus an explicit residual, so an incomplete map
+ * announces itself instead of looking balanced:
+ *
+ * os_committed_bytes what the OS charges the process
+ * live_bytes allocator blocks live on THIS thread's heap
+ * residual os_committed - live_bytes (other threads, allocator
+ * retention, or non-allocator memory)
+ *
+ * Reading the triple localises growth without guessing:
+ * live grows → leak on this thread's heap; buckets say which size
+ * residual grows, live flat → another thread's heap, retention, or OS/CRT memory
+ * both flat but RSS grows → mapped files or stacks, not the heap
+ *
+ * The bucket histogram splits live bytes by size class, so a distinctive class
+ * ("thousands of 384-byte blocks appeared") identifies the allocation without
+ * per-callsite instrumentation.
+ */
+enum { CBM_MEM_MAP_BUCKETS = 8 };
+
+typedef struct {
+ size_t os_committed_bytes;
+ size_t os_rss_bytes;
+ size_t live_bytes;
+ size_t live_blocks;
+ size_t area_committed_bytes;
+ size_t area_reserved_bytes;
+ /* Live bytes by size class: <=64, <=256, <=1K, <=4K, <=16K, <=64K, <=1M, rest */
+ size_t bucket_bytes[CBM_MEM_MAP_BUCKETS];
+ size_t bucket_blocks[CBM_MEM_MAP_BUCKETS];
+} cbm_mem_map_t;
+
+/* Inclusive upper bound of each size class; the last bucket is open-ended and
+ * reports 0. */
+size_t cbm_mem_map_bucket_limit(int bucket);
+
+/* Snapshot the current memory map. Returns false only when out is NULL. If the
+ * allocator declines the walk, the OS totals are still filled and live_bytes
+ * stays 0, so the residual carries the whole process and the caller can SEE
+ * that the walk contributed nothing rather than reading 0 as "no leak". */
+bool cbm_mem_map_collect(cbm_mem_map_t *out);
+
#endif /* CBM_MEM_H */
diff --git a/tests/test_mem.c b/tests/test_mem.c
index 99469203a..252362e16 100644
--- a/tests/test_mem.c
+++ b/tests/test_mem.c
@@ -1167,8 +1167,68 @@ TEST(parallel_extract_with_slab) {
PASS();
}
+/* The memory map is a diagnostic, so it must be proven non-vacuous: a map that
+ * silently reported zeros would read as "no leak" and send a future
+ * investigation down the wrong path. Allocate a KNOWN volume in a KNOWN size
+ * class and require the map to attribute it to that class. */
+TEST(mem_map_attributes_a_known_allocation) {
+ enum { PROBE_BLOCKS = 4000, PROBE_SIZE = 3000 };
+ cbm_mem_map_t before;
+ cbm_mem_map_t after;
+ ASSERT_TRUE(cbm_mem_map_collect(&before));
+
+ /* Allocate through mi_* explicitly. The map walks the mimalloc heap, and
+ * only the PRODUCTION build routes plain malloc there (the test build is
+ * CRT+ASan) -- so a malloc-based probe would report 0 here and wrongly look
+ * like a broken instrument. Using mi_malloc exercises the walk and the
+ * bucket attribution in every build configuration. Note the corollary,
+ * which is why the residual exists: in a build where malloc does NOT reach
+ * mimalloc, live_bytes legitimately reads 0 and the residual owns
+ * everything. */
+ void **kept = malloc(PROBE_BLOCKS * sizeof(*kept));
+ ASSERT_NOT_NULL(kept);
+ for (int i = 0; i < PROBE_BLOCKS; i++) {
+ kept[i] = mi_malloc(PROBE_SIZE);
+ ASSERT_NOT_NULL(kept[i]);
+ ((char *)kept[i])[0] = (char)i; /* touch it so it is really committed */
+ }
+ ASSERT_TRUE(cbm_mem_map_collect(&after));
+
+ /* The walk must account for the bulk of the probe. Slack covers allocator
+ * rounding and blocks the aggregate walk may not reach; a map that saw
+ * ~nothing is precisely the failure this test exists to catch. */
+ size_t probe_bytes = (size_t)PROBE_BLOCKS * PROBE_SIZE;
+ ASSERT_GT(after.live_bytes, before.live_bytes);
+ ASSERT_GT(after.live_bytes - before.live_bytes, probe_bytes / 2);
+
+ /* 3000-byte blocks belong to the <=4096 class, not to a smaller one. */
+ int expected_bucket = -1;
+ for (int i = 0; i < CBM_MEM_MAP_BUCKETS; i++) {
+ size_t limit = cbm_mem_map_bucket_limit(i);
+ if (limit >= (size_t)PROBE_SIZE) {
+ expected_bucket = i;
+ break;
+ }
+ }
+ ASSERT_TRUE(expected_bucket >= 0);
+ ASSERT_GT(after.bucket_bytes[expected_bucket], before.bucket_bytes[expected_bucket]);
+ ASSERT_GT(after.bucket_blocks[expected_bucket] - before.bucket_blocks[expected_bucket],
+ (size_t)(PROBE_BLOCKS / 2));
+
+ /* OS totals must be populated independently of the walk, so the residual is
+ * meaningful rather than derived from an empty measurement. */
+ ASSERT_GT(after.os_committed_bytes, 0);
+
+ for (int i = 0; i < PROBE_BLOCKS; i++) {
+ mi_free(kept[i]);
+ }
+ free(kept);
+ PASS();
+}
+
SUITE(mem) {
/* mem API */
+ RUN_TEST(mem_map_attributes_a_known_allocation);
RUN_TEST(mem_rss_tracking);
RUN_TEST(mem_collect_reclaims);
RUN_TEST(mem_budget_check);