Skip to content

Refactor AnyTask into Awaitable and AnyTask hierarchy - #15

Merged
lalinsky merged 1 commit into
mainfrom
refactor/awaitable-anytask-split
Oct 1, 2025
Merged

lalinsky merged 1 commit into
mainfrom
refactor/awaitable-anytask-split

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 1, 2025 •

Copy link
Copy Markdown
Owner

Summary

Splits the task system to support multiple awaitable types, preparing for future BlockingTask support.

Changes

  • Add Awaitable base type with:

    • Kind discriminator (AwaitableKind enum with .coro option)
    • Reference counting
    • Intrusive linked list support (next, waiting_list)
    • Type-erased destructor function pointer
  • Refactor AnyTask to:

    • Embed Awaitable as first field
    • Add fromAwaitable() method with runtime kind assertion for safe casting
    • Add fromCoroutine() method for consistent API
  • Rename AnyTaskList → AwaitableList:

    • Operates on *Awaitable pointers
    • Used in ready/cleanup queues and all sync primitives
  • Clean up variable naming:

    • Rename task_node → task throughout sync.zig
    • Remove old taskPtrFromCoroPtr() helper

Why

This refactoring prepares the runtime for future BlockingTask support. Blocking tasks will also embed Awaitable with a different kind discriminator (.blocking), allowing both coroutine-based and blocking tasks to:

  • Be stored in the same wait queues
  • Use the same synchronization primitives
  • Share the same reference counting and lifecycle management

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

    • Migrated runtime and synchronization internals to a unified awaitable-based model for queuing and scheduling.
    • Streamlined task join/wait paths to use a single runtime wait mechanism.
    • Updated run loop and cleanup processing to operate on awaitable queues.
  • New Features

    • More consistent and predictable waiting/wake-up behavior across Mutex, Condition, and ResetEvent.
  • Chores

    • Public API adjustments to synchronization wait queues; projects using custom integrations with these queues may require minor updates.

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

coderabbitai Bot commented Oct 1, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Introduces 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

Cohort / File(s) Summary of Changes
Awaitable-centric runtime overhaul
src/runtime.zig
Adds AwaitableKind, Awaitable, and AwaitableList. Embeds Awaitable in AnyTask with fromAwaitable/fromCoroutine helpers. Converts ready/cleanup queues to AwaitableList. Updates spawn, wait, join, result, destroy/deinit, markReady, release logic, and run-loop to operate on Awaitable instead of AnyTask. Exposes Awaitable-related APIs.
Sync primitives migrate to Awaitable
src/sync.zig
Replaces AnyTaskList with AwaitableList in Mutex, Condition, ResetEvent. Enqueues/removes awaitables instead of task nodes. Updates timedWait TimeoutContext from task_node: *AnyTask to awaitable: *Awaitable. Adjusts wake/signal/broadcast paths to convert via AnyTask.fromAwaitable.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I thump my paws on ordered ground,
Awaitables hop in tidy round;
Queues now shimmer, neat and bright,
Tasks become the moonlit night—
Wake, resume, and gently glide,
Carrots queued, bugs set aside.
Hop, schedule, hop—then ride! 🥕✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly captures the main objective of the changeset by indicating that the existing AnyTask abstraction is being refactored into a hierarchy with Awaitable as a base type and AnyTask as a specialized variant, which aligns directly with the introduction of AwaitableKind and the refactoring of task queues and lifecycle to operate on Awaitable handles.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/awaitable-anytask-split

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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 13f78f4 and 4b55306.

📒 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).

@lalinsky
lalinsky merged commit 6cd7d16 into main Oct 1, 2025
@lalinsky
lalinsky deleted the refactor/awaitable-anytask-split branch October 1, 2025 10:47
@coderabbitai coderabbitai Bot mentioned this pull request Dec 7, 2025
2 tasks done
lalinsky added a commit that referenced this pull request Jan 6, 2026
* 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]>
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