Repository navigation
Refactor task creation to use create/destroy pattern - #86
Conversation
- Move Task initialization logic from Runtime.spawn() to Task.create() - Move BlockingTask initialization to BlockingTask.create() - Introduce CreateOptions struct for task-specific options (stack_size, pinned) - Separate task creation concerns from runtime orchestration - Consolidate AwaitableList into awaitable.zig module - Rename Awaitable.zig to awaitable.zig following Zig conventions
WalkthroughRemoved legacy core awaitable modules and replaced them with new core modules implementing Awaitable, FutureImpl, Task, and BlockingTask; runtime and many callers updated to import and construct tasks via the new create() APIs and to source AnyTask/resumeTask from core/task.zig. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (1)
🔇 Additional comments (6)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/runtime.zig (1)
1403-1417: Fix compile error in maybeShutdown—error union syntax is invalid.The call to
self.tasks.close()returnserror{NotEmpty}!void, which cannot be used directly in an if-condition as a boolean. The proposed fix is correct: wrap it in a catch-block to extract the error state into a flag, then use the flag for control flow.Apply the suggested diff as-is. This is required for compilation.
🧹 Nitpick comments (3)
src/core/blocking_task.zig (1)
19-24: Empty wait_node_vtable: clarify intent or add a no-op wake.Awaitable.wait_node’s vtable is set to an empty VTable. If WaitNode.VTable requires wake, make it an explicit no-op to document that blocking tasks aren’t resumed via WaitNode and are completed via markComplete().
- pub const wait_node_vtable = WaitNode.VTable{}; + fn noWake(_: *WaitNode) void {} + pub const wait_node_vtable = WaitNode.VTable{ + .wake = noWake, + };Also applies to: 103-111
src/runtime.zig (2)
858-878: Dead migration branch guarded byand false.This disables sync-task migration entirely. If intentional, add a feature flag or TODO; otherwise remove the guard or wire it to an option (e.g., RuntimeOptions.enable_migration).
- if (old_state == .waiting_sync and mode == .maybe_remote and task.pin_count == 0 and false) { + if (old_state == .waiting_sync and mode == .maybe_remote and task.pin_count == 0 and enable_migration) {Define
const enable_migration = false;near Executor and make it configurable later.
274-281: Docs for cancel() contradict safe blocking-task semantics.If we adopt “always execute” for blocking tasks (to guarantee a result), update the comment:
- From: “skip execution if not yet started”
- To: “best-effort; may not preempt already queued work; the task still runs to produce a result”
Please confirm which behavior you want and I’ll follow up with a doc/impl diff across runtime + blocking_task.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
src/core/Awaitable.zig(0 hunks)src/core/AwaitableList.zig(0 hunks)src/core/awaitable.zig(1 hunks)src/core/blocking_task.zig(1 hunks)src/core/task.zig(1 hunks)src/io/base.zig(1 hunks)src/runtime.zig(5 hunks)
💤 Files with no reviewable changes (2)
- src/core/AwaitableList.zig
- src/core/Awaitable.zig
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
PR: lalinsky/zio#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/blocking_task.zig
🔇 Additional comments (3)
src/io/base.zig (1)
6-6: Import move looks correct; IO resume mode stays appropriate.AnyTask now comes from core/task.zig and callback resumes with
.local, which matches the executor-local wakeup requirement for IO. No action needed.src/core/blocking_task.zig (1)
88-94: destroyFn frees only the wrapper; caller owns the result.This matches the intended ownership model for async blocking tasks. Just calling allocator.destroy(self) here is correct. Based on learnings.
src/core/awaitable.zig (1)
23-31: RefCounter initialization confirmed — starts at 1 as expected.Verified that
RefCounter(u32).init()initializes.refsto 1, not 0. The runtime's assumption holds: registry holds the initial ref,JoinHandleincrements, andreleaseAwaitable(done=true)only destroys when handle is gone. No changes needed.
| // Check if the task was canceled before it started executing | ||
| if (!any_blocking_task.awaitable.canceled.load(.acquire)) { | ||
| // Execute the user's blocking function only if not canceled | ||
| any_blocking_task.execute_fn(any_blocking_task); | ||
| } | ||
|
|
||
| // Mark awaitable as complete and wake all waiters (thread-safe) | ||
| // Even if canceled, we still mark as complete so waiters wake up | ||
| any_blocking_task.awaitable.markComplete(); | ||
|
|
There was a problem hiding this comment.
Cancel-before-start can complete without a result → panic at join/getResult.
threadPoolCallback skips execution when canceled, then marks complete. Since JoinHandle.join for blocking tasks returns T (not Cancelable), this path leaves FutureResult unset and getResult() will crash. Execute the function regardless of the canceled flag, or change the API to propagate error.Canceled. Minimal fix below keeps API stable:
- // Check if the task was canceled before it started executing
- if (!any_blocking_task.awaitable.canceled.load(.acquire)) {
- // Execute the user's blocking function only if not canceled
- any_blocking_task.execute_fn(any_blocking_task);
- }
+ // Always execute so a result is produced; cancellation is best-effort.
+ any_blocking_task.execute_fn(any_blocking_task);If you want cancel to truly skip work, then JoinHandle.join must return an error-capable type for blocking tasks and FutureResult must store that state. Otherwise, you risk UB/panic on getResult().
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Check if the task was canceled before it started executing | |
| if (!any_blocking_task.awaitable.canceled.load(.acquire)) { | |
| // Execute the user's blocking function only if not canceled | |
| any_blocking_task.execute_fn(any_blocking_task); | |
| } | |
| // Mark awaitable as complete and wake all waiters (thread-safe) | |
| // Even if canceled, we still mark as complete so waiters wake up | |
| any_blocking_task.awaitable.markComplete(); | |
| // Always execute so a result is produced; cancellation is best-effort. | |
| any_blocking_task.execute_fn(any_blocking_task); | |
| // Mark awaitable as complete and wake all waiters (thread-safe) | |
| // Even if canceled, we still mark as complete so waiters wake up | |
| any_blocking_task.awaitable.markComplete(); | |
🤖 Prompt for AI Agents
In src/core/blocking_task.zig around lines 31 to 40, the current logic skips
calling any_blocking_task.execute_fn when the task is canceled but still marks
the awaitable complete, leaving the FutureResult unset and causing a panic on
getResult(); to fix this while keeping the JoinHandle API stable, remove the
canceled check and always call any_blocking_task.execute_fn(any_blocking_task)
so the FutureResult is populated by the task execution before
any_blocking_task.awaitable.markComplete() is called.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/signal.zig (1)
329-330: Same issue as in wait() - move imports to file level.See comment on lines 264-266. These function-scoped imports should be consolidated at the top of the file.
🧹 Nitpick comments (1)
src/signal.zig (1)
264-266: Move function-scoped imports to file level.Both
AnyTaskandresumeTaskare imported inside thewait()function. This pattern is repeated intimedWait()at lines 329-330. While Zig allows function-scoped imports, this is inconsistent with the file-level imports at the top of the file and makes the code harder to scan.Additionally,
AnyTaskis still imported fromruntime.ziginstead ofcore/task.zig, which is inconsistent with the refactoring goal.Move these imports to the file level (near line 6) and update
AnyTaskto import fromcore/task.zig:const Runtime = @import("runtime.zig").Runtime; const Cancelable = @import("common.zig").Cancelable; const Timeoutable = @import("common.zig").Timeoutable; +const AnyTask = @import("core/task.zig").AnyTask; +const resumeTask = @import("core/task.zig").resumeTask;Then remove the function-scoped imports at lines 264-266 and 329-330.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/io/base.zig(1 hunks)src/signal.zig(2 hunks)src/sync/Condition.zig(1 hunks)src/sync/Mutex.zig(1 hunks)src/sync/ResetEvent.zig(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
PR: lalinsky/zio#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/Mutex.zig
🔇 Additional comments (4)
src/sync/ResetEvent.zig (1)
52-52: Import path updated correctly.The
resumeTaskimport now points to the newcore/task.zigmodule, aligning with the refactoring to consolidate task management.src/sync/Mutex.zig (1)
29-29: Import path updated correctly.The
resumeTaskfunction is now sourced fromcore/task.zig, matching the refactoring pattern across the codebase.src/sync/Condition.zig (1)
56-56: Import path updated correctly.The
resumeTaskfunction now comes fromcore/task.zig, consistent with the task management consolidation.src/io/base.zig (1)
5-6: Import paths updated correctly.Both
resumeTaskandAnyTasknow come fromcore/task.zig, completing the migration of task-related functionality to the core module.
…exports - Move AnyTask and resumeTask imports to file level in signal.zig - Update AnyTask import in select.zig to use core/task.zig directly - Remove public re-exports of AnyTask, resumeTask, and AnyBlockingTask from runtime.zig
Summary
This PR refactors task initialization to follow a cleaner
create()/destroy()pattern, separating task creation concerns from runtime orchestration:Taskinitialization logic fromRuntime.spawn()toTask.create()insrc/core/task.zigBlockingTaskinitialization toBlockingTask.create()insrc/core/blocking_task.zigCreateOptionsstruct for task-specific options (stack_size,pinned)AwaitableListintoawaitable.zigmoduleAwaitable.zig→awaitable.zigfollowing Zig naming conventionsThis change simplifies
runtime.zigby removing ~370 lines of task initialization code and improves separation of concerns.Test plan
./check.sh(format, build, tests)