Skip to content

Reset LocalAllocator when returning it to the pool - #1435

Merged
Aidan63 merged 2 commits into
masterfrom
fix-pooled-allocator-race
Oct 29, 2026
Merged

Aidan63 merged 2 commits into
masterfrom
fix-pooled-allocator-race

Conversation

@Simn

@Simn Simn commented Oct 28, 2026

Copy link
Copy Markdown
Member

When a thread registers, RegisterCurrentThread takes a LocalAllocator from the pool in GetPooledAllocator, which holds gThreadStateChangeLock only for that step. AttachThread then calls AddLocal, which takes the lock again. In between, the allocator is neither in the pool nor in mLocalAllocs.

A collection resets every registered allocator at the end of Mark and every pooled one in ClearPooledAlloc. An allocator caught in that window gets neither reset. It keeps its holes, the collection may reclaim those blocks for other allocations, and the newly attached thread then allocates over live objects.

The fix calls Reset() at the start of AttachThread. That only drops the allocator's current holes, so the thread starts with a fresh allocation region.

This is easy to hit when threads attach and detach very often. hxcpp_luv_io's Work.queue registers the libuv worker thread with SetTopOfStack(&top, true) and unregisters it with UnregisterCurrentThread() for every work item. hxcoro's LuvDispatcher sends every dispatch through Work.queue. With that dispatcher, about 25% of hxcoro's C++ test runs on Windows crashed with access violations in unrelated objects (6 of 30). With this change, there were no access violations in 60 runs.

🤖 Generated with Claude Code

Between GetPooledAllocator and AddLocal, the allocator is neither pooled nor
registered, so a collection in that window does not reset it. The thread then
allocates from holes that the collection may have handed out again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Aidan63

Aidan63 commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

Part of me wonders if a local allocator should be reset when pulled from the pool GetPooledAllocator or put into it ReturnToPoolLocked, but I'm not confident enough in the GC internals to say one way or another. So lets go with.

Pooled allocators now never hold holes, instead of resetting them when a
thread attaches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Simn

Simn commented Oct 29, 2026

Copy link
Copy Markdown
Member Author

Moved the reset into ReturnToPoolLocked, since that gives the simplest invariant: a pooled allocator never holds holes. Nothing allocates on an allocator while it sits in the pool, so it stays empty until a thread attaches it, and the window between GetPooledAllocator and AddLocal no longer matters. Resetting in AttachThread also fixed the race, but it ran for freshly constructed allocators too, which shows the reset belongs to the pool rather than to attaching. ReturnToPoolLocked is defined before LocalAllocator, so it goes through ClearPooledAlloc, the helper Mark already uses for pooled allocators.

I didn't remove the ClearPooledAlloc loop at the end of Mark. It should now be a no-op, but I didn't want to mix that into this fix.

Tested with hxcoro's C++ tests from HaxeFoundation/hxcoro#164, which runs the suite on LuvDispatcher: 60 of 60 runs passed, with no access violations or hangs.

🤖 Generated with Claude Code

@Simn

Simn commented Oct 29, 2026

Copy link
Copy Markdown
Member Author

I don't fully understand what this whole "hole" business is about, this this fix (still) does help with my access violation problems.

@Aidan63

Aidan63 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

IIUC when an allocation is moved / collected from a block a "hole" is recorded in that block where the object previously lived. Future allocations into that block will check for a hole large enough to reuse before resorting to bump allocating at the end of the block / getting a fresh block.
But since the allocators hole collection wasn't being reset it could be given a new block by the global allocator but still have the hole ranges from the previous block, allowing it to incorrectly allocate over live objects.

@Simn

Simn commented Oct 29, 2026

Copy link
Copy Markdown
Member Author

Right, makes sense. That makes me wonder why this isn't a more common issue, but I suppose there's a timing component here with the allocator being in an intermittently bad state.

@Simn

Simn commented Oct 29, 2026

Copy link
Copy Markdown
Member Author

Aidan's description of the outcome is right: the allocator ends up allocating over live objects. Two details of the mechanism are different, though.

Holes aren't recorded when objects are moved or collected. Immix divides each block into lines and marks the lines that contain live objects during a collection. At the end of the collection, each block's holes are recomputed from those marks as runs of unmarked lines (mRanges, mHoles). Objects that died simply leave their lines unmarked.

The allocator keeps its old block, not a new block with old holes. A LocalAllocator caches an allocation window in its current block: allocBase, spaceStart/spaceEnd, a pointer to the block's mRanges and its position in them. When it does call GetFreeBlock, it reloads all of that from the new block, so those fields stay consistent. The problem is what a collection does to the block it's still holding:

  1. The thread detaches, and the allocator goes into the pool. Its window still points into the unused end of its current block.
  2. The pooled allocator is pulled out again. Before AddLocal registers it, a collection runs. The allocator is neither pooled nor registered, so the collection neither waits for it nor resets it.
  3. The collection recomputes that block's holes. The unused window has no live objects, so it counts as free. createFreeList then marks the block mOwned = false and puts it on the global free list.
  4. Another thread gets that block from GetFreeBlock and allocates into those lines. The newly attached thread still has the stale window and allocates into the same memory. Two threads now put objects at the same addresses, and one overwrites the other's live objects. The block's mRanges were also rewritten, so the stale hole index and count no longer match them either.

