Skip to content

Implement direct context switching between coroutines - #39

Merged
lalinsky merged 2 commits into
mainfrom
direct-switch-context
Oct 9, 2025
Merged

lalinsky merged 2 commits into
mainfrom
direct-switch-context

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 9, 2025 •

Copy link
Copy Markdown
Owner

Summary

This PR optimizes the coroutine scheduler by implementing direct context switching between tasks, reducing scheduler overhead and improving runtime performance.

  • Simplified state machine: Removed running state from coroutines, now only ready, waiting, and dead
  • Direct switching in yield(): Tasks can now directly switch to the next ready coroutine instead of always returning to the scheduler
  • New next_ready_queue: Tracks tasks that yield as ready for the next scheduling cycle
  • API cleanup: Removed deprecated waitForReady() methods across the codebase
  • Consistent naming: Changed AwaitableList.append() to push()
  • Updated all callsites: All I/O operations, synchronization primitives, and tests updated to use new yield() API

Implementation Details

The key optimization is in Runtime.yield() which now:

  1. Sets the coroutine to the desired state (ready, waiting, or dead)
  2. If yielding as ready, adds to next_ready_queue for next cycle
  3. Attempts to directly switch to the next ready task if available
  4. Only returns to scheduler if no ready tasks exist

This reduces the number of context switches through the scheduler's main context, improving performance for workloads with many cooperative yields.

Test plan

  • All existing unit tests pass
  • Mutex and synchronization tests verify correct waiting behavior
  • Future and task tests verify direct switching works correctly
  • I/O operations (file, TCP, UDP) tested with new yield API

Summary by CodeRabbit

  • New Features

    • More precise coroutine control with explicit yield states, improving responsiveness and predictability.
  • Refactor

    • Unified waiting across I/O, networking, and synchronization primitives to use cooperative yielding instead of blocking waits.
    • Streamlined scheduler queues for staging and resuming ready tasks, enhancing fairness under load.
    • Simplified coroutine state model and lifecycle handling.
  • Tests

    • Updated demos and test scenarios to align with the new yielding semantics.
  • Chores

    • Minor consistency updates across components to adopt the new scheduling and waiting approach.

This change optimizes coroutine scheduling by allowing tasks to directly
switch to the next ready task instead of always returning to the scheduler.

Key changes:
- Simplified coroutine states (removed "running", kept ready/waiting/dead)
- Enhanced yield() to take desired state and perform direct switching
- Added next_ready_queue to track tasks yielding as ready
- Removed deprecated waitForReady() methods across the codebase
- Updated all I/O and synchronization operations to use new yield() API
- Changed AwaitableList.append() to push() for consistency

This reduces context switch overhead and improves runtime performance.
@coderabbitai

coderabbitai Bot commented Oct 9, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors coroutine scheduling: removes waitForReady, introduces Runtime.yield(desired_state), adds next_ready_queue, and switches list enqueues from append to push. Updates coroutines, sync primitives, and I/O (file/tcp/udp) to yield .waiting and tests/examples to yield .ready. Removes CoroutineState.running and adds current coroutine helpers.

Changes

