Skip to content

Fix task migration race in yield path - #304

Merged
lalinsky merged 4 commits into
mainfrom
fix/task-migration-race
Feb 8, 2026
Merged

lalinsky merged 4 commits into
mainfrom
fix/task-migration-race

Conversation

@lalinsky

@lalinsky lalinsky commented Feb 8, 2026

Copy link
Copy Markdown
Owner

Summary

  • Fix a race condition where a task's coroutine context could be resumed before it was saved, caused by the state transition to .waiting happening before the actual context switch
  • Introduce a deferred cleanup mechanism (TaskCleanup) where state transitions happen after the context is saved, processed by the next coroutine to run
  • Move yield from Executor to AnyTask with a simpler YieldMode enum (.park / .reschedule)
  • Restructure startFn to handle its own lifecycle: cleanup → run → set finish cleanup → switch out
  • Remove Executor.current_task and Executor.current threadlocal, deriving current task/executor from the coroutine layer's current_context instead

Test plan

  • All 352 unit tests pass
  • Full build (examples + benchmarks) succeeds
  • Run multi-executor stress tests to exercise the migration path

…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)
@coderabbitai

coderabbitai Bot commented Feb 8, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@lalinsky has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 9 minutes and 16 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📝 Walkthrough

Walkthrough

This 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

Cohort / File(s) Summary
Coroutine context methods
src/coro/coroutines.zig
Adds pub fn getCurrent() ?*Coroutine, pub fn setCurrent(self: *Coroutine) void, and pub fn clearCurrent() void to manage thread-local coroutine context on Coroutine.
Root coroutine API
src/coro/root.zig
Removes the former pub fn getCurrent() ?*Context from the root module; context access is migrated to Coroutine methods.
Runtime core & accessors
src/runtime.zig
Removes Executor.current_task and threadlocal current executor; adds pending_cleanup: TaskCleanup union, processCleanup(), switchOut(), and public accessors getCurrentTask()/getCurrentTaskOrNull()/getCurrentExecutor()/getCurrentExecutorOrNull(). Refactors yield/now signatures and run loop landing-site cleanup handling.
Task yield / lifecycle
src/runtime/task.zig
Adds YieldMode (park, reschedule) and AnyTask.yield(mode, cancel_mode), updates start/yield paths for deferred cleanup, executor migration, and registerTask behavior to consult current executor.
Wait path change
src/common.zig
Replaces executor yield state sequence in Waiter.waitTask with direct task-level yields: task.yield(.park, .allow_cancel) or task.yield(.park, .no_cancel), simplifying wait wake/schedule signaling.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🪄 Park the task, let contexts wake,
Coroutine setCurrent for clarity's sake.
Cleanup waits until the landing's due,
Park or reschedule — the scheduler's cue.
Small changes, big choreography.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly addresses the main change: fixing a task migration race in the yield path, which is the core issue resolved by introducing the deferred cleanup mechanism and restructuring the yield flow.
Description check ✅ Passed The description clearly explains the race condition being fixed, the deferred cleanup solution, and key architectural changes across multiple files that all relate directly to the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/task-migration-race

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.

@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

🤖 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.

getCurrent relies on current_context always pointing to a Context embedded in a Coroutine (never a standalone Context). That invariant holds because only setCurrent writes the threadlocal and it's only called on main_task.coro (in Executor.init) and implicitly via switchContext (which sets current_context = new_context at line 123, always targeting a Coroutine.context).

One thing worth noting: the downstream chain getCurrentTaskOrNull → getCurrent → fromCoroutine further assumes the Coroutine lives inside an AnyTask. That's true for main_task and spawned tasks, but a stray setCurrent on a test-only Coroutine (like in the tests below at lines 947-1181) would silently cause UB via @fieldParentPtr. Might be worth a debug assert in getCurrent or a doc comment making this contract explicit.

Comment thread src/runtime.zig Resolved

@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

🤖 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.

Comment thread src/runtime.zig
Comment on lines +937 to 951
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();
}

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.

⚠️ Potential issue | 🟡 Minor

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.

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