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.

feat(diagnostics): deterministic memory-attribution driver

Martin Vogel6a483344c6dd
diff --git a/Makefile.cbm b/Makefile.cbm
index e4d180257..568b5f3d2 100644
--- a/Makefile.cbm
+++ b/Makefile.cbm
@@ -109,6 +109,15 @@ MIMALLOC_WRAP_FLAGS :=
ifeq ($(IS_MINGW),yes)
MIMALLOC_WRAP_FLAGS := $(foreach sym,$(MIMALLOC_WRAP_SYMS),-Wl,--wrap=$(sym))
endif
+# Linux wraps a smaller set for MEASUREMENT only (see mem_override_posix.c):
+# allocations already reach mimalloc here, but the profiler needs the same
+# observation point as Windows or the platform comparison is not like-for-like.
+# macOS ld has no --wrap, so it stays census-only.
+IS_LINUX := $(shell uname -s 2>/dev/null | grep -q Linux && echo yes || echo no)
+MIMALLOC_WRAP_SYMS_POSIX := malloc calloc realloc free strdup
+ifeq ($(IS_LINUX),yes)
+MIMALLOC_WRAP_FLAGS := $(foreach sym,$(MIMALLOC_WRAP_SYMS_POSIX),-Wl,--wrap=$(sym))
+endif
ifeq ($(IS_MINGW),yes)
WIN32_LIBS := -lws2_32 -lpsapi -lshell32 -ladvapi32 -Wl,--allow-multiple-definition -Wl,--stack,8388608 -static
endif
@@ -141,6 +150,7 @@ FOUNDATION_SRCS = \
src/foundation/compat_regex.c \
src/foundation/mem.c \
src/foundation/mem_profile.c \
+ src/foundation/mem_override_posix.c \
src/foundation/diagnostics.c \
src/foundation/profile.c \
src/foundation/dump_verify.c \
diff --git a/scripts/memlab-drive.py b/scripts/memlab-drive.py
new file mode 100644
index 000000000..071d96881
--- /dev/null
+++ b/scripts/memlab-drive.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python3
+"""Drive a fixed sequence of MCP requests over stdio and wait for each reply.
+
+Batching all requests and closing stdin does not work: the server treats EOF as
+the client disconnecting and shuts down before answering, so the run produces a
+census of a process that never did any work. Reading each response before
+sending the next also makes the workload deterministic — every request is
+serviced from the same steady state, which is what makes two runs comparable.
+"""
+import argparse
+import json
+import subprocess
+import sys
+
+
+def rpc(proc, payload, timeout_note):
+ proc.stdin.write(json.dumps(payload) + "\n")
+ proc.stdin.flush()
+ while True:
+ line = proc.stdout.readline()
+ if not line:
+ raise RuntimeError(f"server closed stdout while waiting for {timeout_note}")
+ line = line.strip()
+ if not line.startswith("{"):
+ continue
+ try:
+ message = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if message.get("id") == payload.get("id"):
+ return message
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("binary")
+ parser.add_argument("corpus")
+ parser.add_argument("requests", type=int)
+ args = parser.parse_args()
+
+ proc = subprocess.Popen(
+ [args.binary],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ text=True,
+ bufsize=1,
+ )
+ served = 0
+ failures = 0
+ try:
+ rpc(proc, {"jsonrpc": "2.0", "id": 0, "method": "initialize",
+ "params": {"protocolVersion": "2024-11-05", "capabilities": {},
+ "clientInfo": {"name": "memlab", "version": "1"}}},
+ "initialize")
+ indexed = rpc(proc, {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": {"name": "index_repository",
+ "arguments": {"path": args.corpus}}},
+ "index_repository")
+ if "error" in indexed:
+ print(f"index failed: {indexed['error']}", file=sys.stderr)
+ return 3
+
+ for i in range(2, args.requests + 2):
+ reply = rpc(proc, {"jsonrpc": "2.0", "id": i, "method": "tools/call",
+ "params": {"name": "search_graph",
+ "arguments": {"name_pattern": ".*Widget.*",
+ "limit": 10}}},
+ f"request {i}")
+ served += 1
+ if "error" in reply:
+ failures += 1
+ finally:
+ try:
+ proc.stdin.close()
+ except Exception:
+ pass
+ try:
+ proc.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+
+ print(f"served={served} failed={failures}")
+ return 0 if served == args.requests and failures == 0 else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/memlab.sh b/scripts/memlab.sh
new file mode 100644
index 000000000..347bfbd80
--- /dev/null
+++ b/scripts/memlab.sh
@@ -0,0 +1,94 @@
+#!/usr/bin/env bash
+#
+# memlab.sh — deterministic memory-attribution run for #581.
+#
+# The soak answers "did memory grow over eight minutes"; this answers "which
+# allocation sites retained it", in about a minute, with a fixed request count
+# so two runs are directly comparable. Everything that made soak numbers hard
+# to compare — wall-clock duration, background reindexes, crash-recovery
+# phases, throughput differences between builds — is deliberately absent.
+#
+# Usage: scripts/memlab.sh <binary> [requests] [label]
+#
+# Output: memlab-<label>.jsonl (profiler records, one block per sample)
+# memlab-<label>.log (daemon log with mem.census lines)
+# Analyse with: scripts/memlab-report.py memlab-<label>.jsonl --census memlab-<label>.log
+set -u
+
+BINARY="${1:?usage: memlab.sh <binary> [requests] [label]}"
+REQUESTS="${2:-200}"
+LABEL="${3:-$(uname -s | tr '[:upper:]' '[:lower:]')}"
+
+if [ ! -x "$BINARY" ]; then
+ echo "FAIL: $BINARY is not executable" >&2
+ exit 2
+fi
+
+WORK=$(mktemp -d 2>/dev/null || mktemp -d -t memlab)
+PROFILE_OUT="$PWD/memlab-${LABEL}.jsonl"
+RUN_LOG="$PWD/memlab-${LABEL}.log"
+rm -f "$PROFILE_OUT" "$RUN_LOG"
+
+cleanup() { rm -rf "$WORK" 2>/dev/null || true; }
+trap cleanup EXIT
+
+# A fixed corpus: same file count and content on every platform, so a
+# difference in the output cannot come from a difference in the input.
+CORPUS="$WORK/corpus"
+mkdir -p "$CORPUS/src"
+for i in $(seq 1 60); do
+ cat > "$CORPUS/src/module_$i.py" <<EOF
+class Widget$i:
+ """Fixed corpus file $i."""
+ def __init__(self, name):
+ self.name = name
+ self.parts = []
+
+ def attach(self, part):
+ self.parts.append(part)
+ return self
+
+ def render(self):
+ return "-".join(str(p) for p in self.parts)
+
+def build_$i(count):
+ widget = Widget$i("w$i")
+ for index in range(count):
+ widget.attach(index)
+ return widget.render()
+EOF
+done
+
+echo "=== memlab: binary=$BINARY requests=$REQUESTS label=$LABEL ==="
+echo "corpus: $(find "$CORPUS" -name '*.py' | wc -l | tr -d ' ') files"
+
+export CBM_CACHE_DIR="$WORK/cache"
+export CBM_MEM_PROFILE=1
+export CBM_MEM_PROFILE_OUT="$PROFILE_OUT"
+export CBM_MEM_CENSUS=1
+export CBM_LOG_LEVEL=info
+export CBM_LOG_FORMAT=text
+mkdir -p "$CBM_CACHE_DIR"
+
+# Drive the MCP stdio path via the request/response driver (see its header for
+# why batching into a closed stdin does not work).
+python3 "$(dirname "$0")/memlab-drive.py" "$BINARY" "$CORPUS" "$REQUESTS" > "$WORK/drive.out" 2>&1
+RC=$?
+# With CBM_CACHE_DIR set the process logs to its own file rather than stderr,
+# so fold that in or the census series is invisible.
+cat "$CBM_CACHE_DIR"/logs/*.log >> "$RUN_LOG" 2>/dev/null || true
+RESPONSES=$(sed -n "s/.*served=\\([0-9]*\\).*/\\1/p" "$WORK/drive.out" | head -1); RESPONSES=${RESPONSES:-0}
+CENSUS=$(grep -c "mem.census" "$RUN_LOG" 2>/dev/null | head -1); CENSUS=${CENSUS:-0}
+SITES=$(grep -c '"site"' "$PROFILE_OUT" 2>/dev/null | head -1); SITES=${SITES:-0}
+
+echo "exit=$RC responses=$RESPONSES census_samples=$CENSUS profile_records=$SITES"
+if [ "$CENSUS" -eq 0 ]; then
+ echo "WARN: no census samples — check CBM_MEM_CENSUS wiring" >&2
+fi
+if [ "$SITES" -eq 0 ]; then
+ # Not fatal, but never silent: on macOS there is no --wrap, so the
+ # profiler legitimately has no observation point.
+ echo "WARN: no profiler records — expected on macOS (no --wrap); a gap anywhere else" >&2
+fi
+echo "profile: $PROFILE_OUT"
+echo "log: $RUN_LOG"
diff --git a/src/foundation/mem.c b/src/foundation/mem.c
index 89b15e913..970254984 100644
--- a/src/foundation/mem.c
+++ b/src/foundation/mem.c
@@ -816,9 +816,11 @@ void cbm_mem_census_log(const char *tag) {
return;
}
cbm_mem_win_census_t census;
- if (!cbm_mem_win_census(&census)) {
- return;
- }
+ /* A false return means the OS-region walk is unavailable (non-Windows), not
+ * that there is nothing to report: the allocation-site half is the whole
+ * point of the cross-platform comparison, so it still runs and the pool
+ * fields simply read zero. */
+ (void)cbm_mem_win_census(&census);
/* Kilobytes throughout: the CRT heap measured 0 at megabyte resolution,
* which reads as "empty" when it may simply be small — a diagnostic that
* rounds its own evidence away is worse than none. */
diff --git a/src/foundation/mem_override_posix.c b/src/foundation/mem_override_posix.c
new file mode 100644
index 000000000..2d3ab225d
--- /dev/null
+++ b/src/foundation/mem_override_posix.c
@@ -0,0 +1,69 @@
+/*
+ * mem_override_posix.c — allocation-site visibility on POSIX.
+ *
+ * On POSIX the build links mimalloc's object first, so its strong malloc/free
+ * win and every allocation already lands in mimalloc — nothing needs
+ * redirecting for correctness. What is missing is a place to OBSERVE those
+ * allocations: the Windows side gets it for free from the --wrap interposer it
+ * needs anyway, and without an equivalent here the profiler could only ever
+ * describe Windows, which makes the platform comparison — the one measurement
+ * that actually isolates #581 — impossible.
+ *
+ * So this file exists purely for symmetry of measurement. Each wrapper forwards
+ * to the same mi_* entry point the symbol would have reached on its own and
+ * records the block, so both platforms are profiled through the same code path
+ * and a difference in the output is a difference in behaviour rather than an
+ * artifact of two different instrumentation schemes.
+ *
+ * Linux only: --wrap is a GNU ld/lld feature. macOS ld has no equivalent, so
+ * macOS runs census-only and the profiler reports nothing there. That gap is
+ * stated in the harness spec rather than hidden behind zeros that look like
+ * "no allocations".
+ */
+#include "foundation/mem_profile.h"
+
+#include <mimalloc.h>
+#include <stddef.h>
+
+#if defined(__linux__)
+
+void *__wrap_malloc(size_t size) {
+ void *block = mi_malloc(size);
+ cbm_mem_profile_alloc(block, size);
+ return block;
+}
+
+void *__wrap_calloc(size_t count, size_t size) {
+ void *block = mi_calloc(count, size);
+ cbm_mem_profile_alloc(block, count * size);
+ return block;
+}
+
+void *__wrap_realloc(void *block, size_t size) {
+ if (block) {
+ cbm_mem_profile_free(block);
+ }
+ void *grown = mi_realloc(block, size);
+ cbm_mem_profile_alloc(grown, size);
+ return grown;
+}
+
+void __wrap_free(void *block) {
+ if (!block) {
+ return;
+ }
+ /* Unlike Windows there is no foreign-allocator hazard to route around:
+ * every malloc in this image is already mimalloc's. */
+ cbm_mem_profile_free(block);
+ mi_free(block);
+}
+
+char *__wrap_strdup(const char *text) {
+ char *copy = mi_strdup(text);
+ if (copy) {
+ cbm_mem_profile_alloc(copy, mi_usable_size(copy));
+ }
+ return copy;
+}
+
+#endif /* __linux__ */