Skip to content

feat: pthread_atfork fork-safety handlers with lock-order contract - #289

Merged
zackees merged 8 commits into
mainfrom
bun-parity/p5-atfork
Sep 2, 2026
Merged

zackees merged 8 commits into
mainfrom
bun-parity/p5-atfork

Conversation

@zackees

@zackees zackees commented Sep 2, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Implements Bun parity P5: pthread_atfork fork-safety handlers with a POSIX repro #270 (Bun parity P5): pthread_atfork fork-safety handlers with a
    documented lock-order contract, plus a POSIX repro test landed first per the
    issue's Step 1.
  • src/subproc.c gains _mi_process_fork_prepare/parent/child, a 13-step lock
    order documented in a comment block at the top of the file and self-checked in
    MI_DEBUG builds (mi_fork_lock_order_assert).
  • Registered once in src/init.c's mi_process_init_once, POSIX only
    (#if !defined(_WIN32) && !defined(__wasi__)) -- never per heap (see "what the
    issue got wrong" below for why that distinction matters).
  • Wired into macOS's alloc-override-zone.c: the introspection force_lock/
    force_unlock/reinit_lock callbacks and the _malloc_fork_* DYLD interpose
    both call the same handlers, made idempotent by a nesting guard.
  • Child-side policy for the profiler/DHAT/memory-events: continue. Their state
    is ordinary process memory (profiler/DHAT records come from the raw-OS-layer
    arena per rule 4, never the hooked path) that survives fork() by plain
    copy-on-write; only each subsystem's own lock needs resetting. mi_prof_dump/
    mi_dhat_dump are exercised in the child by test-fork-locks.c.
  • test/test-fork-user-heap.c imported from oven-sh/mimalloc@942b8342 (MIT),
    with the two cases needing the not-yet-landed scavenger/tld registry disabled
    as #if 0 // Phase 7 (they don't compile against this tree).
  • MIMALLOC_FORKS.md's pthread_atfork row -> IMPORTED.

Repro (issue Step 1)

test/test-fork-locks.c: a churn thread holds heaps_lock/arena_reserve_lock
(mi_heap_new/mi_heap_delete + a large allocation in a loop) while the main
thread fork()s 200 times; each child does mi_malloc(64)/mi_free/_exit(0),
watchdog-guarded (5s alarm() + waitpid).

At the committed test's own scale (1 churn thread, 200 serialized forks) this
reproduced 0/200 failures on the pre-#270 tree, across 10+ runs (~2,000 forks
total) on this machine -- the race window is narrow, matching Bun's own
"Case A is probabilistic" caveat for their equivalent test. Since the issue asks
for an observed failure rate, I went further with an ad hoc, heavier
multi-threaded stress harness (not part of the committed suite: several forking
threads racing several heap-churn threads). That did reproduce the hazard
concretely on the pre-#270 tree: multiple single-threaded child processes left
permanently hung, confirmed via /proc/<pid>/wchan = futex_do_wait with
Threads: 1, never progressing (a single-threaded process blocked forever on a
futex is the unambiguous signature of an inherited, permanently-locked mutex --
nothing else produces it). After the handlers, the same heavier harness produced
zero hangs.

Verification

  • test-fork-locks / test-fork-user-heap: green x20 in Release, green x20 in
    Debug+MI_DEBUG_FULL+MI_PPROF=ON, no hangs.

  • Full ctest suite (36 tests, Debug+FULL+MI_PPROF=ON; 24 tests,
    MI_PPROF=OFF): 100% pass in both.

  • uv run ci/verify_local.py --keep-going:

    config result
    release PASS
    off PASS
    debug-full PASS
    guarded PASS
    shared PASS
    bundle PASS
    memory-gate PASS
    diag PASS
    rust PASS
    lint PASS
    asan FAIL (environmental -- see below)
  • asan is environmentally red in this sandbox: sanitizer/asan_interface.h is
    not installed, so CMake falls back to MI_TRACK_ASAN=OFF and verify_local
    correctly flags that as a failed gate. Confirmed this is unrelated to this PR --
    even mimalloc-test-api (no fork, untouched by this change) segfaults with zero
    ASan output under the same manual build.

  • A separate manual gcc -fsanitize=address -fno-omit-frame-pointer build (not
    through verify_local, MI_DEBUG=2) was attempted per the task instructions:
    it compiles clean, but running any test under it segfaults before printing an
    ASan report (confirmed on test-api too, not fork-specific) -- consistent with
    the same environmental gap, not a regression from this PR.

  • pyright (uv run --with 'pyright[nodejs]==1.1.411' pyright): 0 errors.

  • cargo run -p xtask -- amalgamate-c && amalgamate-h && check: clean; cargo test -p mimalloc-pprof: all green (regenerated in a separate, rust-only
    commit per rule 2).

