Skip to content

Refactor current_coroutine tracking to eliminate special cases - #273

Merged
lalinsky merged 2 commits into
mainfrom
refactor-current-coroutine
Feb 3, 2026
Merged

lalinsky merged 2 commits into
mainfrom
refactor-current-coroutine

Conversation

@lalinsky

@lalinsky lalinsky commented Feb 3, 2026

Copy link
Copy Markdown
Owner

Summary

Refactors current_coroutine tracking to eliminate special-case handling in getCurrentTask().

Previously, current_coroutine was null when in the main task context, requiring a special case check. Now it 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)

Benefits

  1. Cleaner API: No special cases in getCurrentTask()
  2. Better semantics: Cleanup callbacks always run in scheduler context (current_coroutine = null)
  3. More explicit: The transition between task and scheduler contexts is now clearly visible

Test plan

  • All existing tests pass (./check.sh)

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().
@coderabbitai

coderabbitai Bot commented Feb 3, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Executor's active-coroutine field was renamed and repurposed: current_coroutine → current_task. Initialization, yield/resume, run loop, task completion and getCurrentTask now use current_task as the single source of truth; public APIs are unchanged.

Changes

Cohort / File(s) Summary
Runtime — executor/task scheduling
src/runtime.zig
Renamed Executor.current_coroutine → Executor.current_task; set self.current_task = &self.main_task in Executor.init; updated yield, yield-to, resume, run loop, getCurrentTask, finished-task detection, stack release, and related assertions to use current_task consistently. No public signatures changed.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

The task pointer steadies the wheel, no stray,
Main waits ready while runners play.
Yield, resume, stacks freed with care,
One field watches all — runtime aware.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main change: refactoring current_coroutine tracking to eliminate special cases, which aligns with the core objective of the PR.
Description check ✅ Passed The description is well-related to the changeset, explaining the rationale behind tracking changes, benefits, and test coverage.
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 refactor-current-coroutine

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: 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 | 🟠 Major

Fix 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;
}

@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: 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 | 🔴 Critical

Avoid writing current_coroutine on 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.
With current_coroutine set 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();
 }

@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: 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 | 🟡 Minor

Data race when task yields and migrates to a different executor

When a spawned task suspends via coro.yield() and migrates to a different executor, the defer self.current_task = current_coro at 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 = null after 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 yieldTo path (line 435) where migration can't occur. Let the scheduler handle current_task when resuming tasks that went through coro.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
@lalinsky
lalinsky force-pushed the refactor-current-coroutine branch from 701916a to 2dd4c7d Compare February 3, 2026 13:24
Repository owner deleted a comment from claude Bot Feb 3, 2026
Repository owner deleted a comment from claude Bot Feb 3, 2026

@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: 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 unwraps current_task. In scheduler callbacks and inside run() (where current_task is intentionally null), any call path through getCurrentTaskOrNull() will now trap instead of returning null. That’s a behavior regression for “no current task” contexts.

Consider adding an optional accessor on Executor and using it in the *OrNull helpers.

🛠️ 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();
 }

@lalinsky
lalinsky merged commit 7d6bc09 into main Feb 3, 2026
4 checks passed
@lalinsky
lalinsky deleted the refactor-current-coroutine branch February 3, 2026 13:47
@coderabbitai coderabbitai Bot mentioned this pull request Feb 8, 2026
2 of 3 tasks
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