Repository navigation
Conversation
+ replace individual ready queues with a multi-stack pool per executor + introduce work stealing logic to balance task distribution + add a centralized global task queue protected by a mutex + update scheduler to periodically check for global or stolen tasks + add `pop` method to `ConcurrentStack` for atomic item retrieval
|
Important Review skippedDraft detected. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe runtime scheduler now uses per-executor stealable stacks plus a global queue, with atomic readiness tracking and idle-executor wake coordination. ChangesExecutor scheduling and work-stealing rewrite
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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 |
+ optimize `has_local_work` check by simplifying condition logic + use `unreachable` for mutex locking to reflect system constraints + update task stealing to re-queue tasks already processed this tick + panic on failed remote task scheduling to prevent silent failures
lalinsky
left a comment
There was a problem hiding this comment.
This is a critical core part of the library, so be prepared that I'll be hard on the review. :)
Nothing, but a perfect solution, will be accepted.
+ replace custom mutex with `std.Io.Mutex` for global queue synchronization + update mutex methods to accept IO instance + limit task draining to the current executor's stack + adjust global queue check frequency in `getNextTask`
+ simplify global queue locking by removing I/O context dependencies. + integrate periodic global queue polling directly into the executor task loop. + remove error handling from scheduleTaskRemote as the mutex operations are now infallible.
|
@lalinsky, I think the mutex might need a way to let us know it didn't succeed. e.g., a situation where we previously locked and we're attempting to lock again. really, the only issue might be logic bugs, but it seems to happen (ran into one today 😅) |
+ add `idle_mask` and `searchers` atomic fields to `Runtime` to track executor activity. + introduce `checkAboutForWork` to encapsulate local, stolen, and global task discovery. + update worker loop to manage idle bit during blocking I/O calls. + implement `wakeOne` to target a single idle executor instead of broadcasting wakeups.
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/runtime.zig`:
- Line 512: The global-queue pop path in the runtime still contains a leftover
debug statement, so remove the `std.debug.print` call from the queue-pop logic
in `runtime.zig` to avoid printing on every successful pop. Locate the debug
output inside the code path that performs the global queue pop and delete it,
keeping the rest of the queue handling unchanged.
- Around line 633-647: The task migration option is not affecting dispatch
because Runtime.initStatic still assigns the shared loop_group and
scheduleTask() still always routes tasks through the current/home executor path.
Update Runtime.initStatic, Executor, and scheduleTask to branch on
enable_task_migration so non-migration mode keeps tasks local to one executor
and does not use the shared/global queue, or remove enable_task_migration
entirely if it is always enabled.
- Around line 533-543: The steal path in the queue-pool loop is leaving the
victim executor’s ready_count unchanged after tasks are removed by popAll(), so
adjust the victim’s counter when transferring work in the steal logic around
victim.queue_pool, push_cursor, and ready_count. Update the stealing code to
decrement victim.ready_count by the number of drained tasks before or after
moving them, while still incrementing self.ready_count for the stolen tasks, so
maybeYield() reflects the victim’s actual remaining work.
- Around line 461-473: Reset runtime.searchers on both execution paths in the
worker loop around checkAboutForWork and the idle_mask handling, because
wakeOne() relies on the 0 -> 1 transition and the current early-return path
leaves the token stuck at 1 when work is already available. Update the logic so
the cmpxchgStrong(1, 0, ...) reset happens regardless of whether the branch
takes .no_wait or .once, ensuring future wakeups from global_queue pushes can
arm a sleeper correctly.
- Around line 454-459: The shuffle in `popAll()`/task redistribution inside
`runtime.zig` is incorrectly incrementing `ready_count` for tasks that are only
being moved between `queue_pool` stacks. Remove the `fetchAdd(1)` from the
`while (drained.pop())` loop in the `queue_pool` transfer logic, and keep the
existing count unchanged since these tasks are already accounted for by the
scheduler state used by `maybeYield()`.
- Around line 1048-1061: The wake token in Runtime.wakeOne is left set after
Executor.run() takes the .no_wait path, so later wakeOne calls can no longer
acquire it and wake an idle executor. Move the searchers reset out of the .once
branch in Executor.run() so it is cleared for both .once and .no_wait flows, and
keep the wakeOne logic unchanged except for relying on that token being released
correctly.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 47f52521-ab38-497a-a5eb-261b6b5ef6cf
📒 Files selected for processing (2)
src/runtime.zigsrc/utils/concurrent_stack.zig
+ decrement ready_count of victim when stealing tasks + remove unnecessary debug print + remove redundant ready_count increment in drain loop
|
will keep at it in the morning. the failing ci, some seem to be unrelated but others seem to be an issue with using a 64 bit atomic with 32 bit archs? (I'm unsure). how do we deal with failing ci? and tell me what part of this needs improvements |
+ add atomic global_queue_count to reduce lock contention + implement batch popping from the global queue + ensure correct ready_count decrements when stealing tasks + fix task scheduling priority to prefer local execution over remote + simplify queue_pool initialization using @Splat
There was a problem hiding this comment.
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)
624-628: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winUpdate
global_queue_countwhile holding the queue mutex.There is a window after
push()/unlock()but beforefetchAdd()where another popper that already passed the count check can pop this uncounted node and thenfetchSub()from zero. Keep the queue mutation and count mutation in the same mutex window.🐛 Proposed fix
const wait_node = &task.awaitable.wait_node; self.runtime.global_queue_mutex.lock(); self.runtime.global_queue.push(wait_node); + _ = self.runtime.global_queue_count.fetchAdd(1, .acq_rel); self.runtime.global_queue_mutex.unlock(); - _ = self.runtime.global_queue_count.fetchAdd(1, .acq_rel); if (self.runtime.options.enable_task_migration) { self.runtime.wakeOne(); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/runtime.zig` around lines 624 - 628, The `global_queue_count` update in `runtime.zig` is happening outside the `global_queue_mutex` critical section in the `wait_node` enqueue path. Move the count increment into the same mutex-held window as the `global_queue.push(wait_node)` inside the relevant runtime queueing code so both the queue mutation and count mutation are synchronized together, using the `global_queue_mutex`, `global_queue`, and `global_queue_count` symbols to locate the fix.
591-600: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winAvoid
ConcurrentStack.pop()here. It doesswap(null)and then restoreschain.next, so a concurrentpush()in that gap can be overwritten and dropped. Use a CAS-based pop, or stop callingpop()on this stack until the primitive is fixed.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/runtime.zig` around lines 591 - 600, The task selection path in `Runtime` is using `ConcurrentStack.pop()`, which can lose nodes because it clears the head before restoring the next pointer. Update this branch to avoid calling `stack.pop()` from the ready/task loop and instead use a CAS-based pop implementation, or replace the usage with a safer primitive until `ConcurrentStack` itself is fixed. Keep the change localized around the `stack.pop()` / `stack.push(node)` logic in `runtime.zig` so `last_run_tick` and `ready_count` handling stays unchanged.
♻️ Duplicate comments (2)
src/runtime.zig (2)
470-483: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winRelease
searcherson the.no_waitpath too.This still leaves
searchers == 1whencheckAboutForWork()finds work and the executor runs.no_wait, so laterwakeOne()calls can stop waking idle executors. Move the reset after theif/elseso both paths release the token.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/runtime.zig` around lines 470 - 483, The .no_wait branch in runtime.zig leaves the searchers token held when checkAboutForWork() finds work, which can block later wakeOne() calls from waking idle executors. Update the logic around the self.loop.run(.no_wait) / self.loop.run(.once) paths in runtime main loop so the searchers reset via cmpxchgStrong(1, 0, .acq_rel, .acquire) happens after the if/else, ensuring both execution paths release the token consistently.
673-682: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winGate the current-executor fast path by runtime and migration mode.
Line 673 schedules onto whatever executor is current. With
enable_task_migration = false, that still migrates tasks; with nested/different runtimes, it can enqueue a task into the wrong runtime. Only usecurrent_execwhen it is the home executor, or when it belongs to the same runtime and migration is enabled; otherwise inject into the home executor and wake it.🐛 Proposed fix
- if (getCurrentExecutorOrNull()) |current_exec| { + if (getCurrentExecutorOrNull()) |current_exec| { + if (current_exec == home_exec or + (current_exec.runtime == home_exec.runtime and home_exec.runtime.options.enable_task_migration)) + { + current_exec.scheduleTaskLocal(task); + return; + } + } + + if (home_exec.runtime.options.enable_task_migration) { + home_exec.scheduleTaskRemote(task); + } else { + home_exec.scheduleTaskLocal(task); + home_exec.loop.wake(); + } - current_exec.scheduleTaskLocal(task); - return; - } - - if (home_exec.runtime.options.enable_task_migration) { - home_exec.scheduleTaskRemote(task); - } else { - home_exec.scheduleTaskLocal(task); - }Based on learnings,
enable_task_migration == falsemeans each executor should behave as an independent event loop.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/runtime.zig` around lines 673 - 682, The fast path in `scheduleTask` / `getCurrentExecutorOrNull()` is too broad and can route work to the wrong executor or runtime. Update the current-executor branch so it is only used when `current_exec` is the home executor, or when it belongs to the same runtime and `enable_task_migration` is enabled; otherwise fall back to scheduling on `home_exec` and wake it appropriately. Keep the existing `enable_task_migration` branch behavior aligned with `home_exec.scheduleTaskRemote` versus `home_exec.scheduleTaskLocal`.Source: Learnings
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@src/runtime.zig`:
- Around line 624-628: The `global_queue_count` update in `runtime.zig` is
happening outside the `global_queue_mutex` critical section in the `wait_node`
enqueue path. Move the count increment into the same mutex-held window as the
`global_queue.push(wait_node)` inside the relevant runtime queueing code so both
the queue mutation and count mutation are synchronized together, using the
`global_queue_mutex`, `global_queue`, and `global_queue_count` symbols to locate
the fix.
- Around line 591-600: The task selection path in `Runtime` is using
`ConcurrentStack.pop()`, which can lose nodes because it clears the head before
restoring the next pointer. Update this branch to avoid calling `stack.pop()`
from the ready/task loop and instead use a CAS-based pop implementation, or
replace the usage with a safer primitive until `ConcurrentStack` itself is
fixed. Keep the change localized around the `stack.pop()` / `stack.push(node)`
logic in `runtime.zig` so `last_run_tick` and `ready_count` handling stays
unchanged.
---
Duplicate comments:
In `@src/runtime.zig`:
- Around line 470-483: The .no_wait branch in runtime.zig leaves the searchers
token held when checkAboutForWork() finds work, which can block later wakeOne()
calls from waking idle executors. Update the logic around the
self.loop.run(.no_wait) / self.loop.run(.once) paths in runtime main loop so the
searchers reset via cmpxchgStrong(1, 0, .acq_rel, .acquire) happens after the
if/else, ensuring both execution paths release the token consistently.
- Around line 673-682: The fast path in `scheduleTask` /
`getCurrentExecutorOrNull()` is too broad and can route work to the wrong
executor or runtime. Update the current-executor branch so it is only used when
`current_exec` is the home executor, or when it belongs to the same runtime and
`enable_task_migration` is enabled; otherwise fall back to scheduling on
`home_exec` and wake it appropriately. Keep the existing `enable_task_migration`
branch behavior aligned with `home_exec.scheduleTaskRemote` versus
`home_exec.scheduleTaskLocal`.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 5097e629-64c7-4efd-b166-6689dbafd7bc
📒 Files selected for processing (1)
src/runtime.zig
|
I think we will need to change course a little bit. I'm sorry to say this, but I don't have much confidence that you know what you are doing too well here. Like, the last commit, introducing a non-concurrent doubly-linked list and removing the last_tick fairness policy, is very wrong. Can you please write down the design of what you want to end up with? And then follow that design. |
+ change ready_count load to acquire order for better performance + prevent race conditions in idle state entry by double-checking work + add assertion in scheduleTaskLocal to verify executor locality
|
I've done a LOT of benchmarking, all possible variants of concurrent linked lists, plus the Go-style ring buffer, and I must say, the ring buffer is by far the cheapest option. It's super close to the current plain-ptr linked list. The atomic linked lists are 1.5-2x slower in a single channel ping-pong benchmark. This is why I wanted to do it in phases, because it allows us to decide on the queue before reworking the whole scheduler. It's not possible to get relevant numbers if you mix too many changes. If you want, I can open a PR for the ring buffer that essentially implements phase 1 of my original design. It just replaces the current queues, but doesn't add work stealing yet. And then you can work on the design of the idle/searching executors + work stealing. |
yes, do |
|
I've merged the queue swap, plus had to fix a nasty bug where LLVM was silently ignoring our register clobbers and the queue swap exposed it. |
|
work stealing requires a new pr and branch or we'll just have to squash the merge |
closes: #460