Skip to content

Allow async operations from main thread without spawning - #159

Merged
lalinsky merged 15 commits into
mainfrom
refactor-main-task-yield
Dec 14, 2025
Merged

lalinsky merged 15 commits into
mainfrom
refactor-main-task-yield

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

  • Add main_task to Executor to support calling rt.sleep() and other async operations directly from the main thread without requiring spawn()
  • Unify run() and runSchedulerLoop() - both now use the same scheduler loop with different exit conditions
  • Remove dead code: ExecutorWaiter, ThreadWaiter, and related no-task handling in select

Test plan

  • All 168 existing tests pass
  • New test "Runtime: sleep from main" validates the feature

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!
@coderabbitai

coderabbitai Bot commented Dec 14, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds 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 getCurrentTask() orelse guards with direct calls; tests and examples switched from runUntilComplete to spawn+join.

Changes

Cohort / File(s) Summary
Executor & runtime core
src/runtime.zig
Add main_task: AnyTask; implement fn runSchedulerLoop(self: *Executor) !void; move current-task access to executor-centric model; update init/run/deinit and shutdown to use main_task and runSchedulerLoop; remove legacy shutdownCallback/shutdown_async and main_context.
Task plumbing
src/core/task.zig
AnyTask.create now uses executor.main_task.coro.context as parent_context_ptr; update coroutine→executor mapping and fromCoroutine traversal to account for main_task.
Scheduler / yield semantics
src/runtime.zig (yield/run)
Yield differentiates main-thread vs coroutine paths; main thread enters runSchedulerLoop; non-main coroutines yield/schedule next ready; Executor.run updated for new exit semantics.
Awaitable registry
src/core/awaitable.zig
Remove AwaitableList state machine, close, isClosed, and pop; simplify add() to always push; keep remove() and isEmpty(); public signatures adjusted.
Select / wait model
src/select.zig
Remove ThreadWaiter and futex-based waiting; always use current task's wait_node; unify winner/cleanup and cancellation to coroutine-style path.
I/O, FS & net call sites
src/io.zig, src/fs/file.zig, src/fs/dir.zig, src/net.zig
Replace guarded rt.getCurrentTask() orelse panic with const task = rt.getCurrentTask() (no immediate panic); capture task locally and use task.getExecutor(); remove thread-blocking panics at call sites.
Sync primitives
src/sync/Mutex.zig, src/sync/Condition.zig, src/sync/Notify.zig, src/sync/ResetEvent.zig, src/sync/broadcast_channel.zig, src/sync/channel.zig, src/sync/Semaphore.zig, src/sync/Barrier.zig
Replace runtime.getCurrentTask() orelse unreachable with runtime.getCurrentTask() in wait/send/receive paths; update tests to spawn tasks and join handles instead of runUntilComplete.
Signals & timed waits
src/signal.zig, src/core/timeout.zig
Replace orelse/unreachable guards when fetching current task; adjust timeout APIs to rely on executor-centric current task.
Groups & stdio/task lists
src/core/group.zig, src/stdio.zig
Remove try around rt.tasks.add(&task.awaitable) (now plain add); use shutting_down.load(.acquire) for shutdown checks; stop swallowing add() failures; tests updated to spawn+join.
Examples, docs, benchmarks & tests
examples/*.zig, docs/index.md, benchmarks/echo_server.zig, many src/* tests
Replace runUntilComplete usage with spawn(...) + handle.join(rt) across examples, docs, benchmarks, and tests; rename runtime var to rt in many tests.
Misc small edits
src/fs.zig, src/io.zig, README.md, manifest_file, build.zig
Remove orelse/unreachable guards, capture current task locally in call sites, and adapt test scaffolds and examples to spawn/join flow.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Pay extra attention to:
    • src/runtime.zig — correctness of runSchedulerLoop: draining remote tasks, ready-queue scheduling, finished-task cleanup (stack release, awaitable wake), and main vs non-main exit conditions.
    • src/select.zig — ensure removal of thread-based waiters preserves wake/race semantics previously provided by futex paths.
    • Widespread removal of orelse guards (IO/FS/net/sync) — verify callers cannot encounter null getCurrentTask() during shutdown or thread startup.
    • src/core/awaitable.zig & src/stdio.zig — shutdown sequencing and error propagation after AwaitableList simplification and removed catches around tasks.add().

Possibly related PRs

Poem

The main task sits where threads once stood,
The scheduler hums, dispatching work as it should,
No futex clanks — just nodes that sleep and wake,
Spawn, join, and finish: each coroutine takes its stake,
A cleaner loop, one heartbeat for each task. 🚦

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed Title clearly summarizes the main feature: allowing async operations from the main thread without spawning.
Description check ✅ Passed Description directly relates to the changeset, covering main_task addition, run/runSchedulerLoop unification, and dead code removal.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor-main-task-yield

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5ac40d5 and ecb8984.

📒 Files selected for processing (1)
  • src/runtime.zig (24 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

Use zig env to 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 (20)
src/runtime.zig (20)

348-352: Clear documentation for main_task field.

The comments clearly explain the purpose and special handling. The field is marked undefined, which is correct since it's initialized in init().


357-364: Navigation through main_task is correct.

The updated fromCoroutine correctly navigates the new hierarchy: context → coro → main_task → executor. This matches the initialization where spawned tasks have parent_context_ptr pointing to main_task.coro.context.


470-524: Correctly handles main thread vs spawned task yield paths.

The bifurcation at line 496 is appropriate:

  • Main thread has no coroutine to yield, so it must use runSchedulerLoop()
  • Spawned tasks can optimize with direct yieldTo() when another task is ready

The migration check (lines 515-518) correctly skips the main thread case.


529-592: Scheduler loop correctly implements dual exit conditions.

The loop handles both main executor (exits when main_task.state == .ready) and non-main executors (exits when loop.stopped()). The dual checks at lines 564-566 and 587-590 ensure main executor responsiveness to wake events.

Stack release before markComplete (lines 550-556) is the correct order to avoid use-after-free.


642-648: getCurrentTask now supports main thread context.

Returning main_task when current_coroutine is null allows main-thread callers to use async operations without spawning. This is the core of the new capability.


675-682: Simplified run() implementation using runSchedulerLoop.

Setting main_task.state to .waiting (line 680) and calling runSchedulerLoop() cleanly expresses the intent: wait until all tasks complete. The early return for empty task list prevents unnecessary event loop cycles.


787-794: Special case for main_task is correctly implemented.

The early return prevents main_task from being queued (since it's not a real coroutine). The loop.wake() call when scheduled remotely ensures the event loop picks up the state change.


808-808: Migration correctly updates parent_context_ptr.

When a task migrates to a different executor, updating parent_context_ptr to point to the new executor's main_task.coro.context maintains the correct executor association for fromCoroutine() navigation.


845-847: Shutdown coordination fields are appropriate.

The shutdown_mutex protects task list iteration during shutdown, preventing races with concurrent releaseAwaitable calls. The atomic shutting_down flag prevents new spawns.


873-882: Graceful shutdown in deinit prevents resource leaks.

Calling shutdown() before cleanup ensures tasks complete and resources are released. Logging errors instead of panicking allows cleanup to proceed even if shutdown encounters issues.


915-917: Spawn rejection during shutdown prevents resource leaks.

The shutting_down check at the start of spawn() and spawnBlocking() correctly prevents new tasks from being created during the shutdown sequence, avoiding tasks that would never complete.

Also applies to: 925-927


1069-1088: Correct shutdown coordination in releaseAwaitable.

The conditional locking (lines 1072-1078) only acquires shutdown_mutex during shutdown, avoiding overhead in the normal path. Waking main_task when the task list empties (lines 1084-1087) allows run() and runSchedulerLoop() to exit cleanly.


1093-1127: Shutdown sequence is well-structured.

The three-phase shutdown is correct:

  1. Cancel all tasks under lock (lines 1099-1108)
  2. Drive main executor until tasks complete (line 1111)
  3. Stop non-main executors and thread pool (lines 1114-1126)

The lock during cancellation prevents races with concurrent task completion, and main_executor.run() ensures canceled tasks propagate their cancellation errors.


978-987: Runtime methods correctly delegate to current executor.

The early return in yield() (line 978) is safe for threads without an executor. The sleep() method (line 986) correctly panics via getCurrentExecutor() if called without executor context, since sleep requires event loop access.


1052-1067: Panic behavior is appropriate for executor-only operations.

getCurrentTask() and now() correctly panic when called without executor context via getCurrentExecutor(). These operations fundamentally require an executor, so failing fast is better than returning sentinel values.


1166-1177: Test correctly exercises spawnBlocking.

The test properly spawns a blocking task, waits for completion, and cleans up with deferred cancellation. The pattern matches the recommended usage.


1220-1242: Test validates implicit execution via join.

This test confirms that join() implicitly drives the executor through waitUntilComplete(), which uses the scheduler loop. The test exercises the core use case without explicit run().


1244-1257: Test validates the core new feature: main-thread async operations.

This test exercises the primary capability added by this PR: calling runtime.sleep() directly from the main thread without spawn(). The main_task mechanism enables this by providing a task context for timeout and yield operations.


1259-1306: Tests cover monotonic time and cancellation correctly.

The now() test (lines 1259-1274) exercises main-thread sleep while validating time progression. The cancellation test (lines 1276-1306) properly spawns a sleeping task, cancels it, and verifies early termination with timing constraints.


374-390: The concern about undefined destroy_fn is not valid. The code is safe by design.

destroy_fn is only called at line 1081 when awaitable.ref_count.decr() returns true. RefCounter.decr() returns true only if the counter was > 0 before decrementing. Since main_task.awaitable.ref_count starts at 0 (default initialization) and is never incremented anywhere in the codebase—only spawned tasks increment their ref_count at spawn time—decr() will always return false for main_task. This means destroy_fn will never be invoked on main_task.awaitable, regardless of any code path. The comment at line 381 correctly describes this intentional design.

Likely an incorrect or invalid review comment.


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.

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

@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 (5)
src/runtime.zig (5)

362-378: Executor.fromCoroutine() now depends on parent_context_ptr always pointing at executor.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 recovered main_task has awaitable.kind == .task, just to make “wrong parent_context_ptr” fail loudly.


388-405: Don’t leave destroy_fn = undefined on main_task.awaitable (future footgun → UB).

Today it’s “never destroyed via this”, but if main_task.awaitable ever accidentally gets into the global registry / refcount path, releaseAwaitable() will call an undefined function pointer.

Suggestion: set destroy_fn to 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 known task instead of re-reading self.current_coroutine.

Inside the loop you already have task and set self.current_coroutine = &task.coro. Re-checking self.current_coroutine after step() 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 = &current_task.awaitable;
                         ...
-                    }
-                }
+                }

(Not a blocker—more about readability and reducing “optional state” confusion.)


687-698: Executor.run() sets main_task to .waiting but never restores it — OK if run() is one-shot, but worth making explicit.

If run() can be called more than once on the same executor (or if users call sleep() after run() returns in some future scenario), leaving main_task in .waiting could 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() reuses Executor.current if present: add a guard against calling it from within a coroutine.

If Runtime.run() is invoked while executor.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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f552d7 and e30a326.

📒 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 env to 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 wakes main_task without going through scheduleTask — OK, but keep the state contract consistent.

Storing .ready directly is fine (run loop polls it), but this creates a “second way” to wake main_task vs scheduleTask(). If you keep both, I’d at least comment that shutdownCallback intentionally bypasses scheduleTask and why ordering (.release) is sufficient with the .acquire load in runSchedulerLoop.


656-662: Executor.getCurrentTask() returning main_task as fallback is the right shape for “main thread async”.

This simplifies call sites a lot and matches the PR goal.


803-845: Special-casing main_task in scheduleTask() makes sense; migration update to parent_context_ptr looks correct.

Two nits to consider:

  • In the main_task branch, you wake the loop only when scheduled cross-thread. If main_task is used to break out of .once waits, that’s fine; just be sure the same-thread paths always re-check state after loop.run() returns (they do).
  • The migration write task.coro.parent_context_ptr = &current_exec.main_task.coro.context is now extremely load-bearing; if anything else writes parent_context_ptr, Executor.fromCoroutine() can go sideways (debug assertions suggested earlier help here).

1004-1093: Context APIs now panic outside executor context (getCurrentExecutor), and sleep()/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 imply Runtime.sleep() works from arbitrary threads without calling Runtime.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_wait protocol works as you said: a waker sees that state and skips scheduling, knowing the task will observe .ready and bail out of the yield. But sleep() on main_task takes a different path:

  1. timeout.set() queues the timer to the event loop (doesn't invoke callbacks yet)
  2. yield(.ready, .waiting) performs the state CAS; if it succeeds, state becomes .waiting
  3. Main thread checks state at line 528; since it's now .waiting, enters runSchedulerLoop()
  4. runSchedulerLoop() calls loop.run(), which is where the timer callback actually fires
  5. Timer callback calls loop.wake() to interrupt the loop and state.swap(.ready) to mark task ready
  6. loop.run() returns; runSchedulerLoop() sees state is .ready and exits

The timer cannot fire between timeout.set() and the CAS—it only fires when loop.run() executes, which is after the CAS. The loop.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.

@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: 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() and send() operations previously used orelse unreachable and now assume getCurrentTask() 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

📥 Commits

Reviewing files that changed from the base of the PR and between e30a326 and 54c13ef.

📒 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 env to get the path to the Zig standard library when needed

Files:

  • src/sync/Notify.zig
  • src/core/timeout.zig
  • examples/sleep.zig
  • src/net.zig
  • src/sync/Mutex.zig
  • src/sync/ResetEvent.zig
  • src/sync/Condition.zig
  • src/sync/channel.zig
  • src/sync/broadcast_channel.zig
  • src/io.zig
  • src/fs/dir.zig
  • src/signal.zig
  • src/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.zig
  • src/sync/ResetEvent.zig
  • src/sync/Condition.zig
  • src/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.zig
  • src/sync/Mutex.zig
  • src/sync/ResetEvent.zig
  • src/sync/Condition.zig
  • src/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.zig
  • src/net.zig
  • src/io.zig
  • src/signal.zig
  • src/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.zig
  • examples/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.zig
  • src/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 unreachable is correct. With the new main_task support, getCurrentTask() now always returns a non-null task (either from a spawned task or the main thread's task context). The subsequent task.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 unreachable is correct. The main_task changes ensure getCurrentTask() 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 unreachable aligns 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 unreachable is correct given the main_task changes guarantee non-null task context.

src/io.zig (2)

34-38: LGTM - Good refactor.

Capturing task locally in cancelIo is cleaner than the previous approach and eliminates redundant getCurrentTask() calls. The removal of orelse unreachable is correct per the main_task changes.


48-49: LGTM - Standard pattern.

Removing orelse unreachable is correct. The main_task addition ensures getCurrentTask() 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 *AnyTask pointer.

The original code's orelse @panic("no active task") was guarding against an impossible condition. getCurrentTask() at src/runtime.zig:656 always returns a valid pointer: either from the current coroutine or from main_task, which is initialized for all executor instances. The main thread can now use async file operations via main_task, making the panic unreachable. No null-safety issue exists here.

Comment thread examples/sleep.zig Resolved
- 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

@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 (2)
src/runtime.zig (2)

348-390: main_task design looks sound.

The self-referential parent_context_ptr at line 387 is clever - it terminates the parent chain for fromCoroutine() navigation. Spawned tasks point their parent_context_ptr to &executor.main_task.coro.context, so the chain always resolves back to the executor.

One thing: destroy_fn is set to undefined (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:

  1. Set shutting_down flag (prevents new spawns)
  2. Cancel all tasks by walking the registry linked list
  3. Run scheduler until tasks drain
  4. Stop non-main executor loops
  5. 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 an iterate() method to AwaitableList if this pattern shows up elsewhere.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ae0b87e and f817a92.

📒 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 env to get the path to the Zig standard library when needed

Files:

  • src/stdio.zig
  • src/core/group.zig
  • src/core/awaitable.zig
  • src/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.zig
  • src/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.zig
  • 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 (13)
src/core/group.zig (1)

143-143: LGTM!

Matches the new AwaitableList.add() signature that returns void. The registry no longer has a closed state to reject additions.

src/stdio.zig (3)

90-92: LGTM!

Cleaner separation: shutting_down flag 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() returning void. The errdefer on 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 AwaitableList and moving shutdown logic to Runtime.shutting_down is 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 yieldTo for efficiency, falling back to scheduler

The 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-thread yield() 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 do current_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. The Runtime.beginShield() wrapper (lines 997-1001) does have a null check and early return, so the safe path is to use rt.beginShield() not executor.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 returns main_task which has the necessary awaitable and 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 .ready and waking the loop (if remote) is sufficient - runSchedulerLoop() checks main_task.state directly.


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.

@lalinsky

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Dec 14, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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.

@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/sync/broadcast_channel.zig (1)

159-162: Add a defensive runtime/task consistency check (or document the contract).

receive() now assumes runtime.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 the runtime passed in (mirrors what Timeout does) 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 a std.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: Make timeout_ns → timeout_ms conversion overflow-safe.

timeout_ns + (ns_per_ms/2) can overflow u64 and trap in safe builds. Consider saturating or using std.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

📥 Commits

Reviewing files that changed from the base of the PR and between 0109083 and 5ac40d5.

📒 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 env to get the path to the Zig standard library when needed

Files:

  • benchmarks/echo_server.zig
  • src/sync/Semaphore.zig
  • src/sync/future.zig
  • src/net/test.zig
  • src/sync/Barrier.zig
  • src/select.zig
  • examples/http_server.zig
  • src/sync/channel.zig
  • src/core/timeout.zig
  • src/stdio.zig
  • src/signal.zig
  • src/fs/file.zig
  • src/runtime.zig
  • src/sync/broadcast_channel.zig
  • src/core/group.zig
  • src/sync/Condition.zig
  • src/sync/ResetEvent.zig
  • src/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.zig
  • examples/http_server.zig
  • src/core/timeout.zig
  • src/runtime.zig
  • src/sync/ResetEvent.zig
  • src/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.zig
  • src/stdio.zig
  • src/sync/Condition.zig
  • src/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.zig
  • src/stdio.zig
  • src/sync/Condition.zig
  • src/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.zig
  • src/stdio.zig
  • src/fs/file.zig
  • src/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 in main() is the right shape for the new handle-based API.
Given serverTask runs forever, join() becoming the “main blocks here” point is expected; error propagation is preserved via try.

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 on runUntilComplete.

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 join is a clean replacement for runUntilComplete.


247-249: Multiple-waiter test still reads clearly after the spawn/join swap.

benchmarks/echo_server.zig (1)

174-175: Benchmark main() now matches the handle-based execution model.
spawn + try join keeps 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—use detach() instead of deinit().

Line 87 calls task.deinit(), but JoinHandle has no deinit() method. The correct API for fire-and-forget per-connection tasks is detach(), which releases the handle and lets the task run independently. This matches the actual API: JoinHandle provides join(), cancel(), and detach() 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 runUntilComplete to explicit spawn + join is clean and consistent with the PR's goal of unifying the scheduler loop. Error propagation through try handle.join(runtime) properly surfaces any failures from Test.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 receive and send now assume a valid task context exists.


717-718: Test migrated to spawn+join.

trySend and tryReceive test 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 removing orelse unreachable is 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 in wait().

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 in timedWait().

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 without rt.run() are a good proof point.

Assuming the new executor/main_task model is meant to make read/write/sleep usable 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. The rt.tasks.add call 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 on getCurrentTask() 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 for rt.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 in Signal.wait and timedWait is safe by design.

src/sync/ResetEvent.zig (5)

124-125: Change aligns with the new main_task design.

The removal of orelse unreachable is correct here. With the new executor model, getCurrentTask() always returns a valid task (either a spawned coroutine or main_task for the main thread). This enables calling wait() directly from the main thread without spawning.


174-175: Same pattern as wait() - 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 expectError call works because timedWait can now run on the main thread via main_task. Clean and readable.


358-366: Test now exercises the main-thread path.

Calling reset_event.wait(rt) directly from main validates that the new main_task mechanism 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 from asyncTask.

src/select.zig (5)

270-271: Removes panic path - now relies on main_task.

With main_task always 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_continue branch now uses the same executor.yield() mechanism as regular coroutines. The shield/retry logic is preserved correctly:

  1. First cancellation triggers shield and calls fut.cancel()
  2. Loop continues until the future completes
  3. 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 of runUntilComplete(). 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 before shutting_down was set.


109-111: Registry add now propagates errors correctly.

Previously, errors from rt.tasks.add() may have been handled differently. The errdefer on 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 through main_task internally.


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_task field allows the main thread to participate in the same yield/wake mechanisms as spawned tasks, enabling rt.sleep() and similar operations without spawning.

The comment accurately notes that main_task.coro is not a real coroutine - scheduleTask handles it specially.


357-364: Navigation path updated for main_task.

The comment explains the traversal clearly:

  1. Coroutines have parent_context_ptr pointing to main_task.coro.context
  2. Navigate: context → coro (via @fieldParentPtr) → main_task → executor

This replaces the previous main_context field approach.


374-390: main_task initialization.

A few observations:

  • state starts as .ready which is correct for the main thread
  • parent_context_ptr points to itself (line 387) - this is intentional since main_task is the root
  • destroy_fn is undefined because main_task is never destroyed via this path
  • closure is 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 efficiency

The assertion on line 517 correctly only applies to non-main contexts since is_main tasks don't have a real coroutine.


526-588: runSchedulerLoop - the unified scheduler.

This replaces the previous separate run() and runSchedulerLoop() implementations. Key points:

  1. Lines 533-537: Drains remote queue first (cross-thread tasks)
  2. Lines 540-567: Processes ready tasks, handles completion, releases stacks
  3. 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
  4. Line 587: Uses no_wait mode when there's work, once otherwise

The 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_coroutine is null (main thread), it returns main_task instead of null/panic.


784-791: main_task scheduling is state-only.

main_task is never added to any queue - it just checks its state in runSchedulerLoop. The wake call on line 788 handles cross-thread notification correctly.


1066-1084: releaseAwaitable wakes main when tasks drain.

When done is true and the task list becomes empty, it wakes main_task so run() 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_ptr is updated to point to the new executor's main_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:

  1. Set shutting_down flag (prevents new spawns)
  2. Cancel all tasks under mutex lock
  3. Run main executor until tasks drain
  4. Stop non-main executor loops
  5. Stop thread pool

The mutex on lines 1097-1098 is critical—it prevents the task list iteration from racing with releaseAwaitable removing tasks. The lock ordering is safe: shutdown_mutex is released before main_executor.run() is called, so worker threads calling releaseAwaitable() during task completion won't contend with the shutdown thread. releaseAwaitable() only uses shutdown_mutex (no other locks involved), and it only acquires it when both shutting_down and done are 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.
@lalinsky
lalinsky merged commit 2f9dfd5 into main Dec 14, 2025
@lalinsky
lalinsky deleted the refactor-main-task-yield branch December 14, 2025 21:18
This was referenced Jan 10, 2026
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