Skip to content

Fix thread pool shutdown order - #534

Merged
lalinsky merged 2 commits into
mainfrom
fix-thread-pool-shutdown-order
Jun 27, 2026
Merged

lalinsky merged 2 commits into
mainfrom
fix-thread-pool-shutdown-order

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Fixes #524.

Problem

Thread-pool completion callbacks reach back into the event loop and write its eventfd. In loopLinkedWorkComplete the worker thread first publishes the result (work_completions.push) and then calls loop.wake() → backend.wake() → eventfd_write. These are two separate steps, so the worker can be preempted between them. Meanwhile the loop observes the published completion, finishes, and gets torn down — and the worker's trailing wake() then writes to a closed eventfd:

thread panic: eventfd_write: write failed: .BADF
  src/os/eventfd.zig:120  in eventfd_write
  src/ev/thread_pool.zig:241  in runTasks

The violated invariant is that the loop must outlive the thread pool's threads. The old ThreadPool.stop() only signalled shutdown; only deinit() joined the threads. So nothing guaranteed the pool was quiescent before a loop was closed — neither in the failing test nor in Runtime.deinit (which closed loops at shutdownWorkers()/main_executor.deinit() while the pool wasn't joined until later).

Fix

  • ThreadPool.stop() now performs the full hard stop: set shutdown, drop queued work, refuse new submissions, and join all worker threads (idempotent). After it returns, no worker thread exists, so no completion callback can fire. The pool object stays valid until deinit().
  • submit() drops work when shutdown is set (also prevents a post-stop spawnThread), so executors still tearing down can safely call into it.
  • ThreadPool.deinit() is now just stop() + free the workers list.
  • Runtime.deinit() reordered to: stop+join the pool (all loops still alive) → shut down executors → deinit pool → deinit executors.
  • Tests reordered so the pool is stop()-ed (joined) before loop.deinit(); the blocker-based cancel tests unblock the worker before the join so it can't deadlock.

Behavior note

submit() after stop() now silently drops the work without firing its completion. This is intentional for shutdown ("all tasks are dropped"); in practice nothing submits post-stop since all tasks are already complete.

Testing

  • Full native unit suite passes (io_uring and -Dbackend=epoll).
  • cancel: work before run (the reported failure) and the cancel/fs/ThreadPool groups pass under aarch64-linux qemu with epoll. (io_uring is unavailable under qemu; the original CI failure was on the epoll path.)

Thread-pool completion callbacks wake the owning event loop (writing its
eventfd). The worker publishes the result and then calls loop.wake() as two
separate steps, so it can be preempted in between; the loop can finish and be
torn down before the trailing wake(), which then writes to a closed eventfd
(eventfd_write: .BADF). Fixes #524.

The invariant is that the loop must outlive the pool's threads. Previously
stop() only signalled shutdown and only deinit() joined, so nothing guaranteed
the pool was quiescent before a loop was closed.

- ThreadPool.stop() now drops queued work, refuses new submissions, and joins
  all worker threads (idempotent). After it returns no completion callback can
  run. The pool object stays valid; submit() drops work once stopped.
- ThreadPool.deinit() is now just stop() + free the workers list.
- Runtime.deinit() stops/joins the pool first (all loops still alive), then
  shuts down executors, then deinits the pool, then deinits executors.
- Tests reordered to stop() the pool before deinit'ing the loop; blocker-based
  cancel tests unblock the worker before the join.
@coderabbitai

coderabbitai Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

Pull request was closed or merged during review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 56adb41b-d1ab-4ab3-90d8-0b60ea438f73

📥 Commits

Reviewing files that changed from the base of the PR and between b3dc6bb and 70a1a22.

📒 Files selected for processing (1)
  • src/ev/thread_pool.zig

📝 Walkthrough

Walkthrough

Thread pool shutdown now runs through an idempotent stop() path that joins workers and rejects submissions after shutdown. Runtime.deinit() stops and deinitializes the pool earlier, and the cancellation and file tests now stop pools before loop teardown.

Changes

Thread pool shutdown ordering

