Skip to content

Refactor coroutine result handling with FutureResult - #14

Merged
lalinsky merged 6 commits into
mainfrom
future-result-refactor
Oct 1, 2025
Merged

lalinsky merged 6 commits into
mainfrom
future-result-refactor

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 1, 2025 •

Copy link
Copy Markdown
Owner

Changes:

  • Add FutureResult(T): thread-safe result container with atomic state

    • Uses CAS to ensure results are set exactly once
    • get() returns ?T based on atomic state check
  • Update Coroutine:

    • Store result_ptr: ?*anyopaque instead of AnyCoroutineResult
    • init() now takes comptime Result: type and *FutureResult(Result)
    • Wrapper calls FutureResult.set() with function result
    • Remove CoroutineData.result field
  • Refactor Task(T):

    • Now contains any_task, future_result, and runtime pointer
    • Simplified API: join() waits and returns result
    • deinit() uses runtime.releaseTask() with ref counting
  • Update AnyTask:

    • Add destroy_fn pointer for type-erased destruction
    • Runtime uses @fieldParentPtr to get typed Task from AnyTask
  • Runtime.spawn() now returns *Task(T) directly

All tests pass

Summary by CodeRabbit

  • New Features

    • Async results now use a dedicated FutureResult with single-writer semantics and non-blocking retrieval.
  • Refactor

    • Task/coroutine lifecycle and join/result paths simplified to use FutureResult; spawn now returns heap-backed task handles with improved destroy/release flow and safer ownership.
  • Chores

    • Examples updated to use pointer-based task handles and adjusted teardown for spawned tasks.

Changes:
- Add FutureResult(T): thread-safe result container with atomic state
  - Uses CAS to ensure results are set exactly once
  - get() returns ?T based on atomic state check

- Update Coroutine:
  - Store result_ptr: ?*anyopaque instead of AnyCoroutineResult
  - init() now takes comptime Result: type and *FutureResult(Result)
  - Wrapper calls FutureResult.set() with function result
  - Remove CoroutineData.result field

- Refactor Task(T):
  - Now contains any_task, future_result, and runtime pointer
  - Simplified API: join() waits and returns result
  - deinit() uses runtime.releaseTask() with ref counting

- Update AnyTask:
  - Add destroy_fn pointer for type-erased destruction
  - Runtime uses @fieldParentPtr to get typed Task from AnyTask

- Runtime.spawn() now returns *Task(T) directly

All tests pass
@coderabbitai

coderabbitai Bot commented Oct 1, 2025 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@lalinsky has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 6 minutes and 47 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 1e326f1 and 90d94a1.

📒 Files selected for processing (6)
  • examples/mutex_demo.zig (1 hunks)
  • examples/producer_consumer.zig (1 hunks)
  • examples/sleep.zig (1 hunks)
  • examples/udp_echo.zig (1 hunks)
  • src/runtime.zig (7 hunks)
  • src/zio.zig (1 hunks)

Walkthrough

Coroutines now write results into external FutureResult storage; internal AnyCoroutineResult and CoroutineResult helpers were removed. Runtime and Task types embed FutureResult, spawn returns a pointer to Task, and task lifecycle uses reference-counted release with a destroy callback.

Changes

Cohort / File(s) Summary
Coroutine result indirection
src/coroutines.zig
Replace internal AnyCoroutineResult with result_ptr: ?*anyopaque; init now takes comptime Result and result_ptr: *FutureResult(Result); coroutine wrapper writes result into provided FutureResult instead of internal union; removed getResult and related helpers.
FutureResult implementation
src/future_result.zig
FutureResult(comptime T: type) adds State (not_set, setting, set) and result: T; set(value: T) uses CAS to transition not_set -> setting -> set with proper memory ordering; get() ?T uses acquire semantics. Public signatures unchanged.
Runtime / Task lifecycle and API
src/runtime.zig
Task(T) now contains any_task: AnyTask and future_result: FutureResult(T); AnyTask gains destroy_fn; spawn now returns *Task(T); join/result use FutureResult.get(); runtime stores &task.any_task in maps/queues; added releaseTask to manage ref-counted destruction and invoke destroy_fn.
Examples — task handle types
examples/mutex_demo.zig, examples/producer_consumer.zig
Task arrays changed from value types to pointer types ([N]*zio.Task(void)); spawn assignments updated to store returned pointers; spawn counters added and defer teardown loops adjusted to deinit only populated elements.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User
  participant R as Runtime
  participant T as Task(T)
  participant A as AnyTask
  participant C as Coroutine
  participant F as FutureResult(T)

  U->>R: spawn(func, args, options)
  R->>T: allocate Task(T) { any_task, future_result = F }
  R->>A: init AnyTask (destroy_fn, coro)
  R->>C: init coro with Result=T and result_ptr=&F
  R->>R: enqueue &A into ready_queue
  R-->>U: return *Task(T)

  Note over C,F: coroutine stores result externally via FutureResult
  A->>C: run()
  C->>F: set(value)   %% CAS not_set->setting->set

  U->>T: join()
  T->>F: get()
  alt result not set
    T->>R: wait(A.id)
    R-->>T: signaled
    T->>F: get()
  end
  T-->>U: value
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I nibble code carrots, hop through the queue,
A FutureResult carrot — set once, not two.
Spawn me a task, I guard what you write,
Join when it’s ready, I’ll send you the bite.
Soft whisker of cleanup, a tidy goodbye — 🥕🐇

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 core change of the pull request by indicating that coroutine result handling has been refactored to use the new FutureResult mechanism, which aligns directly with the main API and implementation updates described in the diff.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3387be9 and f6cffa8.

