Repository navigation
Fix task migration race in yield path - #304
Conversation
…ntext save The yield path had a race between the CAS that transitions task state to .waiting and the actual coroutine context save. Another executor could wake and resume a task before its context was saved. Fix by introducing a deferred cleanup mechanism: the yielding task records what needs to happen (park/reschedule/finish) on the executor, then context switches. The next coroutine to run processes the cleanup after the context is safely saved. - Add TaskCleanup union and processCleanup/switchOut to Executor - Move yield from Executor to AnyTask with YieldMode enum (park/reschedule) - Restructure startFn to processCleanup → run → set finish cleanup → switchOut - All three landing sites (startFn, yield resume, run loop) call processCleanup
Derive the current task and executor from the coroutine layer's current_context threadlocal, which switchContext already maintains on every context switch. - Add Coroutine.getCurrent/setCurrent/clearCurrent helpers - getCurrentTaskOrNull uses Coroutine.getCurrent -> AnyTask.fromCoroutine - getCurrentExecutorOrNull derives from current task - Zero-initialize main_task.coro.context (not a real coroutine)
|
Warning Rate limit exceeded
⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📝 WalkthroughWalkthroughThis PR moves coroutine/context tracking onto per-task contexts, replaces executor-level yield/state transitions with a task-level yield API (park/reschedule), adds deferred cleanup handling on Executor, and introduces Coroutine.getCurrent/setCurrent/clearCurrent APIs. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
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 |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@src/runtime.zig`:
- Around line 955-957: The now() function currently ignores its Runtime pointer
and calls getCurrentExecutor().loop.now(), which panics when there is no current
executor (e.g., blocking thread-pool tasks); fix by using the Runtime instance
instead of the global executor and by matching the safe behavior of
Runtime.sleep(): read the Timestamp from the runtime's loop or clock via the
Runtime pointer (e.g., use self.loop.now() or an equivalent field/function on
Runtime) and if the runtime has no associated executor/loop, fall back to a
non-panicking system-clock timestamp or an explicit safe default; also apply the
same defensive pattern used in Runtime.sleep() to the free sleep() helper to
avoid panics when no executor exists.
🧹 Nitpick comments (1)
src/coro/coroutines.zig (1)
835-851: New coroutine context accessors look correct for the intended usage.
getCurrentrelies oncurrent_contextalways pointing to aContextembedded in aCoroutine(never a standaloneContext). That invariant holds because onlysetCurrentwrites the threadlocal and it's only called onmain_task.coro(inExecutor.init) and implicitly viaswitchContext(which setscurrent_context = new_contextat line 123, always targeting aCoroutine.context).One thing worth noting: the downstream chain
getCurrentTaskOrNull→getCurrent→fromCoroutinefurther assumes theCoroutinelives inside anAnyTask. That's true formain_taskand spawned tasks, but a straysetCurrenton a test-onlyCoroutine(like in the tests below at lines 947-1181) would silently cause UB via@fieldParentPtr. Might be worth a debug assert ingetCurrentor a doc comment making this contract explicit.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@src/runtime.zig`:
- Around line 937-951: The Runtime methods beginShield, endShield, and
checkCancel currently call getCurrentTask() and will panic outside a task;
change them to mirror the free-function behavior by calling
getCurrentTaskOrNull() and performing a no-op fallback when null (for
beginShield/endShield) and returning Cancelable.ok(void) or equivalent when
checkCancel has no task context; update the implementations of pub fn
beginShield(_: *Runtime), pub fn endShield(_: *Runtime), and pub fn
checkCancel(_: *Runtime) to use getCurrentTaskOrNull(), call
beginShield()/endShield()/checkCancel() on the task when non-null, and otherwise
do the safe no-op/neutral return so these Runtime methods no longer panic in
non-task contexts.
| pub fn beginShield(_: *Runtime) void { | ||
| getCurrentTask().beginShield(); | ||
| } | ||
|
|
||
| /// End a cancellation shield. | ||
| pub fn endShield(self: *Runtime) void { | ||
| self.getCurrentTask().endShield(); | ||
| pub fn endShield(_: *Runtime) void { | ||
| getCurrentTask().endShield(); | ||
| } | ||
|
|
||
| /// Check if cancellation has been requested and return error.Canceled if so. | ||
| /// This consumes the cancellation flag. | ||
| /// Use this after endShield() to detect cancellation that occurred during the shielded section. | ||
| pub fn checkCancel(self: *Runtime) Cancelable!void { | ||
| return self.getCurrentTask().checkCancel(); | ||
| } | ||
|
|
||
| /// Get the currently executing task. | ||
| /// Panics if called from a thread without an active executor context. | ||
| pub fn getCurrentTask(self: *Runtime) *AnyTask { | ||
| return self.getCurrentExecutor().getCurrentTask(); | ||
| } | ||
|
|
||
| /// Get the currently executing task, or null if not in task context. | ||
| pub fn getCurrentTaskOrNull(self: *Runtime) ?*AnyTask { | ||
| const executor = self.getCurrentExecutorOrNull() orelse return null; | ||
| return executor.getCurrentTask(); | ||
| } | ||
|
|
||
| /// Get the current thread's executor. | ||
| /// Panics if called from a thread without an active executor context. | ||
| pub fn getCurrentExecutor(self: *Runtime) *Executor { | ||
| const executor = Executor.current orelse @panic("no current executor"); | ||
| if (std.debug.runtime_safety) { | ||
| std.debug.assert(executor.runtime == self); | ||
| } | ||
| return executor; | ||
| } | ||
|
|
||
| /// Get the current thread's executor, or null if not in executor context. | ||
| pub fn getCurrentExecutorOrNull(self: *Runtime) ?*Executor { | ||
| const executor = Executor.current orelse return null; | ||
| if (std.debug.runtime_safety) { | ||
| std.debug.assert(executor.runtime == self); | ||
| } | ||
| return executor; | ||
| pub fn checkCancel(_: *Runtime) Cancelable!void { | ||
| return getCurrentTask().checkCancel(); | ||
| } |
There was a problem hiding this comment.
beginShield, endShield, checkCancel will panic if called from a non-task context.
These newly changed signatures discard self: *Runtime and call getCurrentTask() (not the OrNull variant). If someone holds a *Runtime reference in a blocking task or a plain thread and calls rt.beginShield(), it panics. The free-function versions (beginShield/endShield at lines 678-690) gracefully handle the null case. The Runtime methods don't.
This is the same class of issue as now() (flagged previously) but applies to three more methods. Consider either using getCurrentTaskOrNull with a no-op fallback (like the free functions do), or documenting that these methods require task context.
Proposed fix — match the free-function behavior
pub fn beginShield(_: *Runtime) void {
- getCurrentTask().beginShield();
+ if (getCurrentTaskOrNull()) |task| {
+ task.beginShield();
+ }
}
pub fn endShield(_: *Runtime) void {
- getCurrentTask().endShield();
+ if (getCurrentTaskOrNull()) |task| {
+ task.endShield();
+ }
}
pub fn checkCancel(_: *Runtime) Cancelable!void {
- return getCurrentTask().checkCancel();
+ if (getCurrentTaskOrNull()) |task| {
+ try task.checkCancel();
+ }
}🤖 Prompt for AI Agents
In `@src/runtime.zig` around lines 937 - 951, The Runtime methods beginShield,
endShield, and checkCancel currently call getCurrentTask() and will panic
outside a task; change them to mirror the free-function behavior by calling
getCurrentTaskOrNull() and performing a no-op fallback when null (for
beginShield/endShield) and returning Cancelable.ok(void) or equivalent when
checkCancel has no task context; update the implementations of pub fn
beginShield(_: *Runtime), pub fn endShield(_: *Runtime), and pub fn
checkCancel(_: *Runtime) to use getCurrentTaskOrNull(), call
beginShield()/endShield()/checkCancel() on the task when non-null, and otherwise
do the safe no-op/neutral return so these Runtime methods no longer panic in
non-task contexts.
Summary
.waitinghappening before the actual context switchTaskCleanup) where state transitions happen after the context is saved, processed by the next coroutine to runyieldfromExecutortoAnyTaskwith a simplerYieldModeenum (.park/.reschedule)startFnto handle its own lifecycle: cleanup → run → set finish cleanup → switch outExecutor.current_taskandExecutor.currentthreadlocal, deriving current task/executor from the coroutine layer'scurrent_contextinsteadTest plan