Repository navigation
Fix ref count race in spawn() and spawnBlocking() - #90
Conversation
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.
WalkthroughModified Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🔇 Additional comments (2)
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. Comment |
Summary
Fixes a use-after-free race condition in
spawn()andspawnBlocking()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:
spawn()schedules task to remote executor/thread poolspawn()tries to increment the freed ref count → assertion failure inRefCounter.incr()This was most visible in multi-executor tests where trivial tasks could complete extremely quickly on parallel threads.
The Fix
Both
Executor.spawn()andRuntime.spawnBlocking()now:errdefercleanup in case scheduling failsTest Plan