Repository navigation
feat: add mi_heap_dump_json / mi_heap_get_seq and snapshot-safe stats printing - #286
Merged
Merged
Conversation
zackees
added a commit
that referenced
this pull request
Sep 2, 2026
Follow-up to PR #286 (issue #269): updates MIMALLOC_FORKS.md's pass-3 table now that the two rows scheduled against #269 have landed, per CLAUDE.md rule 3's provenance-table requirement. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
… printing
Bun's shipped bun:jsc heapStats({dump:true|"blocks"}).mimallocDump API
(oven-sh/mimalloc@942b8342) had no equivalent here, so a rebase onto our
tree would delete a shipped Bun feature (#264 B8, #269).
- New src/heap-dump.c (rule 6): mi_heap_dump_json(include_blocks,
hash_addresses) walks the current subprocess's heaps/pages/(optional)
blocks via mi_subproc_visit_heaps + mi_heap_visit_blocks and builds the
JSON Bun's consumer expects; mi_heap_get_seq(heap) reads the heap_seq
field our mi_heap_t already carries. Declared in include/mimalloc-stats.h,
included unconditionally (not MI_PPROF-gated) from src/static.c, matching
how Bun builds it. Ported blocks carry "imported from oven-sh/mimalloc @
942b8342, MIT" provenance comments.
- src/stats.c: two small ported fixes, same provenance. _mi_stats_print now
prints from a coherent mi_stats_add snapshot instead of the live,
concurrently-updated stats struct; mi_stats_copy copies counter-at-a-time
through mi_stats_add instead of a torn-read-prone _mi_memcpy. Bun has an
open user bug on this surface (oven-sh/bun#28630, MIMALLOC_SHOW_STATS).
- test/test-heap-dump-json.c: two heaps with known allocation counts/sizes,
dumped with and without blocks; checks brace/bracket balance, seq
distinct across heaps and stable across repeated dumps and calls,
block_size read back per heap segment against the known allocation
(not predicted, since debug padding/guard overhead varies), blocks
absent in pages-only mode, hash_addresses hiding a live block's raw
pointer id, and a second thread dumping while the first frees half of
heap1's blocks (no crash). Independent of MI_PPROF, registered like
test-memory-events/test-dhat.
Refs #269, #264, #78.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
ci/check_internal_state.py rejects any unclassified call to the listed allocator wrappers outside src/alloc*.c/os.c. src/heap-dump.c's mi_rezalloc(hbuf->buf, newsize) (the growable JSON buffer, same pattern as src/stats.c's existing "stats-json-buffer" site) had no inventory entry, failing both the diag and lint verify_local.py configs. Adds "heap-dump-json-buffer" to ci/internal-state-inventory.json. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
…ATE=1 ci/verify_local.py's run_guarded config re-runs the whole ctest suite with every allocation guarded (its own single-block page), and separately with MI_GUARDED's default (occasional) sampling. Two assumptions in the new test broke under the rate=1 pass: - "used"/"block_size" were checked against a single page holding all 64 heap1 allocations; guarded mode gives each one its own page. Now summed (sum_field) / bounded (check_field_min) across every page in the heap's JSON segment instead of assuming one page. - the raw-pointer-hiding check compared the dump's block id against the pointer mi_heap_malloc returned; a guarded allocation's user-visible pointer is offset from the block's internal base the dump reports, so they are not the same value. Now self-referential: read back the first raw id from an unhashed dump, then assert hash_addresses hides that same id, instead of predicting it from the allocation call. Verified stable (15x each) under plain and MIMALLOC_GUARDED_SAMPLE_RATE=1 runs. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
Rust-only commit (rule 2): mi_heap_dump_json/mi_heap_get_seq FFI bindings in sys.rs (issue #269), a safe mimalloc_pprof::heap_dump_json() wrapper that owns the mi_free(json) round trip, and one unit test. Also regenerates the vendored amalgamation (cargo run -p xtask -- amalgamate-c && amalgamate-h) to pick up src/heap-dump.c and the include/mimalloc-stats.h declarations from the preceding C-core commits; `xtask check` was failing before this (amalgamation-drift.yml's gate). cargo test -p mimalloc-pprof, cargo clippy --all-targets, and cargo fmt --check all pass. Refs #269. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
Follow-up to PR #286 (issue #269): updates MIMALLOC_FORKS.md's pass-3 table now that the two rows scheduled against #269 have landed, per CLAUDE.md rule 3's provenance-table requirement. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
…q 0) Opus review of PR #286: - src/heap-dump.c: char tmp[128] -> tmp[192]. The page-line format has 5 %zu fields over ~71 fixed characters; worst case (all fields near SIZE_MAX) is 171 bytes + NUL, which _mi_snprintf would silently truncate rather than overflow -- producing malformed JSON that Bun's JSONParse(json) on the caller side turns into `mimallocDump: null` instead of a visible error. Deliberate deviation from Bun's own 128. - src/heap-dump.c: header comment now documents that the dump's own JSON-buffer growth (mi_rezalloc from the default heap) can appear in the walk it is part of, so a block size seen in the blocks[] pass is not guaranteed to already be present in the pages[] pass moments earlier -- same class of best-effort as Bun's own implementation. - test/test-heap-dump-json.c: pins `"seq": 0,` in the pages-only dump (the main/default heap is always the first _mi_heap_init call, and mi_atomic_increment_relaxed returns the pre-increment value -- Bun's own JS test relies on exactly this: `heaps.find(h => h.seq === 0)`), and asserts every page's `reserved` field is > 0 for both heaps (Bun: `expect(page.reserved).toBeGreaterThan(0)`). Header comment softened to name the one Bun assertion not checked as a hard assert (blocks[] size membership in pages[] block_sizes), with the self-mutation reason above. Verified 10x each, plain and MIMALLOC_GUARDED_SAMPLE_RATE=1. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
Rust-only commit (rule 2): src/heap-dump.c changed in 2769ede (tmp[128] -> tmp[192], header comment), which xtask check now flags as drift. Regenerated via cargo run -p xtask -- amalgamate-c && amalgamate-h. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
zackees
force-pushed
the
bun-parity/p4-heap-dump-json
branch
from
September 2, 2026 12:15
da89d43 to
d8a256d
Compare
Owner
Author
|
Opus review: APPROVE after follow-ups ( |
zackees
added a commit
that referenced
this pull request
Sep 2, 2026
Resolves the `src/static.c` include-list conflict (#286's `heap-dump.c` next to #270's `fork.c`) and regenerates the vendored amalgamation over the merged tree. Also picks up #290's `timed_allocation_audit` fix, which was the standing rust-native failure on win-gnu. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
3 of 4 tasks
zackees
added a commit
that referenced
this pull request
Sep 2, 2026
…, P4 #286) cargo run -p xtask -- amalgamate-c && amalgamate-h following the merge commit, which brought in src/fork.c (pthread_atfork, #270/#289) and src/heap-dump.c (#269/#286) from main. xtask check confirms the vendored amalgamation matches src/include again. Rust-only commit per CLAUDE.md rule 2. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
zackees
added a commit
that referenced
this pull request
Sep 2, 2026
Issue #274 (Bun parity P9b). docs/bun-gap-analysis-2026-09-02.md re-runs the 2026-09-01 analysis's four checks against Bun's current pin: the scripts/build/deps/mimalloc.ts commit (942b8342) has not moved, and all five consumer files (mimalloc_sys.rs, MimallocArena.rs, MimallocWTFMalloc.h, BunJSCModule.h, heapStats-mimalloc.test.ts) are byte-identical to what was cached in that session -- no new gap exists at Bun's current pin, so no new sub-issue is filed. The rest of the doc is a status table for every item and gap ID (B1-B20) from the 2026-09-01 analysis against what has actually merged since (#276, #281, #284, #286, #289, #291, #297) versus what's still open (#299, #302, and the items tied to them): 7/9 required-before-pitch items done, 11/20 B-numbered gaps done, 1 partial, 0 new. docs/ci-gates.md gains a `bun-surface` row and a short section explaining why that CI job is temporarily continue-on-error (mi_on_thread_idle isn't on main yet) with a dated TODO for when to make it a hard gate. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
Closed
16 tasks
zackees
pushed a commit
to Nosenzor/mimalloc-pprof
that referenced
this pull request
Sep 27, 2026
New docs/heap-dump-and-diagnostics.md: provenance (zackees#269, zackees#286, zackees#374, zackees#414, zackees#167), the MI_DIAGNOSTICS build surface and stubs, C/Rust API, the JSON schema field by field, the capture flow, raw-OS scratch storage, the diagnostic walk compiled inside arena.c, the owner-gated retry, the contrast with mi_heap_visit_blocks, lock/claim order and memory orders, limits and possible defects, the MI_DEBUG_FULL lock diagnostics, and tests. Independently verified against the serializer and walk; 9 corrections applied (one snippet-style item kept per the check_doc_snippets convention). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #269. Adds
mi_heap_dump_json(bool include_blocks, bool hash_addresses)/mi_heap_get_seq(mi_heap_t*)— the two symbols Bun's shippedbun:jscheapStats({dump:true|"blocks"}).mimallocDumpAPI is built on(
oven-sh/mimalloc@942b8342,src/stats.c:840-949andinclude/mimalloc-stats.h:167-168) — plus two small portedstats.cfixes.src/heap-dump.c(rule 6), included unconditionally (notMI_PPROF-gated) fromsrc/static.c, matching how Bun builds it. Walksmi_subproc_visit_heaps→mi_heap_visit_blocksand builds the JSON Bun'sBunJSCModule.hconsumer parses.Declarations added to
include/mimalloc-stats.h, matching Bun's signatures exactly.Our
mi_heap_talready carries aheap_seqfield assigned at heap creation(
src/heap.c's_mi_heap_init), so notypes.hchange was needed for step 2.Return value is
mi_rezalloc-family memory, freed by the caller withmi_free— samediscipline as the existing
mi_stats_get_json, and matchesBunJSCModule.h:380/403-405'smi_free(json).src/stats.c(step 4, small hunks with provenance):_mi_stats_printnow printsfrom a
mi_stats_addsnapshot instead of the live, concurrently-updated stats struct;mi_stats_copycopies counter-at-a-time throughmi_stats_addinstead of atorn-read-prone
_mi_memcpy. Bun has an open user bug on this surface(
MIMALLOC_SHOW_STATS=1environment variable does not work on Linux oven-sh/bun#28630,MIMALLOC_SHOW_STATS).test/test-heap-dump-json.c: two heaps with known allocation sizes, dumped with andwithout blocks; registered unconditionally (independent of
MI_PPROF, liketest-memory-events/test-dhat). See the ported-code note below for whyblock_sizeis read back rather than predicted.
mimalloc_pprof::heap_dump_json()safe wrapper inrust/mimalloc-pprof/src/lib.rs, FFI bindings insys.rs, one unit test, and theregenerated vendored amalgamation (
cargo run -p xtask -- amalgamate-c && amalgamate-h).Every line ported from Bun carries
// imported from oven-sh/mimalloc @ 942b8342, MITatthe top of its block.
MIMALLOC_FORKS.md's two pass-3 rows for this work are markedIMPORTED with this PR number in a follow-up commit.
Bun's
heapStats-mimalloc.test.tsassertions (the spec)Correct path:
test/js/bun/jsc/heapStats-mimalloc.test.ts(the issue citedtest/js/bun/util/..., which does not exist; confirmed via GitHub code search).Every JSON-shape assertion the mimalloc-side tests can check without a JS runtime:
s.mimallocDump.heapsis an array, length > 0 —count_char('{')==count_char('}')+
strstr(json, "\"heaps\"").seqis a stable, distinct identifier —mi_heap_get_seqcalled twice onthe same heap returns the same value; two heaps get different
seq; both appear inthe dump as
"seq": N,; stable across two independent dumps.main.pagesis an array,length > 0— heap1/heap2 segments both have at least one"used"/"block_size"entry (check_field_min(...) >= 1).page.idis a number,page.block_size > 0,page.used >= 0,page.reserved > 0,page.thread_idis a number — all five fields are emitted bymi_dump_block_visitfor every page entry;
block_size/usedare additionally checked against the knownallocation (summed across pages rather than assumed on one page, since
MIMALLOC_GUARDED_SAMPLE_RATE=1—ci/verify_local.py'sguardedconfig — givesevery allocation its own single-block page).
dump: true):main.blocksisundefined—strstr(json_pages, "\"blocks\"") == NULL.dump: "blocks"mode:main.blocksis an array,length > 0, each entry is[id, size]withsize > 0, and every block size matches some page'sblock_size— verified structurally (
"blocks": [[id,size]...]present,size > 0percheck_field_min); the cross-referencing assertion is a JS-sideSetcomparisonBun's test does at the JS layer, not re-implemented bit-for-bit in C, since our
C-level test's
block_sizevalues are already read back from the same page objectsby construction.
seq/pagesfields havethe right types — a second, independent
mi_heap_dump_json(false, false)call ischecked for
seqstability and JSON validity.hash_addresses(JSC's implicit non-debug default) hides raw addresses — newC-level assertion not in Bun's JS test (JS can't easily assert "not a real pointer"):
the first raw block id from an unhashed dump must not appear anywhere in a hashed
dump of the same live allocations.
arena memory is tagged as application memory) is unrelatedto this issue (B8/
mi_heap_dump_json) — it testsos_tag, already240at our pinper
MIMALLOC_FORKS.md's "already matches" list. Not applicable here.What the issue got wrong
test/js/bun/util/heapStats-mimalloc.test.ts; actualpath is
test/js/bun/jsc/heapStats-mimalloc.test.ts(utildoesn't exist).src/jsc/bindings/BunJSCModule.h; actual path issrc/jsc/modules/BunJSCModule.h.mi_heap_get_seq"add a field totypes.h" step: not needed.mi_heap_t::heap_seqalready exists at our pin (
include/mimalloc/types.h:606, set insrc/heap.c's_mi_heap_init), assigned viami_atomic_increment_relaxedon the subproc's heapcounter — already monotonic and distinct per heap.
mi_heap_get_seqis a two-lineaccessor.
stats.c's privatemi_json_buf_tmachinery (which would mean touching
stats.cbeyond the step-4 fixes),heap-dump.cduplicates the ~20-line growable-buffer helper under a distinct name (
mi_hdump_buf_t)to keep the new feature genuinely self-contained per rule 6.
ci/check_internal_state.py: not mentioned in the issue, butsrc/heap-dump.c'smi_rezalloccall is a "new internal-state allocation site" this repo's own CI gaterequires classifying in
ci/internal-state-inventory.json(mirroring the existingstats-json-bufferentry). Added in its own commit.Verify
uv run ci/verify_local.py --keep-going(final run, on the fully committed tree):asanis environmental-red in this sandbox (sanitizer/asan_interface.hnot installed--
[verify_local] FAIL: MI_TRACK_ASAN did not survive configure), unrelated to this PR;every other config, including
guarded(which runs the whole suite twice, the second timewith
MIMALLOC_GUARDED_SAMPLE_RATE=1forcing every allocation onto its own guard-adjacentpage), is green.
Also verified directly:
c++ -x c++ -std=c++17 -c src/static.c -Iinclude -DMI_STATIC_LIB(Bun's exactbuild mode) compiles clean;
nm -Con the resulting object shows both symbolsT.nm libmimalloc.a | grep -E "mi_heap_dump_json|mi_heap_get_seq"shows bothTin everybuilt variant (release, guarded/debug,
MI_PPROFon and off).test-heap-dump-jsonstable over 15 repeated runs each, plain and underMIMALLOC_GUARDED_SAMPLE_RATE=1.cargo test -p mimalloc-pprof,cargo clippy -p mimalloc-pprof --all-targets,cargo fmt -p mimalloc-pprof -- --checkall pass.Refs #269, #264, #78.
Co-Authored-By: Claude Fable 5.1 noreply@anthropic.com
Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
🤖 Generated with Claude Code
https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S