Repository navigation
Refactor AnyTask into Awaitable and AnyTask hierarchy - #15
Conversation
Split the task system to support multiple awaitable types: - Add `Awaitable` base type with kind discriminator, ref counting, and intrusive list support - Refactor `AnyTask` to embed `Awaitable` as first field - Add `AnyTask.fromAwaitable()` with runtime kind assertion for safe casting - Add `AnyTask.fromCoroutine()` for consistent API - Rename `AnyTaskList` to `AwaitableList` operating on `*Awaitable` - Update all queue operations and sync primitives to use AwaitableList - Rename `task_node` variables to `task` for clarity This prepares the runtime for future `BlockingTask` support, which will also embed `Awaitable` with a different kind discriminator, allowing both coroutine-based and blocking tasks to be stored in the same wait queues.
WalkthroughIntroduces an Awaitable abstraction and AwaitableList queues across the runtime and sync primitives. Replaces AnyTaskList-based scheduling with awaitable-centric structures. Adapts task lifecycle, join/wait, spawn, markReady, and run-loop logic to operate on Awaitable. Updates Mutex, Condition, and ResetEvent wait queues and timed wait contexts to use awaitables. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant User
participant Runtime
participant Task
participant Awaitable
participant Scheduler as Ready/Cleanup Queues
rect rgb(240,245,255)
User->>Runtime: spawn(func, args, options)
Runtime->>Task: create Task/AnyTask
Task->>Awaitable: init(kind=coro, destroy_fn)
Runtime->>Scheduler: enqueue Awaitable (ready_queue)
end
loop run-loop
Scheduler-->>Runtime: pop Awaitable (ready)
Runtime->>Task: AnyTask.fromAwaitable
Runtime->>Task: resume coroutine
alt task completes
Task->>Scheduler: enqueue Awaitable (cleanup_queue)
else task blocks/waits
Task->>Awaitable: add to wait_queue (sync primitive)
end
end
rect rgb(240,255,240)
User->>Runtime: wait/join(handle)
Runtime->>Task: AnyTask.fromCoroutine(current)
Runtime->>Awaitable: park current on target's waiting_list
Note over Runtime,Awaitable: Wake when target ready/completed
end
rect rgb(255,245,240)
Runtime->>Awaitable: releaseAwaitable
Awaitable-->>Task: destroyFn callback
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests
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: 0
🧹 Nitpick comments (7)
src/sync.zig (2)
61-75: Condition.wait: enqueue-before-unlock pattern is correct.This avoids missed signals in the single-threaded scheduler. Reacquire after wake maintains invariant.
Consider documenting that signal/broadcast should be called on the same runtime thread to prevent misuse; if cross-thread signaling is needed, provide a runtime.post or loop.async wrapper.
119-136: Timer callback: safe removal + wakeup.Removing from wait_queue before setting timed_out and markReady prevents double wake. Disarming is correct.
Small nit: consider setting timed_out before remove’s branch to make state visible even if a racy second path checks it (debug aid). Not functionally required under current model.
src/runtime.zig (5)
69-82: Awaitable core types introduced cleanly.AwaitableKind + Awaitable fields (next, waiting_list, ref_count, destroy_fn, in_list[Debug]) cover required state for intrusive lists and lifecycle.
Consider documenting ownership semantics for ref_count (which entities hold a ref) near the type to prevent misuse.
202-205: append delegates to push.Minor duplication retained for API parity with previous code; acceptable.
Consider removing append or making push private to reduce surface area; both are identical.
221-258: remove: correct singly-linked removal with tail update.Head and middle removal logic looks right; in_list toggled (Debug) and next cleared.
We might add a Debug-only assert to ensure awaitable != null and not already removed to catch misuse earlier.
414-446: run loop: ready/dead handling via Awaitable.
- Reschedule list prevents immediate requeue churn.
- Dead branch wakes waiters from awaitable.waiting_list, then moves awaitable to cleanup_queue and drops runtime’s map entry.
Solid flow.Consider bounded per-iteration processing (e.g., cap ready pops) to avoid starvation under heavy producer workloads; optional given current scope.
465-470: markReady enqueues via awaitable from coroutine.Waiting-state assert catches misuse early; append to ready_queue is correct.
If we later support cross-thread wakeups, replace panic with a no-op or metric in release builds to avoid crashing on benign races; keep the assert in Debug.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/runtime.zig(14 hunks)src/sync.zig(15 hunks)
🔇 Additional comments (20)
src/sync.zig (11)
4-6: Imports aligned with new runtime API.Switch to Awaitable/AwaitableList is consistent with the refactor.
11-11: Mutex.wait_queue: type change LGTM.Initialization to empty AwaitableList is correct.
32-34: Enqueue current as awaitable before suspending is correct.Using AnyTask.fromCoroutine and appending &task.awaitable fits the new model.
Please confirm that Mutex.lock/unlock are only invoked from the runtime thread (i.e., within coroutines). If external threads can call unlock, we’d need synchronization around wait_queue to avoid data races.
48-54: Ownership handoff ordering is sound.Store(&task.coro, .release) before markReady ensures proper happens-before; assertion in lock() uses .acquire load. Good.
84-109: Condition.timedWait: timeout context uses awaitable pointer correctly.Appending awaitable, passing &task.awaitable to the timer’s context, and guarding with timed_out is coherent.
152-164: Condition.signal/broadcast: awaitable-centric wakeups look good.Conversion via AnyTask.fromAwaitable and markReady(&task.coro) matches runtime expectations.
172-173: ResetEvent.wait_queue: type change LGTM.Matches AwaitableList usage elsewhere.
201-211: ResetEvent.set: atomic state + broadcast to waiters.swap(.is_set, .release) then draining wait_queue is correct. Good separation from .unset/.waiting.
Docs call ResetEvent “thread-safe”; however, wait_queue operations are not synchronized for cross-thread callers. Please confirm set/reset are only called on the runtime thread; if not, we should route cross-thread set() via the loop (e.g., xev async) or protect wait_queue.
231-238: ResetEvent.wait: enqueue-then-suspend pattern is correct.Appending &task.awaitable before waitForReady prevents missed set() in single-threaded scheduling.
259-286: ResetEvent.timedWait: timeout path mirrors Condition.timedWait.Using awaitable in TimeoutContext and appending before scheduling timer is consistent.
295-311: Timer callback removal on ResetEvent is correct.remove() gate avoids spurious wake if signaled first; markReady then disarm is fine.
src/runtime.zig (9)
90-97: Safe conversions with runtime kind assert.fromAwaitable asserts .coro, preventing miscasts when BlockingTask arrives. fromCoroutine path is idiomatic.
169-187: AwaitableList.push: invariants enforced in Debug.Setting next=null and in_list=true (Debug) prevents multi-enqueue bugs. Tail insertion implements FIFO.
189-205: AwaitableList.pop: state reset is correct.Clears in_list (Debug) and next; head/tail maintenance correct.
206-219: concatByMoving: efficient list splice.Handles empty ‘other’ fast-path; resets other’s head/tail. Works with Debug in_list invariant since nodes remain enqueued.
271-273: ready/cleanup queues migrated to AwaitableList.Matches new scheduling approach.
348-367: spawn: awaitable init, ready enqueue, and ref_count incr.Setting kind=.coro and destroy_fn, then enqueuing awaitable and incrementing refcount aligns with lifecycle design.
If RefCounter.init() does not start at 1, we must call incr() twice to account for both runtime map and JoinHandle. Please verify with the script above.
375-379: releaseAwaitable: simple ref-drop → destroy.Centralized ownership release is clear.
472-484: wait: joins implemented via awaitable.waiting_list.Self-wait check, fast-return if dead, then append current.awaitable and suspend. Clean and minimal.
109-118: Approve code changes
destroyFn and deinit correctly route through Awaitable: releaseAwaitable centralizes destruction; destroyFn converts back to AnyTask and frees Task(T). Verified RefCounter(u32).init() sets the initial count to 1 and spawn() calls incr() exactly once, yielding two references (runtime + JoinHandle).
* Remove userdata from callback signature Users can now access userdata via c.userdata instead of receiving it as a parameter. This simplifies callback signatures from: fn(userdata, loop, completion) to: fn(loop, completion) Changes: - Updated Completion.CallbackFn and Work.WorkFn signatures - Modified Completion.call and thread pool to not pass userdata - Updated Work.init to set c.userdata for easy access - Updated tests to use c.userdata Fixes #15 Co-authored-by: Lukáš Lalinský <[email protected]> * Fix Work callback signature to receive Work pointer WorkFn now receives (*Loop, *Work) instead of (*Loop, *Completion). This allows callbacks to access the Work struct directly, including its userdata field. Work.init no longer incorrectly sets c.userdata. Co-authored-by: Lukáš Lalinský <[email protected]> * Use implicit struct literal syntax in Work.init This makes Work.init consistent with all other init functions in the file, which use 'return .{' instead of 'return Type{'. Co-authored-by: Lukáš Lalinský <[email protected]> --------- Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> Co-authored-by: Lukáš Lalinský <[email protected]>
Summary
Splits the task system to support multiple awaitable types, preparing for future
BlockingTasksupport.Changes
Add
Awaitablebase type with:AwaitableKindenum with.corooption)next,waiting_list)Refactor
AnyTaskto:Awaitableas first fieldfromAwaitable()method with runtime kind assertion for safe castingfromCoroutine()method for consistent APIRename
AnyTaskList→AwaitableList:*AwaitablepointersClean up variable naming:
task_node→taskthroughout sync.zigtaskPtrFromCoroPtr()helperWhy
This refactoring prepares the runtime for future
BlockingTasksupport. Blocking tasks will also embedAwaitablewith a different kind discriminator (.blocking), allowing both coroutine-based and blocking tasks to:The type-safe casting via
AnyTask.fromAwaitable()ensures we never accidentally treat a blocking task as a coroutine task.Testing
All 27 tests pass ✓
Summary by CodeRabbit
Refactor
New Features
Chores