Resetting at the end of each collection exists to prevent exactly this. Every registered allocator drops its window there, and only blocks that nobody holds go back to the free list. The allocator caught in the window misses that reset. With this PR, pooled allocators never hold a window in the first place.

Why this is rare: all of these have to coincide:

  • A collection has to start in the few instructions between GetPooledAllocator and AddLocal.
  • The allocator must have been pooled with space left in its block, which is common.
  • Another thread must be handed that same block and allocate into it before the stale window is used up.
  • The overwrite then has to land on an object that is used later.

Most programs attach a thread once, so they almost never hit the window. hxcpp_luv_io's Work.queue attaches and detaches a libuv worker thread for every work item. With LuvDispatcher, that happens thousands of times per test run while other threads allocate heavily and trigger collections. Even then, the crash shows up later in an unrelated object, which is why the access violations looked random.

🤖 Generated with Claude Code

@Simn Simn changed the title Reset pooled LocalAllocator when attaching a thread Reset LocalAllocator when returning it to the pool Oct 29, 2026
@Aidan63
Aidan63 merged commit eeec6e9 into master Oct 29, 2026
506 of 507 checks passed
Simn added a commit to HaxeFoundation/hxcoro that referenced this pull request Oct 29, 2026
- Make the shutdown check atomic: numPending switches from 0 to -1, and dispatch
  increments it with a CAS that fails once it is negative.
- Remove Luv.shutdown() from the test runner. The crashes were caused by
  HaxeFoundation/hxcpp#1435, not by libuv's library destructor.
- Use a markdown list in the createDefault doc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Simn added a commit to HaxeFoundation/hxcoro that referenced this pull request Oct 29, 2026
* try C++ LuvDispatcher again

* Fix LuvDispatcher loop shutdown crash (uv__queue_done assertion) and post-exit ThreadInfoHolder segfault (#165)

* ...

* Initial plan

* Fix LuvDispatcher crash: use shutdownLoop instead of stopLoop before freeLoop

The Ubuntu CI job failed with:
  uv__queue_done: Assertion `uv__has_active_reqs(req->loop)' failed.

Root cause: the main thread freed the libuv loop (via freeLoop) while a
worker thread was still executing uv__queue_done cleanup after its work
callback. The old stopLoop/freeLoop sequence left async close callbacks
and work-completion callbacks unprocessed.

Fix: replace stopLoop(loop) with shutdownLoop(loop), which calls
uv_walk (closes any remaining handles) then uv_run(UV_RUN_DEFAULT)
to drain all pending callbacks (onAfter for work items, close callbacks
for async handles) before the loop is freed.

Calling stopLoop would set stop_flag=1, causing uv_run in shutdownLoop
to exit immediately without processing callbacks, so it must be removed.

Co-authored-by: Simn <634365+Simn@users.noreply.github.com>

* Fix LuvDispatcher shutdown: use drainLoop (no uv_walk, no GCFreeZone) and blocking pool shutdown

Co-authored-by: Simn <634365+Simn@users.noreply.github.com>

* Revert Setup.hx to use shutdownLoop; keep pool.shutDown(true) fix

Co-authored-by: Simn <634365+Simn@users.noreply.github.com>

* install gdb

* sudo

* Fix LuvDispatcher crash: run work directly on loop thread, not via Work.queue

Co-authored-by: Simn <634365+Simn@users.noreply.github.com>

* Revert "Fix LuvDispatcher crash: run work directly on loop thread, not via Work.queue"

This reverts commit 6178fd7.

* manually shutdown libuv library on test completion

---------

Co-authored-by: Simon Krajewski <simon@haxe.org>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Simn <634365+Simn@users.noreply.github.com>
Co-authored-by: Aidan Lee <aidan.lee@evcam.com>

* Drain LuvDispatcher before closing its handle

Work that is still running when a setup is closed can dispatch more work, e.g.
a channel continuation that resumes its own continuation asynchronously. That
sent on the already closed async handle, and the work was dropped. shutDown now
runs the loop until all dispatched objects have finished, and dispatching
after that throws, like FixedThreadPool does. The dispatcher is also shut down
before the scheduler, because running work might still use it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Address review comments on LuvDispatcher shutdown

- Make the shutdown check atomic: numPending switches from 0 to -1, and dispatch
  increments it with a CAS that fails once it is negative.
- Remove Luv.shutdown() from the test runner. The crashes were caused by
  HaxeFoundation/hxcpp#1435, not by libuv's library destructor.
- Use a markdown list in the createDefault doc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Simn <634365+Simn@users.noreply.github.com>
Co-authored-by: Aidan Lee <aidan.lee@evcam.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@Simn
Simn deleted the fix-pooled-allocator-race branch October 30, 2026 10:09
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.

2 participants