Skip to content

Refactor task creation to use create/destroy pattern - #86

Merged
lalinsky merged 4 commits into
mainfrom
refactor-task-creation
Oct 27, 2025
Merged

lalinsky merged 4 commits into
mainfrom
refactor-task-creation

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

This PR refactors task initialization to follow a cleaner create()/destroy() pattern, separating task creation concerns from runtime orchestration:

  • Move Task initialization logic from Runtime.spawn() to Task.create() in src/core/task.zig
  • Move BlockingTask initialization to BlockingTask.create() in src/core/blocking_task.zig
  • Introduce CreateOptions struct for task-specific options (stack_size, pinned)
  • Consolidate AwaitableList into awaitable.zig module
  • Rename Awaitable.zig → awaitable.zig following Zig naming conventions

This change simplifies runtime.zig by removing ~370 lines of task initialization code and improves separation of concerns.

Test plan

  • All 129 unit tests pass
  • Verified with ./check.sh (format, build, tests)

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

coderabbitai Bot commented Oct 27, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Removed 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

Cohort / File(s) Summary
Awaitable core consolidation
\src/core/Awaitable.zig`, `src/core/AwaitableList.zig`, `src/core/awaitable.zig``
Removed old Awaitable/AwaitableList modules; added core/awaitable.zig exporting AwaitableKind, Awaitable (cancel/asyncWait/asyncCancelWait/markComplete), FutureImpl(comptime T, ...), and AwaitableList (add/remove/close/isEmpty/isClosed/pop).
Task abstraction
\src/core/task.zig``
New task.zig introducing AnyTask, Task(comptime T) built on FutureImpl, CreateOptions, ResumeMode, resumeTask, task create/destroy, coroutine/stack wiring, and executor scheduling integration.
Blocking task
\src/core/blocking_task.zig``
New blocking_task.zig introducing AnyBlockingTask, BlockingTask(comptime T), thread-pool callback, create/destroy, and runtime/thread-pool registration.
Runtime integration & spawn refactor
\src/runtime.zig``
Rewired spawn paths to use Task.create(...) and BlockingTask.create(...); re-exported core awaitable/task symbols; made Runtime.releaseAwaitable public; adapted scheduling and lifecycle handling to new create/registry patterns.
Callsite import updates
\src/io/base.zig`, `src/signal.zig`, `src/sync/Condition.zig`, `src/sync/Mutex.zig`, `src/sync/ResetEvent.zig`, `src/select.zig``
Redirected imports of AnyTask/resumeTask/Awaitable sources from runtime.zig to the new core/* modules; no logic changes beyond import locations.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Files/areas needing extra attention:
    • awaitable.asyncWait / asyncCancelWait / markComplete and WaitQueue sentinel transitions.
    • FutureImpl type conversions (toAny/fromAny/toAwaitable/fromAwaitable) and correctness of Cancelable wait path.
    • Task.create / destroy: stack allocation/release, coroutine setup, pin/shield semantics.
    • BlockingTask thread-pool callback, execute/destroy lifecycle and runtime.releaseAwaitable usage.
    • Runtime spawn refactor and exported re-exports to ensure no unresolved imports across modules.

Possibly related PRs

Poem

🧵 Cores untangled, threads set free,
Tasks get stacks and futures flee,
Wait nodes ring and queues unroll,
Resume the work, resume the soul,
Runtime hums — a smaller, fiercer tree.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Refactor task creation to use create/destroy pattern" directly describes the main change in this PR. The raw summary confirms that task initialization logic has been extracted into Task.create() and BlockingTask.create() functions, which is exactly what the title communicates. The phrasing is concise and specific—a developer scanning commit history would immediately understand that this refactoring introduces a constructor/destructor pattern for task lifecycle management.
Description Check ✅ Passed The PR description accurately maps to the changeset. It explains the core refactoring (moving Task initialization from Runtime.spawn() to Task.create() and BlockingTask initialization to BlockingTask.create()), details supporting changes (CreateOptions struct, consolidating AwaitableList into awaitable.zig, renaming the file), quantifies the impact (~370 lines removed from runtime.zig), and provides test verification (129 passing tests). The description is factually grounded in what the raw summary shows: new files created (src/core/task.zig, src/core/blocking_task.zig, src/core/awaitable.zig), old files deleted (Awaitable.zig, AwaitableList.zig), and multiple import updates to source from the new module locations.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor-task-creation

📜 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 9764898 and 16c9ec3.

📒 Files selected for processing (3)
  • src/runtime.zig (5 hunks)
  • src/select.zig (1 hunks)
  • src/signal.zig (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/signal.zig
🔇 Additional comments (6)
src/select.zig (1)

5-5: LGTM - Import path updated to core module.

The import path change correctly points to the new location of AnyTask in core/task.zig. This aligns with the refactoring objectives and the type is used consistently throughout the file.

src/runtime.zig (5)

23-27: LGTM - Core module imports properly centralized.

The imports correctly source AnyTask, Task, ResumeMode, resumeTask, and BlockingTask from their new core module locations. This establishes the foundation for the create/destroy pattern refactor.


137-140: LGTM - Awaitable types sourced from core module.

The awaitable module path correctly points to core/awaitable.zig, and AwaitableList is properly sourced from the module. This aligns with the PR's consolidation of awaitable types.


461-480: LGTM - Task creation properly refactored to create/destroy pattern.

The refactor successfully adopts the new pattern:

  • Task.create() with CreateOptions struct consolidates initialization logic
  • Error handling chain is correct: errdefer task.destroy() → errdefer tasks.remove()
  • Ref count increment after scheduling is safe since the runtime holds a reference via the tasks registry
  • Scheduling, metrics tracking, and handle return follow proper sequence

This achieves the PR's goal of moving task initialization logic out of runtime.zig into Task.create().


1216-1234: LGTM - BlockingTask creation follows same create/destroy pattern.

The blocking task refactor mirrors the regular task pattern consistently:

  • BlockingTask.create() centralizes initialization logic
  • Error handling cascade with proper errdefer cleanup
  • Scheduling to thread pool occurs after registry add (correct ordering)
  • Ref count management is safe

The pattern is applied uniformly across both task types, which is good for maintainability.


1418-1418: LGTM - Visibility change needed for destroy pattern.

Making releaseAwaitable public is necessary for the new create/destroy pattern. The Task.destroy() and BlockingTask.destroy() methods (now in core modules) need to call this to manage reference counts and trigger shutdown checks.


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.

@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: 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() returns error{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 by and 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

📥 Commits

Reviewing files that changed from the base of the PR and between edb89ea and 1015616.

📒 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 .refs to 1, not 0. The runtime's assumption holds: registry holds the initial ref, JoinHandle increments, and releaseAwaitable(done=true) only destroys when handle is gone. No changes needed.

Comment on lines +31 to +40
// 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();

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.

⚠️ Potential issue | 🔴 Critical

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.

Suggested change
// 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.

Comment thread src/core/task.zig Resolved

@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

♻️ 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 AnyTask and resumeTask are imported inside the wait() function. This pattern is repeated in timedWait() 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, AnyTask is still imported from runtime.zig instead of core/task.zig, which is inconsistent with the refactoring goal.

Move these imports to the file level (near line 6) and update AnyTask to import from core/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

📥 Commits

Reviewing files that changed from the base of the PR and between 1015616 and 5064679.

📒 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 resumeTask import now points to the new core/task.zig module, aligning with the refactoring to consolidate task management.

src/sync/Mutex.zig (1)

29-29: Import path updated correctly.

The resumeTask function is now sourced from core/task.zig, matching the refactoring pattern across the codebase.

src/sync/Condition.zig (1)

56-56: Import path updated correctly.

The resumeTask function now comes from core/task.zig, consistent with the task management consolidation.

src/io/base.zig (1)

5-6: Import paths updated correctly.

Both resumeTask and AnyTask now come from core/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
@lalinsky
lalinsky merged commit 491512b into main Oct 27, 2025
@lalinsky
lalinsky deleted the refactor-task-creation branch October 27, 2025 09:46
@coderabbitai coderabbitai Bot mentioned this pull request Nov 12, 2025
2 tasks
@coderabbitai coderabbitai Bot mentioned this pull request Dec 7, 2025
2 tasks done
@coderabbitai coderabbitai Bot mentioned this pull request 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