Known limitations / what the issue got wrong

  1. mi_tld_t::theaps_lock is not covered. Bun's ported skeleton quiesces a
    per-subprocess tld registry (sp->tlds/tlds_lock) that walks every live
    thread's tld->theaps_lock. That registry is scavenger/park infrastructure
    that does not exist in this tree yet (lands with META: Bun parity — gaps, closure plan, and documentation corrections before proposing a rebase to oven-sh/bun #264 item 7 / Bun parity P7: background scavenger, page hole purging, and mi_on_thread_idle #272). Per the
    issue's own instruction to "port only the lock skeleton... leave a clearly
    marked // Phase 7: scavenger hook point," this gap is documented at every
    affected site in subproc.c and in MIMALLOC_FORKS.md, rather than
    approximated with an ad hoc walk (a heap's theaps list can reach the same
    tld through more than one theap -- one thread, several heaps -- and locking
    a non-recursive mutex twice inside the handler itself would turn a rare hang
    into a guaranteed one).
  2. The ported mi_fork_depth design (Bun's, as specified by the issue) assumes
    fork() calls are serialized across threads. glibc does not do this
    --
    verified empirically with a minimal pthread_atfork probe: concurrent
    fork() calls from different threads interleave their prepare/parent
    handlers essentially every time under load. The single-process-wide-atomic
    nesting counter, exactly as ported, is only correct for same-thread nesting
    (the macOS zone callback + pthread_atfork firing together for one
    fork()); under genuinely concurrent multi-threaded fork() it produced a
    real internal_lock_release_by_non_owner (an ABA race across overlapping
    fork "generations", caught by the P1 reentrancy checker -- not a false
    positive). Fixed here: mi_fork_depth is now a per-thread (mi_decl_thread)
    reentrancy count, and a real mutex (mi_fork_serialize_lock) gives true
    cross-thread exclusion around one fork "generation". This is not called out
    in the issue at all; I found it during evidence-gathering for the repro
    numbers above and fixed it rather than leaving a known-broken design in a
    safety-critical path.
  3. Also found (and independently confirmed unrelated, not fixed here, flagged
    for the user): a pre-existing assertion failure
    (mi_theap_is_valid, theap.c:71) under sustained multi-threaded
    mi_heap_new/mi_heap_delete churn -- reproduces with zero forking
    involved (a single churn thread run alone for ~90s trips it), on both the
    pre-Bun parity P5: pthread_atfork fork-safety handlers with a POSIX repro #270 and post-Bun parity P5: pthread_atfork fork-safety handlers with a POSIX repro #270 tree. Out of scope for this PR; worth its own issue.
  4. macOS CI is cross-built: the arm64 lane compiles only, and x64 execution runs
    under dockur/macos pending a golden image (per .github/workflows/cross.yml).
    So the zone/DYLD-interpose wiring in alloc-override-zone.c is
    compile-verified only in this PR -- not exercised by a running macOS test.

Merge gates checklist (CLAUDE.md rule 3)

  • c-unit on ubuntu with MI_PPROF=ON -- verified locally (verify_local +
    manual full ctest), CI pending.
  • MI_PPROF=OFF job -- verified locally (manual build + ctest), CI pending.
  • rust-native -- verified locally (cargo test -p mimalloc-pprof), CI
    pending.
  • windows-MSVC / windows-MinGW / macos -- not run locally (no such toolchain
    here); relying on CI. macOS execution is cross-built/compile-only per above.

Closes #270

🤖 Generated with Claude Code

https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S


Update: fixed after Opus review (both blockers reproduced and fixed)

  • Blocker 1 (compile break on macOS/Windows, all non-Linux CI red):
    _mi_process_is_initialized was declared only inside prim-tls.h's
    #if MI_TLS_MODEL_LOCAL branch; macOS (pthreads TLS model) and Windows don't
    take that branch. Fixed: unconditional extern in internal.h (dropped
    page.c's now-redundant local extern); the whole fork-handler definition
    block in subproc.c is now guarded with the same
    #if !defined(_WIN32) && !defined(__wasi__) init.c already uses to call
    it, so it's not dead code there either (rule 6).
  • Blocker 2 (deterministic AB-BA deadlock under MIMALLOC_PROF=1):
    reproduced exactly as described (3/3 hangs, Release, MI_PPROF=ON).
    Root cause confirmed: Bun's ported rule assumed hook locks
    (prof_lock/dhat_lock/memevt_cb_lock) are never taken from inside the
    allocation path itself, which is false in this tree (_mi_prof_on_alloc
    etc. are called from alloc.c/page.c while a heap's arena_pages_lock
    can still be held up the stack). Fixed: hook locks now sit innermost in the
    documented order, alongside out_buf_lock; also corrected the
    heap_main vs. non-main-heap arena_pages_lock ordering per the review's
    note on mi_heap_ensure_arena_pages's real nesting. Verified: the exact
    MIMALLOC_PROF=1 Release repro now passes 3/3 (and 20x); added MIMALLOC_DHAT=1
    / MIMALLOC_MEMORY_EVENTS=1 ctest variants alongside it so a future
    reordering regresses loudly in CI.
  • Q1 (mi_decl_thread violated the codebase's own Bun parity P1: bump upstream overlay pin bcee5a88 -> 6def7be9 (Bun's merge-base) + carry glibc 2.44 free(NULL) fix #266 rule): fixed --
    mi_fork_depth/mi_fork_lock_level are no longer mi_decl_thread.
    Replaced with a shared mi_fork_owner (_Atomic mi_threadid_t) + plain
    int depth, both protected by a real mutex (mi_fork_serialize_lock),
    needing no TLS at all. This also fixes the asymmetric-guard-latch gap
    (parent/child now check ownership symmetrically with prepare instead
    of blindly decrementing).
  • Q3: comment now says "modern glibc (>= 2.34)".
  • Secondary: dhat_once/memevt_once now reset in the child (new
    _mi_atomic_once_fork_child_reset helper) unless already resolved; added
    MI_DEBUG-only test hooks (_mi_test_hold_heaps_lock etc.) so
    test-fork-locks.c has a deterministic repro alongside the probabilistic
    one (which measured 0/200 on main, confirmed near-zero discriminating
    power on this machine).
  • Documented the residual, pre-existing mi_prof_visit/prof_lock
    inversion (visitor callback holds the lock, so an allocating visitor
    inverts the alloc-hook nesting) as a "visitor must not allocate" contract
    in profile.h -- out of scope to fix in a fork-safety phase.

Verified: test-fork-locks (base + all 3 env variants) and
test-fork-user-heap green 20x in Debug+FULL and 20x in Release, including
the exact review repro (MIMALLOC_PROF=1, Release) now 3/3 clean where it
was 3/3 hung. Full ctest green in debug-full (39 tests), release (32),
and MI_PPROF=OFF (27). uv run ci/verify_local.py --keep-going: 9/11 pass
(asan still environmentally red -- confirmed via test-api, unrelated to
this PR). Rust amalgamation regenerated in a separate commit;
cargo test -p mimalloc-pprof green.

Commits: 73f22a43 (original), da934391 (original rust), ee890758
(review fixes), 77a72e4d (review-fix rust amalgamation).

zackees and others added 2 commits September 2, 2026 04:02
fork() from a multithreaded process only clones the calling thread; any
mimalloc-internal lock held by another thread at that moment stays locked
forever in the child, hanging its first allocation. Implements #270 (Bun
parity P5):

- test/test-fork-locks.c: POSIX repro (Step 1) -- a churn thread holding
  heaps_lock/arena_reserve_lock racing 200 fork()s, watchdog-guarded.
- src/subproc.c: _mi_process_fork_prepare/parent/child with a documented
  13-step lock order (comment block at the top of the file), self-checked
  in MI_DEBUG builds. Ported design (not code) from oven-sh/mimalloc
  @942b8342, MIT; the tld->theaps_lock gap (needs Bun's scavenger tld
  registry, not yet in this tree) is called out as a known limitation and
  marked `// Phase 7: scavenger`.
- src/init.c: single pthread_atfork registration in mi_process_init_once,
  POSIX only -- never per-heap (Bun's own history: a per-heap registration
  exhausted glibc's atfork table and aborted BoringSSL).
- src/prim/osx/alloc-override-zone.c: wires the macOS zone force_lock/
  force_unlock/reinit_lock callbacks and the _malloc_fork_* DYLD interpose
  to the same handlers.
- src/{profile,dhat,memory-events,threadlocal,options}.c: fork handlers for
  each subsystem's own lock; profiler/DHAT/memory-events all continue in
  the child (their state is ordinary process memory, only the lock needs
  resetting).
- test/test-fork-user-heap.c: imported from oven-sh/mimalloc @942b8342,
  MIT; cases needing the scavenger/tld registry are disabled (`#if 0 //
  Phase 7`) since they don't compile against this tree yet.

Found and fixed during evidence-gathering: the depth counter as first
ported from Bun assumes fork() calls are serialized across threads, which
glibc does not do. Under genuinely concurrent multi-threaded fork() this
produced a real internal_lock_release_by_non_owner (an ABA race across
overlapping fork "generations"), caught by the P1 reentrancy checker.
Fixed by making the depth counter per-thread and adding a real mutex
(mi_fork_serialize_lock) for true cross-thread exclusion.

MIMALLOC_FORKS.md's pthread_atfork row -> IMPORTED.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
cargo run -p xtask -- amalgamate-c && amalgamate-h, after the C-core
fork-safety commit. cargo test -p mimalloc-pprof: all green.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
zackees and others added 6 commits September 2, 2026 05:02
Addresses Opus review of #289 (two blockers):

Blocker 1 (compile break, all non-Linux CI reds): _mi_process_is_initialized
was declared only inside prim-tls.h's `#if MI_TLS_MODEL_LOCAL` branch, which
macOS (pthreads) and Windows don't take. Declared unconditionally in
internal.h instead (dropped page.c's now-redundant local extern), and
guarded the whole fork-handler definition block in subproc.c with the same
`#if !defined(_WIN32) && !defined(__wasi__)` init.c already uses to call it,
so it is not dead code there (rule 6).

Blocker 2 (deterministic AB-BA deadlock under MIMALLOC_PROF=1): Bun's
ported rule ("locks held across an allocation go before arena_reserve_lock")
assumed those locks are never taken from inside the allocation path itself.
In this tree prof_lock/dhat_lock/memevt_cb_lock ARE alloc/free-hook locks
that can nest under a heap's arena_pages_lock a few frames up the same call
stack, so taking them first (steps 3-5) was backwards and deadlocked
against a concurrent mi_malloc under MIMALLOC_PROF=1 (reproduced 3/3 in
Release, confirmed via the actual call-stack nesting rather than Bun's
stated rule). Reordered: hook locks now sit innermost, alongside
out_buf_lock. Also corrected mi_heap_ensure_arena_pages's real nesting
(non-main heap's arena_pages_lock can sit outside heap_main's, the
opposite of the previous order) and documented the residual, pre-existing
mi_prof_visit/prof_lock inversion this phase does not close.

Also fixes (found during the same review pass):
- mi_fork_depth/mi_fork_lock_level were mi_decl_thread (__thread), which
  this codebase already knows is unsafe for hook-adjacent state reached
  from inside libSystem's fork machinery on macOS (see hooks-tld.h/#266).
  Replaced with a shared owner (_Atomic mi_threadid_t) + plain depth, both
  protected by mi_fork_serialize_lock, needing no TLS at all. Symmetric
  ownership checks in parent/child also close an asymmetric-guard-latch gap.
- dhat_once/memevt_once (env-var lazy-init guards) now reset in the child
  via a new _mi_atomic_once_fork_child_reset helper, unless already
  resolved.
- New MI_DEBUG-only test hooks (_mi_test_hold_heaps_lock etc) give
  test-fork-locks.c a deterministic repro alongside the probabilistic one
  (0/200 measured on main gave it near-zero discriminating power). New
  ctest variants register MIMALLOC_PROF=1/MIMALLOC_DHAT=1/
  MIMALLOC_MEMORY_EVENTS=1 env runs of the same binary so a future
  reordering regresses loudly in CI.

Verified: test-fork-locks (base + all three env variants) and
test-fork-user-heap green 20x in Debug+FULL and 20x in Release, including
the exact MIMALLOC_PROF=1 Release repro from the review (3/3 clean, was
3/3 hung). Full ctest green in debug-full (39), release (32), and
MI_PPROF=OFF (27). uv run ci/verify_local.py --keep-going: 9/11 pass
(asan environmentally red as before -- confirmed via test-api, unrelated
to this change; rust fails pending the following amalgamation commit).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
cargo run -p xtask -- amalgamate-c && amalgamate-h, after the review-fix
C-core commit (macOS/Windows compile break + AB-BA deadlock). cargo test
-p mimalloc-pprof: all green.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
…o src/fork.c

Review round 2 on #270. The hook locks were already innermost, but the outer
steps were never re-derived from the actual lock-nesting graph of this tree.

F1. `_mi_meta_zalloc` holds `theap_meta_lock` across a full `mi_theap_zalloc`
on `theap_meta`, whose heap IS `heap_main` -- so it nests `theap_meta_lock`
OUTSIDE `heap_main->arena_pages_lock` (arena.c:685), `arena_reserve_lock`
(arena.c:534) and the page-map lock (page-map.c:393). Prepare took all three
BEFORE `theap_meta_lock`: a latent deadlock against any thread starting up
(init.c:268 / theap.c:329 allocate a fresh tld/theap through `_mi_meta_zalloc`).
The whole order (steps 1-14) is now re-derived by tracing, for every internal
lock, what can be acquired while it is held; the resulting edge list is written
out as a table in src/fork.c and the acquisition sequence is a topological order
of it. Two structural consequences:

  * `mi_thread_locals_lock` is process-global but sits BETWEEN two
    per-subprocess levels (`heaps_lock` -> ... -> `theap_meta_lock`), and a
    heap's three locks do not share one level (`theaps_lock` must precede
    `theap_meta_lock` via `mi_heap_free_theaps` -> `_mi_meta_free`, while the
    MAIN heap's `arena_pages_lock` must follow it). Prepare therefore runs one
    pass per level over all subprocesses, not one walk per subprocess.
  * non-main `arena_pages_lock` stays outside `theap_meta_lock`
    (`mi_heap_free` frees under it), `heap_main`'s stays inside.

`mi_fork_lock_order_assert` used to check only that this handler's own acquires
were ordered -- true by construction. It is now backed by a real runtime
detector (MI_DEBUG>2): diagnostic.c's reentrancy checker already records each
lock's owning thread, so every acquire reads off which tracked locks the thread
already holds and records the nesting edge; every fork() asserts the edges
observed so far agree with the documented order. Prepare's own acquires are
excluded (they would just re-derive the documented order). Verified end to end:
swapping the documented levels of `mi_thread_locals_lock` and `theap_meta_lock`
makes an ordinary test-fork-locks run report the violation.

Rule 6: the handlers, the order table, the checker and the test hooks move to a
new src/fork.c (POSIX-only, included by src/static.c and CMake under the same
guard); subproc.c keeps two registry accessors.

F2. The "deterministic" test hook had no discriminating power: no-op'ing
prepare's `heaps_lock` acquire still passed 20/20, because the child re-inits
that lock unconditionally. The holder thread now POISONS the structure the lock
guards while holding it (detaches `sp->heaps`, restoring before release), and
the child reports via `_mi_test_heaps_lock_poison_observed()`. Measured: acquire
no-op'd 20/20 children see the poison; acquire restored 0/20. The false claims
in the test header and in the deterministic-repro design note are rewritten, and
`check_dump_in_child` now asserts `prof_ok`/`dhat_ok` when the corresponding
subsystem was actually started in the parent.

Also adds a `test-fork-locks-spawn-prof-env` ctest variant (MI_TEST_FORK_SPAWN=1
+ MIMALLOC_PROF=1) that spawns threads continuously during the 200 forks -- F1's
scenario.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
`src/static.c` now includes the new `src/fork.c` under
`#if !defined(_WIN32) && !defined(__wasi__)`; the amalgamator carries the same
guard through, so the sys crate picks up the fork handlers on POSIX and compiles
them away on Windows.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
…onestly

The spawn workload now holds up to 64 threads live at a time (detached, each
allocating 8 MiB and lingering) instead of joining every wave immediately, so
the meta theap has to keep allocating fresh tld/theap storage rather than
recycling one freed slot -- that is the `theap_meta_lock` nesting the re-derived
lock order is about.

It also REPLACES the heap-churn thread in spawn mode instead of running
alongside it: sustained `mi_heap_new`/`mi_heap_delete` churn concurrent with
sustained thread starts trips the pre-existing, fork-unrelated
`mi_theap_is_valid` assertion (theap.c:71) that this PR already flagged --
reproduced here 3/5 runs with a standalone churn+spawn program that never calls
fork(), and 0/6 with the spawner alone. Keeping the two workloads in separate
ctest variants keeps this test's signal about fork safety instead of importing
a known unrelated flake into CI.

The header comment now states the variant's real scope: it is a timing-based
workload, the `theap_meta -> arena/page-map` nestings are rare (a meta
allocation only reaches them on a cold page), and running it against the OLD
inverted order did not hang here in 200 forks. The deterministic evidence for
the order is the MI_DEBUG>2 observed-edge checker in src/fork.c.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
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

zackees commented Sep 2, 2026

Copy link
Copy Markdown
Owner Author

Update: review round 2 (F1 + F2)

Commits: cf15bb2b (C core), 7d8e203c (rust amalgamation, separate per rule 2), c0f622c3 (stress-test scoping), 0a10992b (merge of main).

The merge was needed to get CI to run at all: after #286 and #290 landed, this PR went CONFLICTING (src/static.c's include list — #286's heap-dump.c next to #270's fork.c) and GitHub silently schedules no pull_request workflow runs for a PR whose merge commit cannot be computed. Conflict resolved, amalgamation regenerated over the merged tree, all suites re-run below. It also picks up #290's timed_allocation_audit fix, which was the standing rust-native win-gnu failure.

F1 — the order is now derived, not asserted

You were right: the outer steps were never re-derived. _mi_meta_zalloc holds theap_meta_lock across a full mi_theap_zalloc on theap_meta, whose heap is heap_main (subproc.c:339), so an ordinary allocation slow path runs inside that lock. I re-read every mi_lock* site in src/ and what each critical section can call, and wrote the result out as an edge table at the top of the new src/fork.c. Summary (X -> Y = some real path holds X while acquiring Y):

lock can acquire while held evidence
mi_subprocs_lock heaps_lock, heap->theaps_lock _mi_subproc_prof_sync_force_slow, _mi_subprocs_unsafe_destroy_all
sp->heaps_lock theaps_lock, mi_thread_locals_lock, arena_pages_lock, os_abandoned_pages_lock, theap_meta_lock mi_subproc_unsafe_destroy -> _mi_thread_locals_done / _mi_heap_force_destroy -> mi_heap_free (heap.c:203)
heap->theaps_lock theap_meta_lock mi_heap_free_theaps (heap.c:174) -> _mi_theap_decref -> _mi_meta_free (theap.c:363); tld->theaps_lock only via try-acquire (theap.c:412), not a blocking edge
non-main heap->arena_pages_lock heap_main->arena_pages_lock, arena_reserve_lock, page-map lock, theap_meta_lock, os_abandoned_pages_lock mi_heap_ensure_arena_pages (arena.c:685) holds it across mi_arena_pages_alloc -> mi_heap_zalloc_aligned(heap_main,…) (arena.c:1544); mi_heap_free frees under it
mi_thread_locals_lock theap_meta_lock _mi_thread_local_create -> mi_thread_local_create_expand -> _mi_meta_zalloc_aligned (threadlocal.c:349)
sp->theap_meta_lock heap_main->arena_pages_lock, arena_reserve_lock, page-map lock, heap_main->os_abandoned_pages_lock _mi_meta_zalloc (subproc.c:181) -> mi_theap_zalloc(theap_meta) -> _mi_arenas_page_alloc -> arena.c:784/534, page-map.c:393
heap_main->arena_pages_lock — (leaf) for a main heap mi_heap_ensure_arena_pages only stores &arena->pages_main; mi_heap_free skips the loop (if (!is_main))
arena_reserve_lock — (leaf) mi_arena_reserve -> mi_arena_initialize -> mi_arenas_add is raw-OS + atomics
os_abandoned_pages_lock, page-map lock — (leaf) list splice / _mi_os_zalloc
prof_lock/dhat_lock/memevt_cb_lock (innermost) taken by the alloc/free hooks, i.e. under anything above
out_buf_lock (last) reachable from a warning under any lock above

Derived order — a topological order of that graph, which is not one walk per subprocess (a process-global lock sits between two per-subprocess levels, and a heap's three locks do not share a level), so prepare runs one pass per level:

1 mi_subprocs_lock            6 per sp: theap_meta_lock          11 prof_lock
2 per sp: heaps_lock          7 per sp: heap_main->arena_pages    12 dhat_lock
3 per sp/heap: theaps_lock    8 per sp: arena_reserve_lock        13 memevt_cb_lock
4 per sp/non-main heap:       9 per sp/heap: os_abandoned_pages   14 out_buf_lock
    arena_pages_lock         10 page_map->lock
5 mi_thread_locals_lock

Note theaps_lock (3) and non-main arena_pages_lock (4) end up on opposite sides of theap_meta_lock (6) from each other's old grouping — theaps_lock must precede it, main arena_pages_lock must follow it.

mi_fork_lock_order_assert now checks something real. The old assert only verified prepare's own sequence — true by construction. Under MI_DEBUG>2 there is now a runtime detector: diagnostic.c's reentrancy checker already records each lock's owning thread in debug_owner, so _mi_fork_lock_order_observe (called from _mi_lock_debug_after_acquire) reads off which tracked locks the acquiring thread already holds and records the nesting edge in a global bitmap; every fork() asserts that all edges observed so far agree with the documented order. Prepare's own acquires are excluded (they hold every level at once in the documented order, which would make the check tautological). Only process-lifetime locks are tracked (main subproc's 3, process heap_main's 3, the 5 globals) — a non-main heap's locks are freed with the heap and address-keyed tracking of them would read freed memory. The whole F1 cycle is inside the tracked set.

Detector verified end to end: deliberately swapping the documented levels of mi_thread_locals_lock and theap_meta_lock (and prepare's matching acquire order) makes an ordinary test-fork-locks run print

mimalloc: error: fork lock-order violation: mi_thread_locals_lock (step 6) was held while
acquiring subproc->theap_meta_lock (step 5) -- the order documented in src/fork.c is wrong,
or a new nesting was introduced

and abort. Restored: silent, and the full 40-test Debug+FULL suite runs clean with no violation reported — i.e. nothing the suite exercises contradicts the derived order.

Rule 6: handlers, order table, checker and test hooks moved to a new src/fork.c (POSIX-only; src/static.c and CMake include it under the same guard). subproc.c keeps two accessors (_mi_subprocs_head / _mi_subprocs_lock); init.c is unchanged apart from the comment pointer.

F2 — the deterministic hook now discriminates

You were right that it had none: the child re-inits heaps_lock unconditionally, so no-op'ing the acquire still passed. The holder thread now poisons the structure the lock guards while holding it — it detaches sp->heaps (saving the head) and restores it before releasing — and the child reports via the new _mi_test_heaps_lock_poison_observed(), exiting 3.

prepare's heaps_lock acquire deterministic_hold_repro
no-op'd (counterfactual) 20/20 children observed the poisoned window (FAIL: child N forked inside the poisoned heaps_lock window -- _mi_process_fork_prepare did not acquire subproc->heaps_lock)
restored (this tree) 0/20, 0 hangs

The false claims in the file header (lines 31-36) and in the deterministic-repro design note (142-160) are rewritten; check_dump_in_child now asserts prof_ok/dhat_ok when the corresponding subsystem was actually started in the parent.

Honest scope of the new stress variant

New ctest variant test-fork-locks-spawn-prof-env (MI_TEST_FORK_SPAWN=1 + MIMALLOC_PROF=1) keeps up to 64 threads live while forking 200 times, so every thread start goes through _mi_meta_zalloc under theap_meta_lock. But it is a timing workload, not a proof, and I am not going to claim more than I measured:

  • The edges the detector actually observes in that run are mi_subprocs_lock -> heaps_lock -> theaps_lock and mi_thread_locals_lock -> theap_meta_lock. The theap_meta_lock -> arena/page-map edges are real by inspection but rare at runtime — a meta allocation only reaches mi_heap_ensure_arena_pages / mi_arena_reserve / page-map growth on a cold page, and the meta theap recycles freed tld/theap slots. Tried MIMALLOC_ARENA_RESERVE down to 32 MiB and 64 live threads; they still did not fire.
  • Running the variant against the old (inverted) order did not hang here in 200 forks. So F1 was a latent inversion, not an immediately reproducible one, and the deterministic evidence for the fix is the detector experiment above, not a hang/no-hang pair. The stress variant is the cheap always-on complement.
  • Spawn mode replaces the heap-churn thread rather than running alongside it: sustained mi_heap_new/mi_heap_delete churn concurrent with sustained thread starts trips the pre-existing mi_theap_is_valid assertion (theap.c:71) this PR already flagged as item 3 — reconfirmed here 3/5 runs of a standalone churn+spawn program that never calls fork(), and 0/6 with the spawner alone. Keeping them in separate variants avoids importing a known unrelated flake into CI.

Verification

  • test-fork-locks base + MIMALLOC_PROF=1 + MIMALLOC_DHAT=1 + MIMALLOC_MEMORY_EVENTS=1 + spawn/prof, and test-fork-user-heap: 20/20 each, in Debug+MI_DEBUG_FULL+MI_PPROF=ON and in Release (240 runs, 0 hangs) — re-run in full after the merge, same result.
  • Full ctest: 41/41 Debug+FULL+PPROF, 34/34 Release (40/33 before the merge added feat: add mi_heap_dump_json / mi_heap_get_seq and snapshot-safe stats printing #286's test), 28/28 MI_PPROF=OFF.
  • gcc ASan (-DMI_TRACK_ASAN=ON -DMI_DEBUG_FULL=ON -DMI_PPROF=ON, so MI_DEBUG=3 + MI_GUARDED=1): configures with MI_TRACK_ASAN=ON and runs clean — test-fork-locks base and spawn/prof, and test-fork-user-heap, all pass with no ASan report. This also pins down the earlier "environmentally red" claim: verify_local's asan gate configures with clang (/run/current-system/sw/bin/clang), whose resource dir on this NixOS box has no sanitizer/asan_interface.h, so CMake downgrades to MI_TRACK_ASAN=OFF and the gate correctly fails. With the default cc (gcc) the header is found and the sanitizer really is enabled. Not a property of this PR either way.
  • cargo run -p xtask -- amalgamate-c && amalgamate-h && check clean (fork.c is inlined under the same platform guard); cargo test -p mimalloc-pprof green.
  • uv run ci/verify_local.py --keep-going (post-merge): release, off, debug-full, guarded, shared, bundle, memory-gate, diag, lint PASS; asan FAIL for the clang-toolchain reason above; rust FAIL on bench-harness --test rejections::benchmark_rejects_partial_or_extra_child_output — that one is load-induced flake, not a regression: it passes 5/5 run standalone on this exact tree, it is a pure-Rust harness test that spawns stress-child with a 10 s max_duration_secs (11 configs compiling in parallel is enough to blow it), it touches no mimalloc C, and CI's rust-native is green on this SHA. The pre-merge run of verify_local was 10/11 with only asan red.
  • fork.c compiles warning-free under -Wall -Wextra in Release, Release+MI_PPROF=OFF and Debug+FULL.

CI on 0a10992b: 8/9 green — c-unit (all 17 jobs: MSVC windows-latest, win-gnu, ubuntu, shared, guarded, debug-full, ctest-pprof-off, memory-gate, diagnostic-gates, bundle-roundtrip, isa-baseline x64+arm), rust-native, asan, cross, fuzz, amalgamation-drift, doc-snippets, benchmark-sentinel all success. The one red is macos-bundles: No golden macOS disk under cache key 'macos-x64-golden-ventura-v1' — the #277 image has not been published yet, so that job cannot bootstrap itself; it is red on main too and is unrelated to this PR. macOS coverage here is therefore cross (arm64 compile) only, as already noted in the PR description.

@zackees

zackees commented Sep 2, 2026

Copy link
Copy Markdown
Owner Author

Opus review (three rounds): APPROVE. Final round reproduced both proofs: swapping two documented levels trips the MI_DEBUG>2 lock-order detector (fork lock-order violation: mi_thread_locals_lock (step 6) was held while acquiring subproc->theap_meta_lock (step 5)), and removing the heaps_lock acquire makes the poisoning fork test fail (child forked inside the poisoned heaps_lock window); restored, 18/18 across Release / Debug FULL / gcc ASan × {base, PROF, DHAT, MEMORY_EVENTS, spawn-stress, user-heap}. Nesting edges spot-checked in source (theaps→theap_meta via _mi_theap_decref; non-main arena_pages→heap_main via mi_arena_pages_alloc; theap_meta→heap_main arena/page-map via _mi_meta_zalloc). The glibc ≥2.34 concurrent-fork claim was independently confirmed (prepare depth 4–5 on glibc 2.42), so mi_fork_serialize_lock is load-bearing.

Follow-up (non-blocking, tracked on #264): anonymous mi_atomic_do_once sites (page-map.c:365, profile.c:889, prim-tls.c:124/165/182, init.c) are neither acquired in prepare nor reset in the child — first-init only, narrow.

Merging; only red is the designed run-macos-x64-dockur (golden image pending).

@zackees
zackees merged commit 5fbadef into main Sep 2, 2026
46 of 47 checks passed
@zackees
zackees deleted the bun-parity/p5-atfork branch September 2, 2026 13:26
zackees added a commit that referenced this pull request Sep 2, 2026
…rate amalgamation)

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
P5 (#289) landed a handler-only pthread_atfork design (src/fork.c) without a
persistent "we are a forked child" flag, so the P6 teardown protocol's
mi_heap_visit_page_claim (arena.c) was left with its forked-child branch
deliberately dropped ("add it back when it lands"). Merging origin/main
exposed the gap: test-fork-user-heap's case_a forks while a background
thread churns a shared heap, and the child's mi_heap_delete walked into a
page still queued on that (now-dead) thread's torn theap. The
!mi_page_is_abandoned force-seize path took the page without reconciling
its used/local_free/xthread_free bookkeeping, tripping
mi_page_is_valid_init downstream -- a regression against a previously
green test (confirmed passing 3/3 on origin/main alone via a side-by-side
worktree, failing ~1/200 children on this branch).

Fix, imported from oven-sh/mimalloc @ 942b8342 (MIT), issue #271 / Bun
parity P6:
- src/fork.c: add the missing `_mi_process_is_forked_child` flag (set once
  in `_mi_process_fork_child`, never cleared) that P5's design omitted.
- src/arena.c: restore `mi_heap_visit_page_claim`'s forked-child branch,
  which re-derives page ownership from the page/arena bitmaps instead of
  trusting a dead thread's theap bookkeeping.
- src/heap.c: `mi_heap_detach_theaps` now skips walking (and abandoning
  pages from) a theap whose owning thread did not survive the fork --
  its pages are picked up by the claim-walk's forked-child branch instead.

Verified: test-fork-user-heap 20x direct + in ctest (0/4000 fork-cycle
failures across runs), full ctest suite (47/47) x3 clean, real ASan build
(clang from ~/.clang-tool-chain, 46/46 + 4x direct fork-user-heap), and the
imported P6 corpus (heap-teardown/heap-mt/heap-churn/heap-aba/
heap-delete-race/commit-fail) 20x each (140/140).

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
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 P5: pthread_atfork fork-safety handlers with a POSIX repro

1 participant