Repository navigation
Allow async operations from main thread without spawning - #159
Conversation
Add main_task to Executor to support calling rt.sleep() and other async
operations directly from the main thread without requiring spawn().
Key changes:
- Add main_task field to Executor for non-coroutine yield support
- Modify yield() to detect main context and run scheduler loop inline
- Unify run() to use runSchedulerLoop() with main_task.state as exit condition
- Handle main_task specially in scheduleTask() to avoid queuing
- Remove ExecutorWaiter and ThreadWaiter (dead code after refactor)
- Simplify select.waitInternal() to remove no-task handling
This enables patterns like:
const rt = try Runtime.init(allocator, .{});
try rt.sleep(100); // Works without spawn!
WalkthroughAdds a per-thread main_task to Executor, introduces Executor.runSchedulerLoop and executor-centric current-task access, removes thread-based waiters and futex paths in select, simplifies AwaitableList lifecycle, and replaces many Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🧰 Additional context used📓 Path-based instructions (1)**/*.zig📄 CodeRabbit inference engine (CLAUDE.md)
Files:
🧠 Learnings (3)📚 Learning: 2025-11-04T10:29:56.949ZApplied to files:
📚 Learning: 2025-09-27T04:41:48.632ZApplied to files:
📚 Learning: 2025-10-03T11:09:46.846ZApplied to files:
⏰ 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)
🔇 Additional comments (20)
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 |
Unify the scheduler context with main_task's coroutine context. Spawned tasks now yield back to main_task.coro.context instead of a separate main_context field. This simplifies the executor structure and prepares for direct yieldTo between main and spawned tasks.
Both main and spawned tasks now use yieldTo when switching directly to the next ready task. This simplifies the yield logic: 1. If next task available: yieldTo it (both main and spawned) 2. Else if spawned: yield() back to scheduler 3. If main and not ready: run scheduler loop
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (5)
src/runtime.zig (5)
362-378:Executor.fromCoroutine()now depends onparent_context_ptralways pointing atexecutor.main_task.coro.context(including after migrations).The pointer-walk is clever and fast, but very invariant-heavy. Consider adding a debug-only assert that
main_task.coro.parent_context_ptr == &main_task.coro.context(self-pointing) and/or that the recoveredmain_taskhasawaitable.kind == .task, just to make “wrong parent_context_ptr” fail loudly.
388-405: Don’t leavedestroy_fn = undefinedonmain_task.awaitable(future footgun → UB).Today it’s “never destroyed via this”, but if
main_task.awaitableever accidentally gets into the global registry / refcount path,releaseAwaitable()will call an undefined function pointer.Suggestion: set
destroy_fnto a hard panic or a no-op, so mistakes fail safely..awaitable = .{ .kind = .task, - .destroy_fn = undefined, // main_task is never destroyed via this + .destroy_fn = struct { + fn destroy(_: *Runtime, _: *Awaitable) void { + @panic("main_task.awaitable.destroy_fn should never be called"); + } + }.destroy, .wait_node = .{ .vtable = &AnyTask.wait_node_vtable, }, },
546-607:runSchedulerLoop()looks sane, but the finished-task block should use the knowntaskinstead of re-readingself.current_coroutine.Inside the loop you already have
taskand setself.current_coroutine = &task.coro. Re-checkingself.current_coroutineafterstep()is indirect and makes it harder to reason about invariants.A small tightening keeps intent clear:
- if (self.current_coroutine) |current_coro| { - if (current_coro.finished) { - const current_task = AnyTask.fromCoroutine(current_coro); + if (task.coro.finished) { + const current_task = AnyTask.fromCoroutine(&task.coro); const current_awaitable = ¤t_task.awaitable; ... - } - } + }(Not a blocker—more about readability and reducing “optional state” confusion.)
687-698:Executor.run()setsmain_taskto.waitingbut never restores it — OK ifrun()is one-shot, but worth making explicit.If
run()can be called more than once on the same executor (or if users callsleep()afterrun()returns in some future scenario), leavingmain_taskin.waitingcould surprise.If one-shot is intended, I’d document it in the doc comment or add a debug assert on entry (
main_task.state == .ready).
968-983:Runtime.run()reusesExecutor.currentif present: add a guard against calling it from within a coroutine.If
Runtime.run()is invoked whileexecutor.current_coroutine != null, you’ll re-enter the scheduler loop “inside a task”, which is usually a recipe for confusing state (and hard-to-debug deadlocks).Low-cost safety:
if (Executor.current) |executor| { + std.debug.assert(executor.current_coroutine == null); try executor.run(); return; }
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime.zig(17 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
Use
zig envto get the path to the Zig standard library when needed
Files:
src/runtime.zig
🧠 Learnings (3)
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.
Applied to files:
src/runtime.zig
📚 Learning: 2025-09-27T04:41:48.632Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 5
File: src/runtime.zig:257-273
Timestamp: 2025-09-27T04:41:48.632Z
Learning: RefCounter.init() starts with an initial count of 1, not 0. When a task is created in spawn(), the initial count represents the runtime's ownership when stored in self.tasks, and an additional incr() is called for the returned Task(T) handle.
Applied to files:
src/runtime.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.
Applied to files:
src/runtime.zig
⏰ 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 (6)
src/runtime.zig (6)
97-101: Shutdown wakesmain_taskwithout going throughscheduleTask— OK, but keep the state contract consistent.Storing
.readydirectly is fine (run loop polls it), but this creates a “second way” to wakemain_taskvsscheduleTask(). If you keep both, I’d at least comment thatshutdownCallbackintentionally bypassesscheduleTaskand why ordering (.release) is sufficient with the.acquireload inrunSchedulerLoop.
656-662:Executor.getCurrentTask()returningmain_taskas fallback is the right shape for “main thread async”.This simplifies call sites a lot and matches the PR goal.
803-845: Special-casingmain_taskinscheduleTask()makes sense; migration update toparent_context_ptrlooks correct.Two nits to consider:
- In the
main_taskbranch, you wake the loop only when scheduled cross-thread. Ifmain_taskis used to break out of.oncewaits, that’s fine; just be sure the same-thread paths always re-check state afterloop.run()returns (they do).- The migration write
task.coro.parent_context_ptr = ¤t_exec.main_task.coro.contextis now extremely load-bearing; if anything else writesparent_context_ptr,Executor.fromCoroutine()can go sideways (debug assertions suggested earlier help here).
1004-1093: Context APIs now panic outside executor context (getCurrentExecutor), andsleep()/now()rely on that — acceptable, but the behavior change should be loud in docs.Given
Runtime.sleep()is now “main-thread capable” but still requires an active executor on that thread, the panic is fine; just ensure public docs/examples don’t implyRuntime.sleep()works from arbitrary threads without callingRuntime.run()there first.
1224-1261: Tests cover the feature: “implicit run” and “sleep from main” are exactly the right regression net.These tests exercise both “join drives the loop” and “main-thread sleep uses main_task wakeups”, which are the two scary edges here.
489-544: The main_task sleep path doesn't face the lost-wake risk you describe—but it uses a different protocol than spawned tasks.For spawned tasks, the
.preparing_to_waitprotocol works as you said: a waker sees that state and skips scheduling, knowing the task will observe.readyand bail out of the yield. Butsleep()on main_task takes a different path:
timeout.set()queues the timer to the event loop (doesn't invoke callbacks yet)yield(.ready, .waiting)performs the state CAS; if it succeeds, state becomes.waiting- Main thread checks state at line 528; since it's now
.waiting, entersrunSchedulerLoop()runSchedulerLoop()callsloop.run(), which is where the timer callback actually fires- Timer callback calls
loop.wake()to interrupt the loop andstate.swap(.ready)to mark task readyloop.run()returns;runSchedulerLoop()sees state is.readyand exitsThe timer cannot fire between
timeout.set()and the CAS—it only fires whenloop.run()executes, which is after the CAS. Theloop.wake()call provides the "sticky signal" that wakes the event loop, so the wake isn't lost.That said, main_task and spawned tasks use asymmetric wake protocols (loop interrupt vs
.preparing_to_wait). Both work, but worth documenting the distinction.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (3)
src/net.zig (1)
489-489: Same getCurrentTask() null-safety concern applies to network operations.All network IO operations now assume
getCurrentTask()returns a non-null task pointer. This should be verified alongside the file operations (see src/fs/file.zig review comment).Also applies to: 507-507, 546-546, 578-578, 638-638, 675-675, 802-802, 816-816, 914-914, 932-932, 951-951, 970-970, 987-987, 1001-1001
src/sync/channel.zig (1)
94-94: Channel operations also assume getCurrentTask() is non-null.The
receive()andsend()operations previously usedorelse unreachableand now assumegetCurrentTask()always succeeds. These operations need a task context to yield when blocking. Same verification as file/network operations applies.Also applies to: 186-186
src/sync/broadcast_channel.zig (1)
160-160: Broadcast channel receive assumes non-null getCurrentTask().Same concern as regular channels -
receive()requires a task context to suspend when waiting. Should be covered by the same verification.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (13)
examples/sleep.zig(1 hunks)src/core/timeout.zig(2 hunks)src/fs/dir.zig(4 hunks)src/fs/file.zig(9 hunks)src/io.zig(3 hunks)src/net.zig(14 hunks)src/signal.zig(2 hunks)src/sync/Condition.zig(2 hunks)src/sync/Mutex.zig(1 hunks)src/sync/Notify.zig(2 hunks)src/sync/ResetEvent.zig(2 hunks)src/sync/broadcast_channel.zig(1 hunks)src/sync/channel.zig(2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
Use
zig envto get the path to the Zig standard library when needed
Files:
src/sync/Notify.zigsrc/core/timeout.zigexamples/sleep.zigsrc/net.zigsrc/sync/Mutex.zigsrc/sync/ResetEvent.zigsrc/sync/Condition.zigsrc/sync/channel.zigsrc/sync/broadcast_channel.zigsrc/io.zigsrc/fs/dir.zigsrc/signal.zigsrc/fs/file.zig
🧠 Learnings (5)
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 48
File: src/core/ConcurrentAwaitableList.zig:254-269
Timestamp: 2025-10-16T14:33:19.718Z
Learning: In the zio repository's `src/core/ConcurrentAwaitableList.zig` and `src/core/Awaitable.zig`, the `in_list` field should remain debug-only (conditional compilation with `builtin.mode == .Debug`). Double-removal detection in `ConcurrentAwaitableList.remove()` uses pointer-based checks (comparing `prev`/`next` against `head`/`tail`) rather than relying on a regular `in_list` field.
Applied to files:
src/sync/Notify.zigsrc/sync/ResetEvent.zigsrc/sync/Condition.zigsrc/signal.zig
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.659Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Applied to files:
src/sync/Notify.zigsrc/sync/Mutex.zigsrc/sync/ResetEvent.zigsrc/sync/Condition.zigsrc/sync/channel.zig
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.
Applied to files:
src/core/timeout.zigsrc/net.zigsrc/io.zigsrc/signal.zigsrc/fs/file.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.
Applied to files:
src/core/timeout.zigexamples/sleep.zig
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
Applied to files:
src/net.zigsrc/io.zig
⏰ 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 (10)
src/fs/dir.zig (1)
17-17: LGTM - Aligns with main_task refactor.The removal of
orelse unreachableis correct. With the newmain_tasksupport,getCurrentTask()now always returns a non-null task (either from a spawned task or the main thread's task context). The subsequenttask.getExecutor()call would nil-deref anyway if task were null, so this just removes redundant panic machinery.Also applies to: 32-32, 47-47, 61-61
src/sync/Condition.zig (1)
91-91: LGTM - Consistent with runtime refactor.Removing the
orelse unreachableis correct. The main_task changes ensuregetCurrentTask()returns non-null in all valid call contexts (spawned tasks and main thread).Also applies to: 161-161
src/core/timeout.zig (1)
25-25: LGTM - Standard refactor.The change correctly relies on the non-null getCurrentTask() contract established by the main_task addition.
Also applies to: 34-34
src/sync/Notify.zig (1)
110-110: LGTM - Matches pattern.Correct removal of redundant panic path, consistent with the main_task refactor.
Also applies to: 154-154
src/sync/ResetEvent.zig (1)
124-124: LGTM - Standard change.Removal of
orelse unreachablealigns with the main_task refactor ensuring non-null task context.Also applies to: 174-174
src/signal.zig (1)
280-280: LGTM - Consistent refactor.The change correctly assumes non-null task context from getCurrentTask(), enabled by the main_task addition.
Also applies to: 320-320
src/sync/Mutex.zig (1)
70-70: LGTM - Aligns with refactor.Removing
orelse unreachableis correct given the main_task changes guarantee non-null task context.src/io.zig (2)
34-38: LGTM - Good refactor.Capturing
tasklocally incancelIois cleaner than the previous approach and eliminates redundantgetCurrentTask()calls. The removal oforelse unreachableis correct per the main_task changes.
48-49: LGTM - Standard pattern.Removing
orelse unreachableis correct. The main_task addition ensuresgetCurrentTask()returns non-null in all valid contexts.Also applies to: 74-75
src/fs/file.zig (1)
27-27: The panic removal is correct—getCurrentTask()returns a non-optional*AnyTaskpointer.The original code's
orelse @panic("no active task")was guarding against an impossible condition.getCurrentTask()atsrc/runtime.zig:656always returns a valid pointer: either from the current coroutine or frommain_task, which is initialized for all executor instances. The main thread can now use async file operations viamain_task, making the panic unreachable. No null-safety issue exists here.
- Remove shutdown_async, shutdownCallback, shutting_down, maybeShutdown - Main executor exits when main_task is ready (timer/IO/tasks empty) - Non-main executors exit when loop.stopped() (from deinit) - releaseAwaitable wakes main when task list becomes empty - deinit closes task registry and stops non-main executor loops - Simplify tests to call async ops directly from main
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
src/runtime.zig (2)
348-390: main_task design looks sound.The self-referential
parent_context_ptrat line 387 is clever - it terminates the parent chain forfromCoroutine()navigation. Spawned tasks point theirparent_context_ptrto&executor.main_task.coro.context, so the chain always resolves back to the executor.One thing:
destroy_fnis set toundefined(line 381). That's fine since main_task is never destroyed via the awaitable path, but a comment saying "// never called" would make it obvious this isn't an oversight.
1088-1120: shutdown() implementation is solid.The sequence is correct:
- Set
shutting_downflag (prevents new spawns)- Cancel all tasks by walking the registry linked list
- Run scheduler until tasks drain
- Stop non-main executor loops
- Stop thread pool
Walking
tasks.queue.getState().getPtr()directly is a bit low-level but works since you need to iterate without removing. Consider adding aniterate()method to AwaitableList if this pattern shows up elsewhere.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/core/awaitable.zig(1 hunks)src/core/group.zig(1 hunks)src/runtime.zig(23 hunks)src/stdio.zig(4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
Use
zig envto get the path to the Zig standard library when needed
Files:
src/stdio.zigsrc/core/group.zigsrc/core/awaitable.zigsrc/runtime.zig
🧠 Learnings (4)
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 48
File: src/core/ConcurrentAwaitableList.zig:254-269
Timestamp: 2025-10-16T14:33:19.718Z
Learning: In the zio repository's `src/core/ConcurrentAwaitableList.zig` and `src/core/Awaitable.zig`, the `in_list` field should remain debug-only (conditional compilation with `builtin.mode == .Debug`). Double-removal detection in `ConcurrentAwaitableList.remove()` uses pointer-based checks (comparing `prev`/`next` against `head`/`tail`) rather than relying on a regular `in_list` field.
Applied to files:
src/stdio.zigsrc/core/awaitable.zig
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.
Applied to files:
src/stdio.zigsrc/runtime.zig
📚 Learning: 2025-09-27T04:41:48.632Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 5
File: src/runtime.zig:257-273
Timestamp: 2025-09-27T04:41:48.632Z
Learning: RefCounter.init() starts with an initial count of 1, not 0. When a task is created in spawn(), the initial count represents the runtime's ownership when stored in self.tasks, and an additional incr() is called for the returned Task(T) handle.
Applied to files:
src/runtime.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.
Applied to files:
src/runtime.zig
⏰ 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 (13)
src/core/group.zig (1)
143-143: LGTM!Matches the new
AwaitableList.add()signature that returnsvoid. The registry no longer has a closed state to reject additions.src/stdio.zig (3)
90-92: LGTM!Cleaner separation:
shutting_downflag on Runtime now handles shutdown detection instead of baking it into the awaitable list. Same pattern applied at line 172.
109-111: LGTM!Consistent with the new
AwaitableList.add()returningvoid. Theerrdeferon line 111 still handles cleanup if subsequent operations fail.
191-193: LGTM!Same pattern as
concurrentImpl- tasks.add no longer errors, subsequent errdefer handles cleanup.src/core/awaitable.zig (1)
144-163: Good simplification.Stripping the lifecycle state machine from
AwaitableListand moving shutdown logic toRuntime.shutting_downis the right call. The list now does one job: track awaitables. No more dual-purpose closed/open state tracking.
isEmpty()correctly checks whether the queue state is a pointer (has elements) or a sentinel (empty).src/runtime.zig (8)
470-524: yield() main thread path is well-structured.The split between main (
is_main) and spawned task paths is clear:
- Main thread always goes through
runSchedulerLoop()- Spawned tasks try direct scheduling via
yieldTofor efficiency, falling back to schedulerThe assertion at lines 515-518 correctly skips executor migration checks for main (main_task doesn't migrate).
526-588: runSchedulerLoop() is the unified scheduler heart now.Good factoring - both
run()and main-threadyield()use this. Exit conditions are clear:
- Main executor: exits when
main_task.state == .ready- Worker executors: exits when
loop.stopped()The drain-from-remote → process-ready → check-exit → move-yielded → poll-loop sequence is standard scheduler stuff.
596-637: Shield/pin methods still require a spawned coroutine context.These methods (
beginShield,endShield,checkCanceled,beginPin,endPin) all docurrent_coroutine orelse unreachable- they'll panic if called from main thread.Is that intentional? If main thread calls
rt.sleep(), and something tries to shield during that flow, it'll explode. TheRuntime.beginShield()wrapper (lines 997-1001) does have a null check and early return, so the safe path is to usert.beginShield()notexecutor.beginShield()from code that might run on main.Worth a doc comment clarifying "Executor methods assume spawned coroutine context; use Runtime wrapper methods when context might be main."
639-645: getCurrentTask() fallback to main_task enables the feature.This is the key change that makes
rt.sleep()work from main - instead of returning null, it returnsmain_taskwhich has the necessaryawaitableand state fields for yield/wake.
784-791: main_task scheduling short-circuit is correct.Since main_task isn't a real coroutine, it can't be queued. Setting state to
.readyand waking the loop (if remote) is sufficient -runSchedulerLoop()checksmain_task.statedirectly.
869-920: deinit() now delegates to shutdown() - cleaner separation.Moving the cancellation and cleanup logic into
shutdown()makes it reusable and testable independently. The assertion at line 878 (tasks.isEmpty()) is a good sanity check that shutdown actually drained everything.The log at line 874 on shutdown error is reasonable - can't do much else in deinit.
1237-1250: New test validates the PR's main feature."Runtime: sleep from main" directly tests calling
rt.sleep()without spawning - exactly what the PR set out to enable. The timing assertions are reasonable (>= 10ms elapsed).
1056-1067: Panic-on-missing-executor is a breaking change that's well-aligned with actual usage patterns.All call sites in the codebase (50+ usages across sync primitives, I/O, networking, and file operations) are within async methods designed to run in executor context. No existing code calls
getCurrentTask()from non-executor threads or external callbacks. The panic behavior is correct—if code reaches this point outside executor context, it's already broken and deserves to fail fast rather than silently returning null.The panic message is clear. No changes needed.
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
Simplify single-task tests that don't need spawn/runUntilComplete: - fs/file.zig: 4 tests (basic read/write, positional, close, reader/writer) - core/timeout.zig: 6 tests (all except "user cancel has priority") - sync/Mutex.zig: tryLock test - sync/ResetEvent.zig: timedWait timeout and wait on already set event
Simplify the API by removing the runUntilComplete convenience function. Users now use the same spawn+join pattern for running the main task as they do for spawning other tasks.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
src/sync/broadcast_channel.zig (1)
159-162: Add a defensive runtime/task consistency check (or document the contract).
receive()now assumesruntime.getCurrentTask()is always valid; if the API contract is “always non-null under run loop / main_task”, great—then I’d still add a cheap debug assertion that the task/executor matches theruntimepassed in (mirrors whatTimeoutdoes) to catch accidental cross-runtime misuse early.src/fs/file.zig (1)
26-39: Same “current task always exists” assumption everywhere—consider a debug assert for runtime consistency.If
rt.getCurrentTask()is now non-optional by design (main_task), cool—then it’s worth adding astd.debug.assert(task.getExecutor().runtime == rt)in these entrypoints (at least in debug) so accidental cross-runtime/thread misuse fails loud and early.Also applies to: 41-55, 56-70, 72-86, 88-102, 103-117, 118-134, 446-476
src/core/timeout.zig (1)
22-51: Maketimeout_ns→timeout_msconversion overflow-safe.
timeout_ns + (ns_per_ms/2)can overflowu64and trap in safe builds. Consider saturating or usingstd.math.add-style checked math before dividing. Example:- const timeout_ms: u64 = (timeout_ns + std.time.ns_per_ms / 2) / std.time.ns_per_ms; + const half_ms: u64 = std.time.ns_per_ms / 2; + const rounded = std.math.add(u64, timeout_ns, half_ms) catch std.math.maxInt(u64); + const timeout_ms: u64 = rounded / std.time.ns_per_ms;
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (21)
README.md(1 hunks)benchmarks/echo_server.zig(1 hunks)docs/index.md(1 hunks)examples/http_server.zig(1 hunks)src/core/group.zig(4 hunks)src/core/timeout.zig(4 hunks)src/fs/file.zig(9 hunks)src/net/test.zig(3 hunks)src/runtime.zig(24 hunks)src/select.zig(16 hunks)src/signal.zig(9 hunks)src/stdio.zig(16 hunks)src/sync/Barrier.zig(1 hunks)src/sync/Condition.zig(3 hunks)src/sync/Mutex.zig(2 hunks)src/sync/Notify.zig(4 hunks)src/sync/ResetEvent.zig(5 hunks)src/sync/Semaphore.zig(1 hunks)src/sync/broadcast_channel.zig(11 hunks)src/sync/channel.zig(10 hunks)src/sync/future.zig(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/sync/Mutex.zig
🧰 Additional context used
📓 Path-based instructions (1)
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
Use
zig envto get the path to the Zig standard library when needed
Files:
benchmarks/echo_server.zigsrc/sync/Semaphore.zigsrc/sync/future.zigsrc/net/test.zigsrc/sync/Barrier.zigsrc/select.zigexamples/http_server.zigsrc/sync/channel.zigsrc/core/timeout.zigsrc/stdio.zigsrc/signal.zigsrc/fs/file.zigsrc/runtime.zigsrc/sync/broadcast_channel.zigsrc/core/group.zigsrc/sync/Condition.zigsrc/sync/ResetEvent.zigsrc/sync/Notify.zig
🧠 Learnings (7)
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.
Applied to files:
benchmarks/echo_server.zigexamples/http_server.zigsrc/core/timeout.zigsrc/runtime.zigsrc/sync/ResetEvent.zigsrc/sync/Notify.zig
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.659Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Applied to files:
src/sync/Barrier.zigsrc/stdio.zigsrc/sync/Condition.zigsrc/sync/ResetEvent.zig
📚 Learning: 2025-10-23T16:17:53.575Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.575Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.
Applied to files:
src/select.zig
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 48
File: src/core/ConcurrentAwaitableList.zig:254-269
Timestamp: 2025-10-16T14:33:19.718Z
Learning: In the zio repository's `src/core/ConcurrentAwaitableList.zig` and `src/core/Awaitable.zig`, the `in_list` field should remain debug-only (conditional compilation with `builtin.mode == .Debug`). Double-removal detection in `ConcurrentAwaitableList.remove()` uses pointer-based checks (comparing `prev`/`next` against `head`/`tail`) rather than relying on a regular `in_list` field.
Applied to files:
src/select.zigsrc/stdio.zigsrc/sync/Condition.zigsrc/sync/Notify.zig
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.
Applied to files:
src/core/timeout.zigsrc/stdio.zigsrc/fs/file.zigsrc/runtime.zig
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
Applied to files:
src/core/timeout.zig
📚 Learning: 2025-09-27T04:41:48.632Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 5
File: src/runtime.zig:257-273
Timestamp: 2025-09-27T04:41:48.632Z
Learning: RefCounter.init() starts with an initial count of 1, not 0. When a task is created in spawn(), the initial count represents the runtime's ownership when stored in self.tasks, and an additional incr() is called for the returned Task(T) handle.
Applied to files:
src/runtime.zig
⏰ 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 (61)
examples/http_server.zig (1)
91-92: Spawn + join inmain()is the right shape for the new handle-based API.
GivenserverTaskruns forever,join()becoming the “main blocks here” point is expected; error propagation is preserved viatry.src/sync/Semaphore.zig (1)
207-208: Good test coverage for “join drives progress” (main-thread async).
Spawning the waiter and joining it is a solid way to validate the new semantics without relying onrunUntilComplete.src/sync/future.zig (3)
161-163: Test harness migration to spawn + join is consistent and keeps errors visible.
201-203: Same pattern here:spawn+try joinis a clean replacement forrunUntilComplete.
247-249: Multiple-waiter test still reads clearly after the spawn/join swap.benchmarks/echo_server.zig (1)
174-175: Benchmarkmain()now matches the handle-based execution model.
spawn+try joinkeeps the benchmark body inside the runtime while still failing fast on errors.docs/index.md (1)
98-99: Fix the per-connection task lifecycle in the docs example—usedetach()instead ofdeinit().Line 87 calls
task.deinit(), butJoinHandlehas nodeinit()method. The correct API for fire-and-forget per-connection tasks isdetach(), which releases the handle and lets the task run independently. This matches the actual API:JoinHandleprovidesjoin(),cancel(), anddetach()for task lifecycle management.⛔ Skipped due to learnings
Learnt from: lalinsky Repo: lalinsky/zio PR: 18 File: src/net.zig:18-25 Timestamp: 2025-10-03T11:09:46.846Z Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.src/net/test.zig (3)
159-160: LGTM - spawn+join pattern correctly applied.The migration from
runUntilCompleteto explicitspawn+joinis clean and consistent with the PR's goal of unifying the scheduler loop. Error propagation throughtry handle.join(runtime)properly surfaces any failures fromTest.mainFn.
206-207: Consistent with other helper migrations.Same spawn+join pattern applied here. The test semantics remain identical - spawn the main function, wait for completion, propagate errors.
250-251: Pattern applied consistently across all three helpers.All three test helpers (
checkListen,checkBind,checkShutdown) now use the same orchestration approach.README.md (1)
103-104: Documentation correctly updated to reflect the new spawn+join API.The README example now shows the proper way to run the server task. Users reading this will get the right pattern from day one.
src/sync/channel.zig (10)
186-187: Same pattern - direct task access without fallback.Consistent with the change at line 94. Both
receiveandsendnow assume a valid task context exists.
717-718: Test migrated to spawn+join.
trySendandtryReceivetest now uses the new pattern. Logic unchanged, just orchestration.
919-920: Spawn+join for closed channel test.
960-961: Ring buffer wrapping test migrated.
1022-1023: asyncReceive "already ready" test updated.
1049-1050: asyncReceive closed channel test updated.
1116-1117: asyncSend "already ready" test updated.
1143-1144: asyncSend closed channel test updated.
1202-1203: Select on both send/receive test updated.All channel tests consistently migrated to spawn+join. Good batch update.
94-95: Remove the verification request—the change is correct.
rt.getCurrentTask()returns*AnyTask(non-optional), not?*AnyTask, so removingorelse unreachableis the right call. The runtime guarantees a valid task or panics, so the code can assume it always gets a valid pointer. The test changes (spawn+join migrations) are straightforward and fine.src/sync/Barrier.zig (1)
253-254: Single-task barrier test migrated.Makes sense - with only one task, spawn+join is the right call. The multi-task barrier tests correctly continue using
runtime.run()to execute all spawned tasks concurrently.src/sync/Condition.zig (3)
91-92: Direct task access inwait().Same pattern as channel.zig -
getCurrentTask()now returns non-optional. The task is immediately used on line 92 to get the executor, so any null would have crashed anyway. Cleaner this way.
161-162: Consistent change intimedWait().Both wait variants now use direct task access. Pattern applied uniformly.
323-324: Timeout test migrated to spawn+join.Single-task test, so spawn+join is appropriate. The timeout flag is correctly written inside the spawned task and checked after join.
src/sync/broadcast_channel.zig (1)
614-616: Tests switching to spawn+join look correct.This matches the new “async ops from main thread / main_task” direction and keeps tests consistent with task-driven execution.
Also applies to: 655-657, 693-695, 731-733, 759-761, 883-885, 956-958, 987-989, 1024-1026, 1157-1159
src/fs/file.zig (1)
322-349: Tests exercising file ops withoutrt.run()are a good proof point.Assuming the new executor/main_task model is meant to make
read/write/sleepusable from the main thread, these test updates are aligned and look fine.Also applies to: 351-379, 381-399, 401-442
src/core/group.zig (2)
244-246: Group tests moving to spawn+join look consistent with the new runtime model.Also applies to: 275-277, 334-336
122-147: No issues found. Thert.tasks.addcall is genuinely infallible—it uses a pointer-based linked list with mutex synchronization, not an allocating data structure. There's no hidden panic path on OOM and no failure semantics shift from error to panic. The code change is correct.src/core/timeout.zig (1)
25-27: Looks aligned with “timeouts/sleep usable from main thread”, but it relies ongetCurrentTask()always being valid.The new tests strongly exercise that assumption; just make sure the Runtime contract is explicit (main_task always present on the calling thread once initialized / running).
Also applies to: 34-37, 79-227
src/signal.zig (2)
410-413: spawn+join test updates look correct and consistent.Also applies to: 456-459, 486-489, 526-529, 573-576, 609-612, 661-664
274-299: No issue here. The contract forrt.getCurrentTask()is airtight—it returns*AnyTask(non-optional), never null. The Executor implementation guarantees this: it either returns the current coroutine or falls back to&self.main_task, which is always initialized. The type system enforces it, so the immediate dereference inSignal.waitandtimedWaitis safe by design.src/sync/ResetEvent.zig (5)
124-125: Change aligns with the new main_task design.The removal of
orelse unreachableis correct here. With the new executor model,getCurrentTask()always returns a valid task (either a spawned coroutine ormain_taskfor the main thread). This enables callingwait()directly from the main thread without spawning.
174-175: Same pattern aswait()- looks good.Consistent with the change in
wait().timedWait()can now also be called from the main thread.
306-312: Test harness simplified correctly.Direct
expectErrorcall works becausetimedWaitcan now run on the main thread viamain_task. Clean and readable.
358-366: Test now exercises the main-thread path.Calling
reset_event.wait(rt)directly from main validates that the newmain_taskmechanism works for synchronous-looking async operations.
402-403: Test migrated to spawn/join pattern.Consistent with the broader test refactoring across the codebase. The
handle.join(runtime)properly propagates any errors fromasyncTask.src/select.zig (5)
270-271: Removes panic path - now relies on main_task.With
main_taskalways available,getCurrentTask()never returns null in a valid executor context. The panic was defensive code that's no longer needed.
360-361: Consistent with select() change.Same simplification applied to
selectAwaitables. Good.
405-414: waitInternal simplified - thread waiter path removed.The function now assumes an executor context is always available. This is correct given the PR's goal of unifying execution paths via
main_task.
448-470: Cancellation handling unified to yield-based path.The
.cancel_and_continuebranch now uses the sameexecutor.yield()mechanism as regular coroutines. The shield/retry logic is preserved correctly:
- First cancellation triggers shield and calls
fut.cancel()- Loop continues until the future completes
- Shield is ended in defer
This is cleaner than the previous dual-path approach.
543-544: Test pattern standardized.All select tests now use
spawn()+join()instead ofrunUntilComplete(). This is consistent with the removal of thread-based waiting.src/sync/Notify.zig (3)
110-111: Same main_task integration as ResetEvent.
Notify.wait()can now be called from main thread. Pattern is consistent across sync primitives.
154-155: Consistent with wait() change.
377-378: Tests migrated to spawn/join.Consistent test pattern across the codebase.
Also applies to: 445-446
src/stdio.zig (5)
90-92: Shutdown detection simplified.Using an atomic flag (
shutting_down.load(.acquire)) is more straightforward than the previous callback-based approach. The acquire ordering ensures visibility of any state set beforeshutting_downwas set.
109-111: Registry add now propagates errors correctly.Previously, errors from
rt.tasks.add()may have been handled differently. Theerrdeferon line 111 ensures proper cleanup if scheduling fails later. Good defensive pattern.
172-174: Consistent with concurrentImpl changes.Same shutdown check and registry pattern applied to group operations.
Also applies to: 191-192
882-900: Test now uses main-thread sleep directly.This test validates that
io.sleep()works from the main thread - a key feature of this PR. The sleep call goes throughmain_taskinternally.
1318-1356: DNS lookup test migrated to main-thread pattern.The test now runs lookup operations directly from main without spawning. This exercises the new main-thread async capability.
src/runtime.zig (11)
348-352: main_task enables async ops from main thread.This is the core addition of the PR. The
main_taskfield allows the main thread to participate in the same yield/wake mechanisms as spawned tasks, enablingrt.sleep()and similar operations without spawning.The comment accurately notes that
main_task.corois not a real coroutine -scheduleTaskhandles it specially.
357-364: Navigation path updated for main_task.The comment explains the traversal clearly:
- Coroutines have
parent_context_ptrpointing tomain_task.coro.context- Navigate:
context→coro(via@fieldParentPtr) →main_task→executorThis replaces the previous
main_contextfield approach.
374-390: main_task initialization.A few observations:
statestarts as.readywhich is correct for the main threadparent_context_ptrpoints to itself (line 387) - this is intentional since main_task is the rootdestroy_fnis undefined because main_task is never destroyed via this pathclosureis undefined because main_task has no closure (it's not a spawned task)The initialization looks correct for the intended purpose.
470-524: yield() now handles main thread specially.The logic branches on
is_main(line 496):
- Main thread: Always uses
runSchedulerLoop()- no direct coroutine switching- Spawned tasks: Can use direct
yieldTo()for efficiencyThe assertion on line 517 correctly only applies to non-main contexts since
is_maintasks don't have a real coroutine.
526-588: runSchedulerLoop - the unified scheduler.This replaces the previous separate
run()andrunSchedulerLoop()implementations. Key points:
- Lines 533-537: Drains remote queue first (cross-thread tasks)
- Lines 540-567: Processes ready tasks, handles completion, releases stacks
- Lines 570-580: Exit conditions differ by executor type:
- Main executor exits when
main_task.state == .ready- Non-main executors exit when loop is stopped
- Line 587: Uses
no_waitmode when there's work,onceotherwiseThe structure is sound. One minor observation: the finished coroutine handling (lines 549-565) is inline rather than factored out, but it's clear enough.
639-645: getCurrentTask returns main_task when outside coroutine.This is the key API change that enables the whole feature. When
current_coroutineis null (main thread), it returnsmain_taskinstead of null/panic.
784-791: main_task scheduling is state-only.
main_taskis never added to any queue - it just checks its state inrunSchedulerLoop. The wake call on line 788 handles cross-thread notification correctly.
1066-1084: releaseAwaitable wakes main when tasks drain.When
doneis true and the task list becomes empty, it wakesmain_tasksorun()can exit. The mutex lock during shutdown (lines 1069-1075) prevents races with the shutdown iteration.
1241-1254: New test validates the PR's core feature.This test calls
runtime.sleep()directly from main - no spawn needed. This is exactly what the PR enables. The test verifies timing behavior correctly.
805-806: Task migration now updates parent_context_ptr to new executor's main_task.When a task migrates to a different executor for cache locality, its
parent_context_ptris updated to point to the new executor'smain_task.coro.context. This maintains the navigation path (coroutine → executor) correctly after migration.
1087-1124: shutdown() implements graceful termination with correct lock ordering.The sequence is:
- Set
shutting_downflag (prevents new spawns)- Cancel all tasks under mutex lock
- Run main executor until tasks drain
- Stop non-main executor loops
- Stop thread pool
The mutex on lines 1097-1098 is critical—it prevents the task list iteration from racing with
releaseAwaitableremoving tasks. The lock ordering is safe:shutdown_mutexis released beforemain_executor.run()is called, so worker threads callingreleaseAwaitable()during task completion won't contend with the shutdown thread.releaseAwaitable()only usesshutdown_mutex(no other locks involved), and it only acquires it when bothshutting_downanddoneare true—which happens after the iteration critical section completes.
- Add early exit inside task processing loop when main becomes ready - Move remote queue draining after processing current ready queue - Check loop.stopped() for both main and non-main executors - Check main_task.state after loop.run() for I/O wakeups This optimizes the common case of main waiting for a single task (e.g., spawn+join) to exit immediately when that task completes.
Summary
main_taskto Executor to support callingrt.sleep()and other async operations directly from the main thread without requiringspawn()run()andrunSchedulerLoop()- both now use the same scheduler loop with different exit conditionsExecutorWaiter,ThreadWaiter, and related no-task handling in selectTest plan