Repository navigation
Refactor current_coroutine tracking to eliminate special cases - #273
Conversation
Previously, current_coroutine was null when in the main task context, requiring special-case handling in getCurrentTask(). This refactoring ensures current_coroutine always points to the active coroutine: - Main task context: current_coroutine = &main_task.coro - Inside run() scheduler: current_coroutine = null - Running spawned task: current_coroutine = &task.coro Changes: - Executor.init(): Initialize current_coroutine to &main_task.coro - Executor.run(): Set to null on entry, restore to &main_task.coro on exit (via defer) - Task stepping: Set to null immediately after step() returns, before callbacks - Executor.yield(): Check is_main by comparing to &main_task.coro instead of null - Executor.getCurrentTask(): Simplified to always use current_coroutine (no special case) This ensures cleanup callbacks always run in scheduler context (current_coroutine = null) and eliminates the need for null-checking in getCurrentTask().
📝 WalkthroughWalkthroughExecutor's active-coroutine field was renamed and repurposed: Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 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: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/runtime.zig (1)
461-466:⚠️ Potential issue | 🟠 MajorFix getCurrentTaskOrNull contract after current_coroutine unwrap.
With current_coroutine null in scheduler context, getCurrentTaskOrNull now panics via getCurrentTask, despite its doc saying it returns null when not in task context. This is a behavior regression and will break any callback running in scheduler context that uses the *OrNull helpers.
Consider guarding current_coroutine in the *OrNull helpers (or add an Executor.getCurrentTaskOrNull). Example:
🔧 Proposed fix
pub fn getCurrentTaskOrNull() ?*AnyTask { const executor = getCurrentExecutorOrNull() orelse return null; - return executor.getCurrentTask(); + if (executor.current_coroutine) |coro| { + return AnyTask.fromCoroutine(coro); + } + return null; } pub fn getCurrentTaskOrNull(self: *Runtime) ?*AnyTask { const executor = self.getCurrentExecutorOrNull() orelse return null; - return executor.getCurrentTask(); + if (executor.current_coroutine) |coro| { + return AnyTask.fromCoroutine(coro); + } + return null; }
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/runtime.zig (2)
428-435:⚠️ Potential issue | 🔴 CriticalAvoid writing
current_coroutineon the wrong executor after migration.
defer self.current_coroutine = current_coro;will mutate the original executor even if the task resumes on a different executor, which is a cross‑thread data race and can corrupt scheduler state.🔧 Safer restoration on resume
- defer self.current_coroutine = current_coro; + defer (Executor.current orelse unreachable).current_coroutine = current_coro;
463-468:⚠️ Potential issue | 🟠 Major
getCurrentTaskOrNull()can now trap in scheduler context.
Withcurrent_coroutineset to null in the scheduler,executor.getCurrentTask()will crash even though the API says it should return null when not in task context. Add a null check.🔧 Guard against scheduler context
pub fn getCurrentTask(self: *Executor) *AnyTask { if (std.debug.runtime_safety) { std.debug.assert(current == self); } - return AnyTask.fromCoroutine(self.current_coroutine.?); + const coro = self.current_coroutine orelse `@panic`("no current coroutine"); + return AnyTask.fromCoroutine(coro); } @@ pub fn getCurrentTaskOrNull() ?*AnyTask { const executor = getCurrentExecutorOrNull() orelse return null; - return executor.getCurrentTask(); + if (executor.current_coroutine == null) return null; + return executor.getCurrentTask(); }
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/runtime.zig (1)
430-445:⚠️ Potential issue | 🟡 MinorData race when task yields and migrates to a different executor
When a spawned task suspends via
coro.yield()and migrates to a different executor, thedefer self.current_task = current_coroat line 430 writes to the original executor's current_task field from the new executor's thread—a cross-thread write to a non-atomic field.The practical impact is limited: the original executor has already set
current_task = nullafter its run loop stepped the task (line 516), so the stale write doesn't break anything. The new executor correctly sets and validates its own current_task (line 445).The fix: move the defer restoration into the
yieldTopath (line 435) where migration can't occur. Let the scheduler handle current_task when resuming tasks that went throughcoro.yield().
Refactored Executor to track current_task: ?*AnyTask instead of current_coroutine: ?*Coroutine. This eliminates repeated AnyTask.fromCoroutine() conversions and makes the code more direct. Changes: - Executor.current_task now points directly to the running task - Set current_task = null at the beginning of yield() to ensure getNextTask() is never called with current_task set (executor context) - Restore current_task appropriately before yielding/calling run() - Handle task migration after yieldTo by using resumed_executor - Fix early return when cancellation is detected before yielding by explicitly catching the error and restoring current_task
701916a to
2dd4c7d
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/runtime.zig (1)
471-475:⚠️ Potential issue | 🟠 Major
getCurrentTaskOrNull()can now panic in scheduler context.At Line 475,
getCurrentTask()now unwrapscurrent_task. In scheduler callbacks and insiderun()(wherecurrent_taskis intentionally null), any call path throughgetCurrentTaskOrNull()will now trap instead of returning null. That’s a behavior regression for “no current task” contexts.Consider adding an optional accessor on
Executorand using it in the*OrNullhelpers.🛠️ Proposed fix
pub fn getCurrentTask(self: *Executor) *AnyTask { if (std.debug.runtime_safety) { std.debug.assert(current == self); } return self.current_task.?; } + +pub fn getCurrentTaskOrNull(self: *Executor) ?*AnyTask { + if (std.debug.runtime_safety) { + std.debug.assert(current == self); + } + return self.current_task; +}pub fn getCurrentTaskOrNull() ?*AnyTask { const executor = getCurrentExecutorOrNull() orelse return null; - return executor.getCurrentTask(); + return executor.getCurrentTaskOrNull(); }pub fn getCurrentTaskOrNull(self: *Runtime) ?*AnyTask { const executor = self.getCurrentExecutorOrNull() orelse return null; - return executor.getCurrentTask(); + return executor.getCurrentTaskOrNull(); }
Summary
Refactors
current_coroutinetracking to eliminate special-case handling ingetCurrentTask().Previously,
current_coroutinewasnullwhen in the main task context, requiring a special case check. Now it always points to the active coroutine:current_coroutine = &main_task.cororun()scheduler:current_coroutine = nullcurrent_coroutine = &task.coroChanges
Executor.init(): Initializecurrent_coroutineto&main_task.coroExecutor.run(): Set tonullon entry, restore to&main_task.coroon exit (viadefer)nullimmediately afterstep()returns, before callbacksExecutor.yield(): Checkis_mainby comparing to&main_task.coroinstead ofnullExecutor.getCurrentTask(): Simplified to always usecurrent_coroutine(no special case)Benefits
getCurrentTask()current_coroutine = null)Test plan
./check.sh)