Skip to content

Fix ref count race in spawn() and spawnBlocking() - #90

Merged
lalinsky merged 1 commit into
mainfrom
fix-spawn-ref-count-race
Oct 27, 2025
Merged

lalinsky merged 1 commit into
mainfrom
fix-spawn-ref-count-race

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

Fixes a use-after-free race condition in spawn() and spawnBlocking() where the ref count for the JoinHandle was incremented after scheduling the task.

The Problem

When spawning tasks to different executors (or thread pool), the following race could occur:

  1. spawn() schedules task to remote executor/thread pool
  2. Task starts and completes immediately on another parallel thread
  3. Task's ref count drops from 1→0 and gets destroyed
  4. spawn() tries to increment the freed ref count → assertion failure in RefCounter.incr()
Thread A (spawning):              Thread B (executor):
--------------------              -------------------
create task (ref=1)
add to registry
scheduleTask() →                  → picks up task
                                  → runs task  
                                  → completes
                                  → ref_count.decr() (1→0)
                                  → task destroyed
incr() on freed memory 💥

This was most visible in multi-executor tests where trivial tasks could complete extremely quickly on parallel threads.

The Fix

Both Executor.spawn() and Runtime.spawnBlocking() now:

  • Increment the ref count BEFORE scheduling/submitting the task
  • This ensures ref count goes 1→2 before the task becomes visible to other threads
  • Added proper errdefer cleanup in case scheduling fails

Test Plan

  • All existing tests pass
  • The macOS CI crash that triggered this investigation should now be fixed

The ref count for the JoinHandle was being incremented AFTER scheduling
the task, which created a race condition:

1. spawn() schedules task to remote executor (or thread pool)
2. Task starts and completes immediately on another thread
3. Task's ref count drops from 1→0 and gets destroyed
4. spawn() tries to increment the freed ref count → CRASH

The fix increments the ref count BEFORE scheduling, ensuring the task
has 2 references (runtime + JoinHandle) before it can start running.
This prevents the task from being destroyed before the JoinHandle is
created.

This race was most visible in tests with multiple executors where
trivial tasks could complete extremely quickly on parallel threads.
@coderabbitai

coderabbitai Bot commented Oct 27, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Modified src/runtime.zig to increment the JoinHandle awaitable task ref-count before scheduling (rather than after) in both Executor.spawn and Runtime.spawnBlocking, with an errdefer for cleanup. This prevents a race where tasks complete before the handle is created, keeping the awaitable alive until returned.

Changes

Cohort / File(s) Summary
JoinHandle ref-count timing fix
src/runtime.zig
Moved awaitable ref-count increment to precede task scheduling in Executor.spawn and Runtime.spawnBlocking; added errdefer to decrement on error paths to fix race condition where task completes before JoinHandle creation.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • The fix touches concurrent task lifecycle and memory safety—timing of ref-count changes relative to scheduling is critical and easy to get wrong.
  • Both Executor.spawn and Runtime.spawnBlocking paths need careful verification that error paths decrement correctly.
  • Race condition fixes require reasoning about concurrent execution ordering, not just code structure.

Possibly related PRs

Poem

⏳ A task raced ahead of its handle so bright,
But now we increment—before—set things right.
With errdefer standing guard at the door,
The awaitable lives, forevermore. 🛡️

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Fix ref count race in spawn() and spawnBlocking()" directly maps to the core change in this PR—moving the JoinHandle reference count increment to occur before scheduling the task rather than after. It's specific enough that someone reviewing commit history would immediately understand this addresses a concurrency bug in task spawning, and it avoids vague language. The title captures the main intent without unnecessary noise.
Description Check ✅ Passed The description is well-targeted and directly related to the changeset. It explains the actual race condition with a concrete scenario, shows the problem with a timeline diagram, and then describes the fix (ref count increment before scheduling plus errdefer cleanup). This level of detail—explaining the "why" alongside the "what"—is helpful context even if a developer could figure out the intent from the code alone.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-spawn-ref-count-race

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9e2153e and 30e4562.

📒 Files selected for processing (1)
  • src/runtime.zig (2 hunks)
🔇 Additional comments (2)
src/runtime.zig (2)

470-474: Code changes verify—retain-before-schedule pattern is correct and complete.

The fix properly closes the UAF race by incrementing ref_count before any scheduling operation. Both Executor.spawn (line 472→476) and Runtime.spawnBlocking (line 1229→1233) follow the same pattern: incr, errdefer decr, then schedule. Runtime.spawn delegates to Executor.spawn, so it inherits the fix. No other spawn-like functions bypass this path.

The errdefer ordering is sound: if anything fails after incr, the decrement fires to clean up the ref we just added.


1227-1231: Verification complete: ThreadPool.schedule is infallible.

The signature is pub fn schedule(self: *ThreadPool, batch: Batch) void — no error set, no try/catch, returns void. The ref count retain at line 1229 happens before calling schedule at line 1233, and the errdefer at line 1230 is correctly positioned to clean up if anything goes wrong earlier in the flow (task creation or registry add). Since schedule cannot fail, there's no hidden error path after the retain that could bypass the errdefer.


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 and usage tips.

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.

1 participant