Repository navigation
Task migration and scheduling optimizations - #61
Conversation
Implement a LIFO slot optimization inspired by Tokio's scheduler to improve cache locality when tasks wake other tasks. When a task wakes another task, the woken task is placed in a LIFO slot for immediate execution on the same thread, maximizing the chance that data is still in the CPU cache. Key changes: - Add lifo_slot field to Executor for immediate task execution - Change ready_queue and next_ready_queue from LIFO stack to FIFO queue - Add getNextTask() helper that checks LIFO slot before ready_queue - Add scheduleLocal() helper for local task scheduling with LIFO logic - Implement starvation prevention (MAX_LIFO_POLLS_PER_TICK = 3) - Fix event loop blocking to check both ready_queue and lifo_slot - Refactor spin loop to track count across iterations The LIFO slot is enabled by default as it provides both better cache locality and maintains backward-compatible timing (woken tasks run immediately). Displaced LIFO tasks and yields go to the FIFO ready_queue for fairness.
Tasks waiting on synchronization primitives now migrate between executors when woken from a different thread, avoiding expensive remote wakeup notifications. When task A on executor 1 wakes task B (originally on executor 0): - If B is in waiting_sync state: B migrates to executor 1 by updating parent_context_ptr - If B is in waiting_io state: B stays on executor 0 (I/O callbacks are executor-bound) This eliminates the need for cross-thread notification (remote queue + async wakeup) when tasks wake each other, significantly reducing wakeup latency. Implementation: - scheduleTask() now handles state swap and migration logic - Sync tasks (.waiting_sync) migrate by updating coro.parent_context_ptr - I/O tasks (.waiting_io) are pinned to home executor - yield() re-derives executor after resuming to handle migration - Added scheduleTaskLocal() and scheduleTaskRemote() helpers
WalkthroughAdds task pinning and a LIFO wakeup slot, converts ready queues to FIFO, introduces local/remote scheduling primitives and getNextTask, updates resume/yield flow to use new scheduling, and exposes pin/lifo state via Runtime/Executor public APIs. (≤50 words) Changes
Sequence Diagram(s)sequenceDiagram
participant Runtime
participant Executor
participant LIFO as LIFO_Slot
participant ReadyQ as Ready_Queue
participant Remote as Remote_Queue
participant Task
rect rgb(247,249,255)
Task->>Executor: scheduleTask(mode)
alt local && lifo_enabled
Executor->>LIFO: try_place(task)
else remote_or_lifo_unavailable
Executor->>Remote: scheduleTaskRemote -> enqueue(remote)
end
end
rect rgb(255,250,245)
Executor->>Executor: drain_remote_into_ready()
Executor->>LIFO: poll_lifo()
alt lifo_returns && not_starving
LIFO-->>Executor: task
else
ReadyQ-->>Executor: dequeue()
end
Executor->>Task: resume/execute
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ 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
🧹 Nitpick comments (7)
src/runtime.zig (7)
55-61: LIFO toggle looks good; consider exposing the starvation cap as an option.Default‑on LIFO makes sense and matches the documented timing. Recommend adding a RuntimeOptions knob for MAX_LIFO_POLLS_PER_TICK (currently hardcoded to 3) to ease tuning across workloads.
845-861: Queue swap to FIFO + LIFO slot fields—LGTM; add an invariant/assert for thread‑affinity.ready_queue/next_ready_queue moving to SimpleQueue improves fairness; LIFO fields are clear. Since scheduleTaskLocal must run on the owning executor thread, add a debug assert to catch accidental cross‑thread use.
Apply this diff near the start of scheduleTaskLocal:
fn scheduleTaskLocal(self: *Executor, task: *AnyTask, is_yield: bool) void { + if (builtin.mode == .Debug or builtin.mode == .ReleaseSafe) { + std.debug.assert(Runtime.current_executor == self); + }Also applies to: 907-907
1068-1072: Yield fairness and direct handoff look right; gate the TLS assert to debug builds.
- Yields bypass the LIFO slot—good for fairness.
- Directly switching to getNextTask() preserves locality.
- The TLS re‑derive/assert is great for safety but can be debug‑only.
Apply this diff:
- const resumed_executor = Runtime.current_executor orelse unreachable; - std.debug.assert(resumed_executor.current_coroutine == current_coro); + if (builtin.mode == .Debug or builtin.mode == .ReleaseSafe) { + const resumed_executor = Runtime.current_executor orelse unreachable; + std.debug.assert(resumed_executor.current_coroutine == current_coro); + }Also applies to: 1080-1090, 1091-1095
1197-1197: Event loop spin budget: good latency hedge; make the threshold configurable and add a backoff cap.
- Atomic drain of remote ready to local ready_queue is correct.
- Single‑tick processing then moving next_ready_queue → ready_queue preserves fairness.
- Spin with .no_wait for up to 16 iterations reduces cross‑thread wake latency. Suggest:
- Expose the spin threshold (16) in RuntimeOptions for tuning.
- Optionally track a simple exponential backoff or a max busy‑time budget to avoid wasted CPU on idle systems.
Also applies to: 1210-1215, 1217-1219, 1257-1258, 1259-1273
1276-1315: LIFO starvation guard is clear; consider making MAX_LIFO_POLLS_PER_TICK configurable.The “move LIFO to FIFO when hitting the cap” logic is sound and resets on FIFO pops. Surfacing the “3” as an option alongside lifo_slot_enabled would help portability across workloads.
1343-1357: Remote notify: keep the guard; prefer std.log.warn for visibility.Guarding on remote_initialized avoids use before init. For the warning, use std.log.warn to integrate with logging.
Apply this diff:
- self.remote_wakeup.notify() catch |err| { - std.debug.print("WARNING: remote_wakeup.notify() failed for executor {}: {}\n", .{ self.id, err }); - }; + self.remote_wakeup.notify() catch |err| { + std.log.warn("remote_wakeup.notify() failed for executor {}: {}", .{ self.id, err }); + };
1359-1429: State machine in scheduleTask(): tighten unexpected‑state handling and add a safe release path.The state transitions look correct (including .preparing_to_wait short‑circuit and IO pinning). Two improvements:
- Don’t hard‑panic on unexpected states in release; log and return to avoid crashing production on rare double‑resume bugs.
- Optionally special‑case .dead to no‑op (defensive).
Apply this diff:
- if (old_state != .waiting_sync and old_state != .ready) { - std.debug.panic("scheduleTask: unexpected state {} for task {*}", .{ old_state, task }); - } + if (old_state != .waiting_sync and old_state != .ready) { + if (builtin.mode == .Debug or builtin.mode == .ReleaseSafe) { + std.debug.panic("scheduleTask: unexpected state {} for task {*}", .{ old_state, task }); + } else { + // Defensive no-op in release to avoid taking down the process. + std.log.err("scheduleTask: unexpected state {} for task {*}, ignoring", .{ old_state, task }); + return; + } + }Please run your stress/migration tests with a forced error injection (simulate a spurious resume) to confirm the no‑op path behaves safely under release builds.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime.zig(9 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: test (windows-latest)
🔇 Additional comments (2)
src/runtime.zig (2)
340-345: Centralizing wakeups via home executor is a solid simplification.Routing resumeTask() through Executor.scheduleTask() on the task’s home executor removes foot‑guns and cleanly enables migration. No issues spotted.
Also applies to: 347-349
1317-1341: Local scheduling paths and displacement policy—LGTM.
- Yields → next_ready_queue is the right fairness call.
- LIFO displacement to FIFO avoids losing locality while preventing bubbles.
No changes needed.
Adds fine-grained control over task migration with per-task pin counters. Pinned tasks always stay on their home executor, even when woken from other threads. Features: - SpawnOptions.pinned: Pin tasks at spawn time - AnyTask.pin_count: Nestable pin counter (like shield_count) - Runtime.beginPin()/endPin(): Dynamic pinning control - scheduleTask() checks pin_count before migrating Use cases: - Tasks with thread-local state or executor-specific resources - Tasks requiring specific thread affinity - Fine-grained control over migration behavior Tasks with pin_count > 0 skip migration and stay on home executor.
- Add ExecutorId.isId() helper method - Tasks spawned with .executor = .id(N) are now automatically pinned - Ensures tasks with explicit executor assignment stay on that executor - Cleaner code with executor.isId() vs manual comparisons
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/runtime.zig (1)
1226-1303: LGTM: Spin loop reduces cross-thread wakeup latency.The spin loop (up to 16 iterations) before blocking reduces latency for cross-thread wakeups. The logic correctly checks both
ready_queueandlifo_slotfor available work and properly resets/increments the spin counter.Consider making the spin count (currently hard-coded to 16) configurable via
RuntimeOptionsif fine-tuning is needed for different workloads in the future.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime.zig(14 hunks)
🔇 Additional comments (10)
src/runtime.zig (10)
44-47: LGTM: Clear documentation for pinning behavior.The
pinnedfield is well-documented and the default value offalsemaintains backward compatibility.
59-64: LGTM: LIFO slot feature is well-documented.The documentation clearly explains both the performance benefit and the backward-compatibility rationale for the default value.
342-353: LGTM: Correctly derives home executor for migration support.The change to derive
home_executorfrom the task (viaExecutor.fromCoroutine) is essential for migration, asparent_context_ptrmay have been updated when the task migrated to a different executor.
363-363: LGTM: Pin counter supports nested pinning.The
pin_countfield allows for nestedbeginPin()/endPin()calls, similar to the existingshield_countpattern.
850-865: LGTM: Queue type change and LIFO slot design are sound.The change from
SimpleStack(LIFO) toSimpleQueue(FIFO) for the regular ready queues, combined with the separate LIFO slot for recently woken tasks, provides a good balance between cache locality and fairness. The starvation prevention counter usingu8is sufficient.
1101-1104: LGTM: Correctly handles post-migration executor context.Re-deriving the executor from TLS after resuming is essential because the task may have migrated to a different executor during the yield. The comment clearly explains this critical detail.
1146-1163: LGTM: Pin methods follow established pattern.The
beginPin()/endPin()implementation mirrors the existingbeginShield()/endShield()pattern, providing a consistent API for nested resource management.
1305-1344: LGTM: Starvation prevention logic is sound.The LIFO slot starvation prevention correctly limits consecutive LIFO polls to 3 (matching Tokio's
MAX_LIFO_POLLS_PER_TICK), and when the limit is hit, moves the LIFO task to the back of the ready queue to ensure fairness.
1346-1386: LGTM: Local and remote scheduling logic is correct.
scheduleTaskLocal()correctly routes yields tonext_ready_queueto bypass the LIFO slot for fairness, while woken tasks use the LIFO slot for cache locality.scheduleTaskRemote()safely handles cross-thread scheduling with proper initialization checks.
1971-1991: LGTM: Runtime pin methods follow established delegation pattern.The
beginPin()/endPin()methods correctly delegate to the current executor and handle the case where they're called outside of a coroutine context.
When a task waits on select() with multiple branches that complete at the same time on different threads, both threads call scheduleTask() concurrently. The first thread sees old_state=.waiting_sync and schedules the task correctly. The second thread sees old_state=.ready (already changed by first thread) and would reach the default path, scheduling the task again. Fixed by: 1. Initialize spawned tasks with .waiting_sync instead of .ready 2. Add early return in default path if old_state==.ready to detect and skip tasks already transitioned by another thread This prevents tasks from being enqueued twice while preserving correct spawn and normal wake behavior.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/runtime.zig (1)
1393-1466: Critical: Incomplete fix for double-scheduling race.Line 1453 adds an early return for
old_state == .readyto prevent double-scheduling when multipleSelectWaiterinstances wake the same task concurrently (as discussed in past review). However, this creates a new problem:Issue: The spawn path (lines 1000-1022) starts with task state
.waiting_sync(line 1000), then callsscheduleTask()at line 1022. At that point:
old_state = task.coro.state.swap(.ready, ...)returns.waiting_sync(initial state)- Line 1426 assertion passes:
old_state == .waiting_sync- Code proceeds to migration logic (lines 1431-1449)
- Eventually reaches default path (lines 1455-1466) and schedules the task
But for spawn, we're on the correct executor (self), and there's no prior state to migrate from. The current code works, but the logic is convoluted.
Recommended fix: Add explicit spawn detection before migration logic:
// Handle .waiting_sync or .ready (spawn) states if (old_state != .waiting_sync and old_state != .ready) { std.debug.panic("scheduleTask: unexpected state {} for task {*}", .{ old_state, task }); } + + // Double-wake: another thread already scheduled this task (select() race) + if (old_state == .ready) return; // Sync tasks can migrate for cache locality (waiting_sync state only) if (old_state == .waiting_sync and mode == .maybe_remote and task.pin_count == 0) { ... } // Different runtime - use remote scheduling on home executor self.scheduleTaskRemote(task); return; } - - // Task already transitioned to .ready by another thread - avoid double-schedule - if (old_state == .ready) return;This way:
- Double-wake returns early (before migration logic)
- Spawn (initial
.waiting_sync) goes through migration logic as intended- Migration check explicitly requires
old_state == .waiting_sync
🧹 Nitpick comments (1)
src/runtime.zig (1)
1155-1158: Consider pin_count overflow protection.The
pin_countfield (u32) has no overflow protection. While 4 billion nested pins is unrealistic in practice, a buggy caller could trigger wraparound in a loop, causing the assertion at line 1166 to fire incorrectly.Consider saturation arithmetic:
pub fn beginPin(self: *Executor) void { const current_coro = self.current_coroutine orelse unreachable; const current_task = AnyTask.fromCoroutine(current_coro); - current_task.pin_count += 1; + if (current_task.pin_count < std.math.maxInt(u32)) { + current_task.pin_count += 1; + } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime.zig(15 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: test (windows-latest)
🔇 Additional comments (16)
src/runtime.zig (16)
39-42: LGTM!The
isId()method cleanly distinguishes specific executor IDs from sentinel values (.anyand.same), providing a clear API for pinning logic.
49-52: LGTM!The
pinnedfield is well-documented and correctly defaults tofalse, allowing migration by default while providing explicit control when needed.
64-69: LGTM!The LIFO slot option is well-documented with clear explanation of both the cache locality benefits and the backward-compatibility rationale for enabling it by default.
349-357: LGTM!The refactor correctly derives the home executor from the task's
parent_context_ptr, ensuring that scheduling respects potential task migration.
855-870: LGTM!The queue structure changes are well-documented:
- Migration to FIFO queues provides fairness for regular tasks
- LIFO slot enables cache locality for recently woken tasks
- Starvation counter prevents LIFO slot monopolization
1009-1012: LGTM!The pinning logic correctly sets
pin_count = 1for both explicitly pinned tasks and tasks assigned to specific executors, ensuring they remain on their designated executor.
1095-1109: Excellent migration safety fix!Lines 1106-1109 correctly re-derive the executor from TLS (
Runtime.current_executor) after resuming, since the task may have migrated to a different executor during suspension. Using the capturedselfwould be incorrect and lead to memory safety issues.
1151-1168: LGTM!The pinning API is straightforward with proper assertion to catch unbalanced
beginPin()/endPin()calls. Documentation clearly explains the purpose and usage.
1310-1349: LGTM! Well-designed starvation prevention.The LIFO slot optimization correctly balances cache locality with fairness:
- Allows up to 3 consecutive LIFO polls for cache-hot execution
- At limit, displaces LIFO task to back of FIFO queue
- Counter resets only when polling from ready_queue, ensuring fairness
The
MAX_LIFO_POLLS_PER_TICK = 3value matches Tokio's approach (as noted in comment), providing battle-tested behavior.
1351-1374: LGTM! Clear scheduling policy.The
scheduleTaskLocal()routing is well-designed:
- Yields bypass LIFO slot (not cache-hot, should wait their turn)
- Wakeups use LIFO slot when enabled (cache-hot, immediate execution)
- Displaced tasks go to FIFO queue for fairness
1376-1391: LGTM!The remote scheduling correctly uses the thread-safe
next_ready_queue_remoteand guards notification withremote_initializedcheck to avoid notifying before the event loop is ready.
1979-1999: LGTM!The Runtime-level pinning API correctly delegates to the executor and handles non-coroutine contexts gracefully with no-op behavior.
1244-1248: LGTM!The remote queue draining is correct:
popAll()atomically captures all remote tasks, then pushes them to the localready_queuefor FIFO processing.
917-917: LGTM!The LIFO slot configuration is correctly initialized from
RuntimeOptions.lifo_slot_enabledwith appropriate default (true).
1293-1306: Concern #2 is based on a misunderstanding of queue flow; the other concerns are either valid but not bugs or consistent with codebase patterns.The
next_ready_queueis merged intoready_queueat line 1291 viaconcatByMoving()before the work detection check at line 1295. By that point,next_ready_queueis empty, so checkingnext_ready_queue.headwould be incorrect—it would not reflect actual work availability.The work detection correctly checks
ready_queue.head(which now includes merged yield tasks) andlifo_slot. This is sound.Regarding the wrapping behavior (concern #3): The
+%=pattern is intentional and consistent with similar spin loops elsewhere in the codebase (e.g.,concurrent_queue.zig). Sincespin_countexits at 16 and isu8, wrapping won't occur during normal operation—the pattern is safe.The hardcoded threshold of 16 (concern #1) is reasonable for reducing cross-thread wakeup latency, though it could be made configurable if platform-specific tuning becomes necessary.
Likely an incorrect or invalid review comment.
1441-1441: The race condition in the original review comment is valid. Move parent_context_ptr update before the state change to .ready.The migration sequence has a genuine synchronization issue:
- At line 1405, the task state transitions to
.readywith.releasesemantics- At line 1441,
parent_context_ptris updated (after the state change)- Meanwhile, external code could call
resumeTask()(line 347) with the task's coroutine pointer, which immediately callsExecutor.fromCoroutine(&task.coro)at line 356—readingparent_context_ptrThe
.releasememory ordering on the state store does not guarantee visibility of the subsequent pointer update at line 1441 to readers who observe the.readystate via.acquiresemantics. Another thread could see the task in.readystate but read the staleparent_context_ptrvalue, causing it to route to the wrong executor.Fix: Update
parent_context_ptratomically with the state transition or immediately before it, ensuring both changes are visible together.
* Add dir_open and dir_close operations Implements directory opening and closing operations with async I/O support: - Add DirOpenFlags structure with follow_symlinks and iterate options - Add opendirat() function for POSIX (O_DIRECTORY) and Windows (FILE_FLAG_BACKUP_SEMANTICS) - Add DirOpen and DirClose completion types - Add native io_uring backend support - Add thread pool fallback for other backends - Export new operations in public API * Add dir_open and dir_close to all backends
Summary
Implements task migration and LIFO slot optimization to improve multi-threaded runtime performance by reducing cross-thread wakeup overhead and improving cache locality.
Changes
1. Task State Differentiation (0bc15fd)
.waitinginto.waiting_ioand.waiting_syncstates2. LIFO Slot Optimization (d66a60d)
3. Task Migration (6953096)
.waiting_sync) migrate to waker's executor when woken from different thread.waiting_io) stay pinned to home executor (I/O callbacks are executor-bound)parent_context_ptrto point to new executor's contextPerformance Impact
Task Migration: When task A on executor 1 wakes task B (originally on executor 0), B now migrates to executor 1. This avoids:
LIFO Slot: Recently woken tasks execute immediately with hot cache, improving:
Test Results
All 99 tests pass, including multi-threaded tests that exercise migration across executors.
Summary by CodeRabbit
New Features
Improvements