📒 Files selected for processing (3)
  • src/coroutines.zig (3 hunks)
  • src/future_result.zig (1 hunks)
  • src/runtime.zig (5 hunks)

Comment thread src/future_result.zig Resolved
Comment thread src/runtime.zig Resolved
- Fix race condition in FutureResult.set() by using three-state
  (not_set -> setting -> set) with proper release/acquire ordering
- Remove unused AnyCoroutineResult and CoroutineResult(T) types
- Remove dead Coroutine.getResult() and Runtime.getResult() methods
Replace direct allocator.destroy(task) calls with releaseTask() in
Runtime.deinit and cleanup_queue processing to ensure proper ref
counting and use of task-specific destroy_fn, preventing memory
corruption from freeing wrong-sized allocations.
Change task arrays from Task(T) to *Task(T) to match the new spawn()
return type, and update defer loops to iterate over pointers directly.

@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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e69a37f and f6b650a.

📒 Files selected for processing (2)
  • examples/mutex_demo.zig (1 hunks)
  • examples/producer_consumer.zig (1 hunks)
🔇 Additional comments (4)
examples/producer_consumer.zig (3)

93-94: LGTM! Type declarations updated correctly.

The arrays now hold task pointers, aligning with the new Runtime.spawn() API that returns *Task(T).


96-99: Task spawning integrates correctly with pointer return type.

The assignments correctly store the *Task(void) pointers returned by runtime.spawn().


101-104: LGTM! Task teardown properly handles pointer-based tasks.

The defer block correctly deinitializes each task pointer, ensuring proper cleanup with the new reference-counted lifecycle.

examples/mutex_demo.zig (1)

36-36: LGTM! Array type updated to match pointer-based Task API.

The change from value-based to pointer-based task storage correctly aligns with the refactored Runtime.spawn() API that now returns *Task(T).

Comment thread examples/mutex_demo.zig Resolved
Track task_count/producer_count/consumer_count and only deinit the
slice of tasks that were actually initialized, preventing deinit on
uninitialized entries if spawn() fails partway through the loop.
Add JoinHandle(T) wrapper type with union(enum) { coro: *Task(T) }
to abstract task implementation details and prepare for future
spawnBlocking() support. Task methods are now private, with public
API exposed through JoinHandle. Update all examples to use the new
JoinHandle type.
@lalinsky
lalinsky merged commit 13f78f4 into main Oct 1, 2025
@lalinsky
lalinsky deleted the future-result-refactor branch October 1, 2025 10:47
lalinsky added a commit that referenced this pull request Nov 18, 2025
4bb1a60 Fix stack unwinding on aarch64 and riscv64 (#18)
ae64534 Update CI to use Zig master
cf32ccd Update for Zig 0.16 compatibility
c2f6ee8 Add a test for capturing stack trace (#17)
3d4c6de Test using DebugAllocator in coroutine (#14)
6536658 Fix the test
b6eec4f Build tests in release mode
REVERT: eab0a7b Merge remote-tracking branch 'origin/main' into zig-0.16
REVERT: 7579996 Expose StackPoolConfig
REVERT: 7fa7b4f Update CI to use Zig master
REVERT: cbabd36 Update for Zig 0.16 compatibility

git-subtree-dir: src/lib/coro
git-subtree-split: 4bb1a60186952636e6d3e409d62d9e8cf50b1560
lalinsky added a commit that referenced this pull request Jan 6, 2026
Modified backend tick() functions to return a boolean indicating whether
the wait timed out. This allows the event loop to only re-check timers
when we actually timed out, avoiding unnecessary clock_gettime() syscalls
and timer heap iterations when the loop was woken by I/O events.

Changes:
- poll.zig: Return true when poll() returns 0 (timeout)
- epoll.zig: Return true when epoll_wait() returns 0 (timeout)
- kqueue.zig: Return true when kevent() returns 0 (timeout)
- loop.zig: Only call checkTimers() again if backend timed out

This optimization reduces overhead on every tick that processes I/O events.
lalinsky added a commit that referenced this pull request Jan 6, 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