Cohort / File(s) Summary
Runtime scheduling core
src/runtime.zig
Removed Waiter.waitForReady; expanded Runtime.yield to yield(desired_state); added next_ready_queue; migrated list ops append→push; updated wait/wake paths to suspend via runtime.yield(.waiting); adjusted run loop to stage/move ready tasks.
Coroutine state/API
src/coroutines.zig
Added setCurrent and clearCurrent; removed .running state and reindexed CoroutineState; deleted waitForReady; removed setting state to running in wrapper.
Sync primitives
src/sync.zig
Switched queue insertions append→push; replaced current.waitForReady with runtime.yield(.waiting); updated test harness/task coordination yields to rt.yield(.ready); aligned timed waits/signals.
I/O: files
src/file.zig
Replaced waiter.waitForReady with waiter.runtime.yield(.waiting) in read/write and variants; preserved result/err flows.
I/O: TCP
src/tcp.zig
Replaced waiter.waitForReady with waiter.runtime.yield(.waiting) across accept/connect/read/write/flush/close paths; no change to error propagation.
I/O: UDP
src/udp.zig
Replaced waiter.waitForReady with waiter.runtime.yield(.waiting) in read/write/close paths; maintained result handling.
Example
examples/mutex_demo.zig
Changed rt.yield() to rt.yield(.ready) in incrementTask.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Coroutine
  participant R as Runtime
  participant A as Awaitable (e.g., I/O or Mutex)

  Note over C,R: Waiting flow (new)
  C->>A: enqueue waiter (A.waiting_list.push)
  C->>R: yield(.waiting)
  activate R
  R->>R: stage C in next_ready_queue (when woken)
  deactivate R
  A-->>R: markReady(C)

  Note over R: Scheduling loop
  R->>R: move next_ready_queue -> ready_queue
  R->>C: run next ready coroutine

  Note over C,R: Ready yield (cooperative)
  C->>R: yield(.ready)
  R->>R: push C to next_ready_queue
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

A hop, a pause, I yield to time,
From waiting burrow to ready climb.
Queues now push, not append—how neat!
Coroutines tap a softer beat.
With twitches, ticks, and tidy tread,
I bound from waiting into ready thread. 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly captures the primary enhancement of this PR, namely enabling direct context switching between coroutines, and aligns with the described changes to the scheduler, yield() API, and coroutine state machine without adding extraneous detail.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch direct-switch-context

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0c5465d and efd76f2.

📒 Files selected for processing (7)
  • examples/mutex_demo.zig (1 hunks)
  • src/coroutines.zig (2 hunks)
  • src/file.zig (7 hunks)
  • src/runtime.zig (12 hunks)
  • src/sync.zig (14 hunks)
  • src/tcp.zig (7 hunks)
  • src/udp.zig (3 hunks)
🔇 Additional comments (13)
src/coroutines.zig (2)

14-20: LGTM! Public helpers for managing current coroutine.

These inline helpers provide clean abstractions for setting and clearing the current coroutine. They integrate well with the runtime's direct context switching optimization by giving explicit control over the threadlocal current_coroutine variable.


29-33: LGTM! Simplified coroutine state machine.

Removing the running state simplifies the state machine to three states: ready, waiting, and dead. This aligns with the PR's goal of reducing scheduler overhead, as tasks no longer need to transition through a running state when active.

src/runtime.zig (4)

614-614: LGTM! New queue for staging ready coroutines.

The next_ready_queue field supports the direct switching optimization by staging coroutines that become ready during the current scheduling cycle. This prevents interference with the active ready_queue being processed.


754-779: LGTM! Direct context switching optimization implemented correctly.

The new yield() implementation with desired_state parameter enables efficient direct task-to-task switching:

  1. Sets coroutine state (line 758)
  2. Enqueues ready tasks to next_ready_queue for next cycle (lines 759-761)
  3. Dead tasks always return to scheduler for cleanup (lines 764-767)
  4. Attempts direct switch to next ready task from ready_queue (lines 769-773)
  5. Falls back to scheduler if no ready tasks available (lines 774-776)
  6. Asserts correct coroutine tracking upon return (line 778)

The logic correctly manages the current_coroutine threadlocal: whoever switches to a task (either via direct switch at line 772 or scheduler at line 880) must call setCurrent() first, ensuring the assert at line 778 always passes when the task resumes.


880-900: LGTM! Enhanced dead coroutine detection.

The added check at lines 885-900 correctly handles coroutines that die after being reached via a direct switch. Previously, dead coroutines were only detected when explicitly returning to the scheduler. Now, by checking getCurrent() after any switch (line 885), the scheduler can immediately detect and clean up dead coroutines regardless of how they were scheduled. This prevents delayed cleanup and ensures stacks are released promptly.


905-906: LGTM! Staging queue merged into ready queue.

