Skip to content

feat: add mi_heap_dump_json / mi_heap_get_seq and snapshot-safe stats printing - #286

Merged
zackees merged 7 commits into
mainfrom
bun-parity/p4-heap-dump-json
Sep 2, 2026
Merged

zackees merged 7 commits into
mainfrom
bun-parity/p4-heap-dump-json

Conversation

@zackees

@zackees zackees commented Sep 2, 2026

Copy link
Copy Markdown
Owner

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 shipped bun:jsc
heapStats({dump:true|"blocks"}).mimallocDump API is built on
(oven-sh/mimalloc@942b8342, src/stats.c:840-949 and
include/mimalloc-stats.h:167-168) — plus two small ported stats.c fixes.

  • New src/heap-dump.c (rule 6), included unconditionally (not MI_PPROF-gated) from
    src/static.c, matching how Bun builds it. Walks mi_subproc_visit_heaps →
    mi_heap_visit_blocks and builds the JSON Bun's BunJSCModule.h consumer parses.
    Declarations added to include/mimalloc-stats.h, matching Bun's signatures exactly.
    Our mi_heap_t already carries a heap_seq field assigned at heap creation
    (src/heap.c's _mi_heap_init), so no types.h change was needed for step 2.
    Return value is mi_rezalloc-family memory, freed by the caller with mi_free — same
    discipline as the existing mi_stats_get_json, and matches BunJSCModule.h:380/403-405's
    mi_free(json).
  • src/stats.c (step 4, small hunks with provenance): _mi_stats_print now prints
    from a 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
    (MIMALLOC_SHOW_STATS=1 environment 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 and
    without blocks; registered unconditionally (independent of MI_PPROF, like
    test-memory-events/test-dhat). See the ported-code note below for why block_size
    is read back rather than predicted.
  • Rust (separate commit, rule 2): mimalloc_pprof::heap_dump_json() safe wrapper in
    rust/mimalloc-pprof/src/lib.rs, FFI bindings in sys.rs, one unit test, and the
    regenerated vendored amalgamation (cargo run -p xtask -- amalgamate-c && amalgamate-h).

Every line ported from Bun carries // imported from oven-sh/mimalloc @ 942b8342, MIT at
the top of its block. MIMALLOC_FORKS.md's two pass-3 rows for this work are marked
IMPORTED with this PR number in a follow-up commit.

Bun's heapStats-mimalloc.test.ts assertions (the spec)

Correct path: test/js/bun/jsc/heapStats-mimalloc.test.ts (the issue cited
test/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.heaps is an array, length > 0 — count_char('{')==count_char('}')
    + strstr(json, "\"heaps\"").
  • a heap's seq is a stable, distinct identifier — mi_heap_get_seq called twice on
    the same heap returns the same value; two heaps get different seq; both appear in
    the dump as "seq": N,; stable across two independent dumps.
  • main.pages is an array, length > 0 — heap1/heap2 segments both have at least one
    "used"/"block_size" entry (check_field_min(...) >= 1).
  • page.id is a number, page.block_size > 0, page.used >= 0, page.reserved > 0,
    page.thread_id is a number — all five fields are emitted by mi_dump_block_visit
    for every page entry; block_size/used are additionally checked against the known
    allocation (summed across pages rather than assumed on one page, since
    MIMALLOC_GUARDED_SAMPLE_RATE=1 — ci/verify_local.py's guarded config — gives
    every allocation its own single-block page).
  • pages-only mode (dump: true): main.blocks is undefined —
    strstr(json_pages, "\"blocks\"") == NULL.
  • dump: "blocks" mode: main.blocks is an array, length > 0, each entry is
    [id, size] with size > 0, and every block size matches some page's block_size
    — verified structurally ("blocks": [[id,size]...] present, size > 0 per
    check_field_min); the cross-referencing assertion is a JS-side Set comparison
    Bun's test does at the JS layer, not re-implemented bit-for-bit in C, since our
    C-level test's block_size values are already read back from the same page objects
    by construction.
  • a fresh dump after new allocations is still well-formed and seq/pages fields have
    the right types — a second, independent mi_heap_dump_json(false, false) call is
    checked for seq stability and JSON validity.
  • hash_addresses (JSC's implicit non-debug default) hides raw addresses — new
    C-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.
  • the macOS VM-tag test (arena memory is tagged as application memory) is unrelated
    to this issue (B8/mi_heap_dump_json) — it tests os_tag, already 240 at our pin
    per MIMALLOC_FORKS.md's "already matches" list. Not applicable here.

What the issue got wrong

  • Bun test file path: issue said test/js/bun/util/heapStats-mimalloc.test.ts; actual
    path is test/js/bun/jsc/heapStats-mimalloc.test.ts (util doesn't exist).
  • Consumer header path: issue said src/jsc/bindings/BunJSCModule.h; actual path is
    src/jsc/modules/BunJSCModule.h.
  • mi_heap_get_seq "add a field to types.h" step: not needed. mi_heap_t::heap_seq
    already exists at our pin (include/mimalloc/types.h:606, set in src/heap.c's
    _mi_heap_init), assigned via mi_atomic_increment_relaxed on the subproc's heap
    counter — already monotonic and distinct per heap. mi_heap_get_seq is a two-line
    accessor.
  • JSON-buffer helper: rather than exporting stats.c's private mi_json_buf_t
    machinery (which would mean touching stats.c beyond the step-4 fixes), heap-dump.c
    duplicates 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, but src/heap-dump.c's
    mi_rezalloc call is a "new internal-state allocation site" this repo's own CI gate
    requires classifying in ci/internal-state-inventory.json (mirroring the existing
    stats-json-buffer entry). Added in its own commit.

Verify

uv run ci/verify_local.py --keep-going (final run, on the fully committed tree):

config      | result | seconds
------------+--------+--------
release     | PASS   | 113.6
off         | PASS   | 108.9
debug-full  | PASS   | 161.6
guarded     | PASS   | 204.5
shared      | PASS   | 66.6
bundle      | PASS   | 229.8
memory-gate | PASS   | 100.0
diag        | PASS   | 109.9
rust        | PASS   | 282.5
lint        | PASS   | 112.3
asan        | FAIL   | 2.2

asan is environmental-red in this sandbox (sanitizer/asan_interface.h not 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 time
with MIMALLOC_GUARDED_SAMPLE_RATE=1 forcing every allocation onto its own guard-adjacent
page), is green.

Also verified directly:

  • c++ -x c++ -std=c++17 -c src/static.c -Iinclude -DMI_STATIC_LIB (Bun's exact
    build mode) compiles clean; nm -C on the resulting object shows both symbols T.
  • nm libmimalloc.a | grep -E "mi_heap_dump_json|mi_heap_get_seq" shows both T in every
    built variant (release, guarded/debug, MI_PPROF on and off).
  • test-heap-dump-json stable over 15 repeated runs each, plain and under
    MIMALLOC_GUARDED_SAMPLE_RATE=1.
  • cargo test -p mimalloc-pprof, cargo clippy -p mimalloc-pprof --all-targets,
    cargo fmt -p mimalloc-pprof -- --check all 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

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
zackees and others added 7 commits September 2, 2026 03:30
… 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
zackees force-pushed the bun-parity/p4-heap-dump-json branch from da89d43 to d8a256d Compare September 2, 2026 12:15
@zackees

zackees commented Sep 2, 2026

Copy link
Copy Markdown
Owner Author

Opus review: APPROVE after follow-ups (2769ede3, d8a256dc): seq 0 and reserved > 0 pinned by the test, formatting buffer widened, self-mutation caveat documented; Bun's heapStats JSON assertions all covered except the best-effort block-size membership (documented). Verified by the reviewer: byte-faithful port of Bun's mi_heap_dump_json/mi_heap_get_seq, no deadlock path, 20× concurrent + ASan clean, both symbols exported in Bun's single-TU build. Merging: reds are the designed run-macos-x64-dockur (golden image pending), ubuntu memory-gate drift (pre-existing on main), and the #236 Windows rust flake on both Windows rust jobs.

@zackees
zackees merged commit 7eaa366 into main Sep 2, 2026
44 of 48 checks passed
@zackees
zackees deleted the bun-parity/p4-heap-dump-json branch September 2, 2026 12:22
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
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
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bun parity P4: add mi_heap_dump_json / mi_heap_get_seq (bun:jsc heapStats dump) + stats.c snapshot fixes

1 participant