Layer / File(s) Summary
ThreadPool stop and submit
src/ev/thread_pool.zig
ThreadPool.deinit() delegates shutdown and joining to stop(), stop() becomes idempotent and broadcasts queue_not_empty, and submit() drops work after shutdown.
Runtime teardown order
src/runtime.zig
Runtime.deinit() stops and deinitializes the thread pool earlier in teardown, before worker shutdown and executor loop teardown, and keeps the task_count == 0 assertion before pool deinit.
Test teardown defers
src/ev/test/cancel.zig, src/ev/test/fs.zig, src/ev/test/thread_pool.zig
Cancellation, file, and thread-pool tests add deferred thread-pool stopping before loop teardown, and the cancellation tests reorder blocker_event.set() around the stop defer.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • lalinsky/zio#214 — Also changes cancel.zig synchronization and teardown ordering around blocker_event.set().

Poem

The pool shut down with a tidy click,
workers bowed out, quick and slick.
Loops stayed alive until the last wake,
then tests closed up for the teardown’s sake.
Quiet code, one less late-night trick.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: fixing thread pool shutdown order.
Description check ✅ Passed The description is directly about the thread pool shutdown bug and the same fix described in the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-thread-pool-shutdown-order

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/ev/thread_pool.zig (1)

145-167: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Apply the shutdown guard before inline execution too.

When builtin.single_threaded or max_threads == 0, Line 146 runs work inline before the new shutdown check at Line 162. That means submit() after stop() still executes the work and completion callback in the disabled-pool mode.

Proposed fix
     pub fn submit(self: *ThreadPool, work: *Work) void {
+        self.queue_mutex.lock();
+        const shutdown = self.shutdown;
+        self.queue_mutex.unlock();
+        if (shutdown) return;
+
         if (builtin.single_threaded or self.max_threads == 0) {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/ev/thread_pool.zig` around lines 145 - 167, The shutdown check in
ThreadPool.submit currently happens only on the queued path, so inline execution
still runs after stop() when builtin.single_threaded or max_threads == 0. Move
the self.shutdown guard to the start of submit() before the inline-work branch,
and return early there as well so work.func, work.c.setResult/setError, and
completion_fn are skipped once the pool is shut down.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/ev/thread_pool.zig`:
- Around line 121-128: The ThreadPool stop path currently only sets shutdown in
stop(), but leaves pending items in self.queue, which can still be canceled
later and invoke completion_fn after shutdown. Update ThreadPool.stop to fully
drain or detach any queued work before releasing queue_mutex, using the existing
queue/shutdown handling in ThreadPool.cancel and the queue links so no callbacks
can fire after stop. Make sure the stop() and cancel() paths preserve the
no-callback-after-stop invariant by preventing any remaining queued completion
from being removed and executed after shutdown.

---

Outside diff comments:
In `@src/ev/thread_pool.zig`:
- Around line 145-167: The shutdown check in ThreadPool.submit currently happens
only on the queued path, so inline execution still runs after stop() when
builtin.single_threaded or max_threads == 0. Move the self.shutdown guard to the
start of submit() before the inline-work branch, and return early there as well
so work.func, work.c.setResult/setError, and completion_fn are skipped once the
pool is shut down.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8ab11529-35d6-403f-91c6-a7790e5df39c

📥 Commits

Reviewing files that changed from the base of the PR and between c3e5aea and b3dc6bb.

📒 Files selected for processing (5)
  • src/ev/test/cancel.zig
  • src/ev/test/fs.zig
  • src/ev/test/thread_pool.zig
  • src/ev/thread_pool.zig
  • src/runtime.zig

Comment thread src/ev/thread_pool.zig Resolved
After stop() joins the workers, items submitted but never picked up can
remain linked in the queue. A later cancel() could remove one and invoke
its completion_fn (waking a loop being torn down), breaking the
"no callback after stop" invariant. Drain the queue under the lock so
this can't happen and the documented "drop any queued work" holds.
@lalinsky
lalinsky merged commit 539a494 into main Jun 27, 2026
30 checks passed
@lalinsky
lalinsky deleted the fix-thread-pool-shutdown-order branch June 27, 2026 10:53
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.

Fix thread pool shutdown order

1 participant