Moving next_ready_queue to ready_queue after each scheduling cycle correctly implements the two-phase queuing strategy: tasks that become ready during the current cycle are staged in next_ready_queue, then promoted to ready_queue for the next cycle. This prevents tasks from being scheduled multiple times in a single cycle.

examples/mutex_demo.zig (1)

15-15: LGTM! Updated to use new yield API.

The change from rt.yield() to rt.yield(.ready) correctly simulates preemption while holding the mutex lock. The explicit .ready state makes the intent clear: the task voluntarily yields but remains ready to execute.

src/udp.zig (1)

76-76: LGTM! Updated I/O suspension to use new yield API.

Replacing waiter.waitForReady() with waiter.runtime.yield(.waiting) correctly updates the UDP socket operations (read, write, close) to use the new cooperative scheduling mechanism. The .waiting state appropriately indicates that the task is blocked on I/O and should only be resumed when the operation completes (via markReady() callback).

Also applies to: 130-130, 172-172

src/file.zig (1)

72-72: LGTM! Updated file I/O suspension to use new yield API.

Replacing waiter.waitForReady() with waiter.runtime.yield(.waiting) across all file operations (read, write, pread, pwrite, readBuf, writeBuf, close) correctly adopts the new cooperative scheduling mechanism. This change is consistent with the I/O suspension pattern used in other modules (e.g., udp.zig, tcp.zig).

Also applies to: 121-121, 193-193, 239-239, 286-286, 332-332, 376-376

src/tcp.zig (1)

96-96: LGTM! Consistent migration to new yield API.

All callsites correctly replaced waiter.waitForReady() with waiter.runtime.yield(.waiting). Using .waiting state for blocking I/O operations is semantically correct—the coroutine suspends until the I/O completion callback invokes waiter.markReady().

Also applies to: 142-142, 201-201, 307-307, 346-346, 391-391, 440-440

src/sync.zig (3)

30-30: LGTM! Queue method renamed per PR objectives.

All callsites correctly updated from wait_queue.append() to wait_queue.push(), aligning with the renamed API mentioned in the PR objectives.

Also applies to: 68-68, 82-82, 191-191, 221-221


33-33: LGTM! Correct state transition for blocking operations.

Synchronization primitives (Mutex, Condition, ResetEvent) now use runtime.yield(.waiting) instead of the removed waitForReady(). Using .waiting state correctly indicates that the coroutine is blocked until woken by markReady().

Also applies to: 72-72, 194-194


324-324: LGTM! Test coordination pattern using explicit ready state.

Tests now explicitly use rt.yield(.ready) to voluntarily yield control while remaining schedulable. This is the correct pattern for test synchronization—allowing other coroutines to run (e.g., waiters to block) before proceeding with the test actions (e.g., signaling).

Also applies to: 397-399, 464-464, 523-525, 821-821, 855-856, 929-929, 967-967, 1175-1175


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.

Integrated the new Awaitable abstraction from main that supports both
coroutine and thread waiting. Updated the direct switching implementation
to work correctly with the new waitForComplete() and markComplete() APIs.

Key changes:
- Updated Awaitable.waitForComplete() to use runtime.yield(.waiting) instead of removed waitForReady()
- Changed all append() calls to push() for consistency
- Fixed dead coroutine handling to use correct awaitable reference
- All tests passing

@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

🧹 Nitpick comments (3)
src/tcp.zig (1)

96-96: Yield switchovers look correct; consider a fast-path for immediate completions.

The replacements to waiter.runtime.yield(.waiting) align with the new scheduler model and look good. If any xev ops can complete synchronously (invoke the callback before we reach yield), we’ll still yield once unnecessarily. Optional: add a “completed” flag in Result and skip yielding if already done.

Example (apply similarly to accept/close/connect/write/read/shutdown):

