Skip to content

Get C++ LuvDispatcher working - #164

Merged
Simn merged 7 commits into
masterfrom
cpp-luv-dispatcher-investigation
Oct 29, 2026
Merged

Simn merged 7 commits into
masterfrom
cpp-luv-dispatcher-investigation

Conversation

@Simn

@Simn Simn commented Feb 27, 2026

Copy link
Copy Markdown
Member

Let's finally find out what's with it!

@Simn

Simn commented Feb 27, 2026

Copy link
Copy Markdown
Member Author

@copilot Please check the C++ failures with this dispatcher!

Copilot AI commented Feb 27, 2026

Copy link
Copy Markdown
Contributor

@Simn I've opened a new pull request, #165, to work on those changes. Once the pull request is ready, I'll request review from you.

Copilot AI and others added 2 commits March 1, 2026 13:16
…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>
Comment thread src/hxcoro/run/Setup.hx Resolved
@Simn

Simn commented Mar 1, 2026

Copy link
Copy Markdown
Member Author

Oh no, it segfaulted again...

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

Simn commented Oct 28, 2026

Copy link
Copy Markdown
Member Author

Notes on the segfault after all tests pass, for when we pick this up again. I haven't reproduced it, because I only had a Windows machine, so this is a theory that fits the CI history.

Probable mechanism (Linux and macOS)

  1. In hxcpp, every non-Haxe thread that calls Thread.current() gets a thread_local ThreadInfoHolder. Its destructor calls hx::GCRemoveRoot. This was HXCPP_THREAD_INFO_LOCAL in the old Thread.cpp (since #910), and #1336 kept the pattern in src/hx/thread/ThreadImpl.cpp.
  2. GCRemoveRoot erases from sgRootSet in src/hx/gc/Immix.cpp. That's a plain static std::unordered_set, so it's destroyed during exit(). sGCRootLock is a heap pointer and survives.
  3. On non-Windows platforms, libuv marks uv_library_shutdown() as __attribute__((destructor)) (libuv 1.48.0, src/uv-common.c). It runs from _dl_fini, after the executable's C++ static destructors, and uv__threadpool_cleanup() joins the worker threads.
  4. When a worker thread that has a ThreadInfoHolder exits there, GCRemoveRoot calls erase on the destroyed set. Whether that crashes depends on what's left in the freed memory, which would explain the flakiness.

Fits the CI history:

  • Before Luv.shutdown() (which calls uv_library_shutdown() early) was added to the test runner, C++ failed on ubuntu, macOS and Windows.
  • With it (7424a68, run 22543247617), ubuntu and macOS passed, and only Windows failed, with exit code 1 rather than a crash code. libuv disables the destructor on Windows, so that failure is probably a different problem, and the logs are gone.

Still open

  • I didn't find what calls Thread.current() on a libuv worker. hxcoro doesn't do it directly, but the std does in several places, including EventLoop and thread callbacks.
  • Luv.shutdown() in the test runner only protects our tests. Any program using createLuv could crash the same way at exit. A more robust fix would be in hxcpp: make sgRootSet immortal (heap-allocated and never freed), like sGCRootLock, so that a late GCRemoveRoot is harmless. Alternatively, hxcpp_luv_io could register uv_library_shutdown with atexit once hxcpp is initialized, so that it runs before the static destructors.
  • createLuvThreadPool used a non-blocking pool.shutDown(). That lets Haxe threads, which always have a ThreadInfoHolder, exit during the same teardown. The merge below makes it blocking, like createThreadPool.

Branch state

I merged master locally (not pushed yet). The merge moves Luv.shutdown() into the new atest Main.hx, between runner.run() and Sys.exit, and keeps createLuv() as the C++ default. Eval passes. I couldn't test C++ locally because of HaxeFoundation/haxe#13091, a coroutine codegen bug that makes hxcoro.generators.Yield fail to compile on C++. It isn't related to this PR.

@Simn

Simn commented Oct 28, 2026

Copy link
Copy Markdown
Member Author

Update, after reproducing the crash locally on Windows. This replaces my previous comment: the theory about a crash at exit on Linux and macOS was based on job names without logs, and CI only ever failed on Windows here.

Reproduction

With this branch (LuvDispatcher as the C++ default), about 25% of C++ test runs on Windows crash partway through the run with access violations (6 of 30). The tests that are running when it happens vary. The same binary with HXCORO_DISPATCHER=threadpool or trampoline had no crashes in 40 runs each. With a crash handler, the stack traces were all on libuv worker threads or in LuvDispatcher.loopWork, reading garbage in unrelated objects (channels, PagedDeque, VecDeque, Tls, continuations, vtables). So the GC was corrupting memory in general.

Main cause: HaxeFoundation/hxcpp#1435

Work.queue in hxcpp_luv_io registers the libuv worker with the GC for every work item, and LuvDispatcher sends every dispatch through it. When a thread registers, hxcpp takes an allocator from its pool and only registers it afterwards. If a collection happens in between, the allocator is neither pooled nor registered, so it isn't reset, and the thread then allocates over live objects. With the fix from that PR, there were no access violations in 60 runs. Keeping the workers registered between work items, with no hxcpp change, also gave 0 of 60.

Smaller problems in hxcpp_luv_io (not the cause)

These go against hxcpp's rule that only registered threads outside a GC-free zone may touch the root set. The GC walks the root set without a lock. Fixing them didn't change the crash rate, but they should still be fixed:

  • onCallback in HxcppLuvWork.cpp destroys its RootedObject (GCRemoveRoot) after UnregisterCurrentThread().
  • The uv_close callbacks in timer::close and async::close remove roots while the loop thread is in the GC-free zone of runLoop.

I have local patches for all three. Registering each worker once, instead of for every work item, would also be worth considering in Work.queue.

Still open with the hxcpp fix applied, out of 60 runs

  • 1 libuv assertion during teardown: !(handle->flags & UV_HANDLE_CLOSED) in uv__async_endgame, while LuvDispatcher shuts down after Issue124.testPrime. Something still sends on an async handle that the dispatcher or scheduler has already closed.
  • 2 hangs in Issue86.test (50 tasks writing to an unbounded channel). Probably a lost wakeup or a dispatch that gets dropped. I haven't investigated these yet.

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>
Comment thread tests/src/Main.hx Resolved
Comment thread src/hxcoro/run/Setup.hx Resolved
Simn and others added 2 commits October 29, 2026 16:36
- 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
Simn marked this pull request as ready for review October 29, 2026 15:47
@Simn

Simn commented Oct 29, 2026

Copy link
Copy Markdown
Member Author

I think this is finally in a good place now. The only related PR that's still open is HaxeFoundation/hxcpp#1436, and that has been a rare occurrence. I'll merge this if CI is green to get more runs and more data.

@Simn
Simn merged commit 1e59a68 into master Oct 29, 2026
52 checks passed
@Simn
Simn deleted the cpp-luv-dispatcher-investigation branch October 29, 2026 19:51
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