-        const Result = struct {
+        const Result = struct {
             waiter: Waiter,
             result: xev.ConnectError!void = undefined,
+            completed: bool = false,
             pub fn callback(
                 result_data_ptr: ?*@This(),
                 loop: *xev.Loop,
                 completion_inner: *xev.Completion,
                 socket: xev.TCP,
                 result: xev.ConnectError!void,
             ) xev.CallbackAction {
                 _ = loop;
                 _ = completion_inner;
                 _ = socket;
                 const result_data = result_data_ptr.?;
                 result_data.result = result;
+                result_data.completed = true;
                 result_data.waiter.markReady();
                 return .disarm;
             }
         };
@@
-        waiter.runtime.yield(.waiting);
+        if (!result_data.completed) {
+            waiter.runtime.yield(.waiting);
+        }

Please confirm whether xev ever calls these TCP callbacks synchronously. If it does, the fast-path avoids an extra yield; if not, current code is fine.

Also applies to: 142-142, 201-201, 307-307, 346-346, 391-391, 440-440

src/sync.zig (2)

191-199: ResetEvent.wait: OK; clarify thread-affinity vs. “thread-safe” claim.

The atomic state + queue push + yield is fine for a single-runtime-thread model. However, the doc says “ResetEvent is a thread-safe bool… Concurrent calls to set(), isSet(), reset() are allowed.” set() iterates wait_queue w/o external locking; if set() can be called from other OS threads, that would race with wait_queue.push/remove. Please clarify invariants (e.g., all methods must be invoked on the runtime thread) or add a runtime-thread assertion in set().


325-325: Tests: repeated rt.yield(.ready) are fine; consider compacting.

The explicit yields help sequencing with the new scheduler. Optional: replace repeated lines with a tiny loop or helper to reduce noise.

Also applies to: 397-400, 465-465, 523-526, 821-821, 855-856, 930-930, 967-967, 1175-1175

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0c5465d and b0d5081.

📒 Files selected for processing (7)
  • examples/mutex_demo.zig (1 hunks)
  • src/coroutines.zig (2 hunks)
  • src/file.zig (7 hunks)
  • src/runtime.zig (11 hunks)
  • src/sync.zig (14 hunks)
  • src/tcp.zig (7 hunks)
  • src/udp.zig (3 hunks)
🔇 Additional comments (4)
src/sync.zig (4)

30-37: Mutex slow path: looks correct; confirm push preserves FIFO fairness.

Replacing append with push and yielding .waiting is consistent. Please confirm AwaitableList.push preserves the previous FIFO behavior (append to tail) so lock handoff remains fair when paired with pop().


68-76: Condition.wait ordering: cooperative-safe; confirm no lost-wakeup edge.

Enqueue (push) → unlock → runtime.yield(.waiting) matches the new model and should avoid lost wake-ups under cooperative scheduling (no other task runs until we yield). Please confirm Runtime.yield(.waiting) cannot race against a prior markReady on the same coroutine in a way that leaves it stuck waiting.


82-83: Condition.timedWait push: OK.

Using push before timedWaitForReadyWithCallback is consistent with the non-timed path and the removal-on-timeout callback. LGTM.


221-244: ResetEvent.timedWait push: OK.

Push then timedWaitForReadyWithCallback with remove on timeout is correct and mirrors the Condition path. LGTM.

@lalinsky
lalinsky merged commit 277032f into main Oct 9, 2025
@lalinsky
lalinsky deleted the direct-switch-context branch October 9, 2025 10:37
lalinsky added a commit that referenced this pull request Jan 6, 2026
Replace manual UTF-8 to UTF-16 conversion with std.os.windows.sliceToPrefixedFileW
for better path handling on Windows. This change:

- Eliminates heap allocations for path conversion
- Adds proper directory handle support for relative path operations
- Enables automatic long path support via \\?\ prefix
- Improves path normalization and edge case handling

Modified functions in src/os/fs.zig:
- openat(): Now properly handles directory-relative file opening
- createat(): Now properly handles directory-relative file creation
- renameat(): Now properly handles directory handles for both paths
- unlinkat(): Now properly handles directory-relative file deletion

All tests pass on Linux and Windows (via Wine).
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