Skip to content

Explore a higher-level task group primitive #272

Open

Description

@tisonkun

Context

WaitGroup is a low-level lifetime barrier: cloned RAII handles represent outstanding work, and waiters observe when all handles are gone. It deliberately does not own tasks, collect results, propagate errors, or define cancellation and parent-child relationships.

Some use cases need a higher-level abstraction for a group of related asynchronous tasks. That should be designed as a separate primitive rather than changing WaitGroup. ForkJoin was an initial placeholder, not a proposed public name.

Ecosystem survey

  • Rust's tokio::task::JoinSet<T> owns runtime-spawned tasks, yields homogeneous results in completion order, and aborts remaining tasks when dropped. It is primarily controlled by one mutable collection owner.
  • Rust's tokio_util::task::TaskTracker is cloneable and supports registration without mutable access. Waiting requires the tracker to be both closed and empty; completed tasks release their storage immediately, results are not retained, and dropping the tracker does not abort tasks.
  • Go's errgroup.Group groups goroutines belonging to one operation, waits for them, returns the first non-nil error, can cancel a derived context on failure, and optionally limits concurrency.
  • Java's StructuredTaskScope makes one owner responsible for a lexical task scope. It forks subtasks, joins them under an explicit policy, prevents new forks after joining, and closes by cancelling and waiting for unfinished subtasks.
  • Swift's TaskGroup is a non-escaping structured scope for dynamically created child tasks. Children inherit parent context, results form an asynchronous sequence, and the scope cannot return while children remain.
  • Kotlin's coroutineScope establishes a parent-child task tree: the parent waits for children, while failure and cancellation propagate through the scope.

These examples separate into at least three families: result-owning task collections (JoinSet), shareable lifecycle trackers (TaskTracker), and structured lexical scopes (StructuredTaskScope, Swift TaskGroup, Kotlin coroutineScope). Go's errgroup combines lifecycle tracking with failure policy.

Questions to answer

  1. Is the target a runtime-agnostic future tracker, or may it spawn and therefore depend on a runtime?
  2. Is registration shareable with child tasks, restricted to one owner, or lexically scoped so handles cannot escape?
  3. Does joining only signal quiescence, return one result at a time, collect all results, or reduce them through a policy?
  4. How are task errors and panics represented, and should the first failure cancel siblings?
  5. What does dropping the owner do: detach, cancel, abort, or synchronously/asynchronously wait?
  6. Is there an explicit close transition that prevents new top-level work? Can running children register nested work after close?
  7. Is bounded concurrency part of this primitive or an orthogonal concern?
  8. Does the design require one join owner, or are multiple completion observers meaningful?

Naming

The name should follow the selected contract rather than lead it:

  • TaskGroup suggests structured child ownership and possibly result collection.
  • JoinSet suggests an owned collection with per-task results.
  • TaskTracker suggests shared lifecycle observation without task ownership.
  • TaskScope suggests lexical structure and non-escaping children.

No name or API is proposed yet. The next step is to identify concrete Asyncband use cases and choose which semantic family, if any, belongs in a runtime-agnostic synchronization crate.

Activity

  1. changed the title [-]Explore WaitGroup internals and a separate ForkJoin primitive[/-] [+]Explore a higher-level task group primitive[/+] on Sep 3, 2026
  2. Colerar commented on Sep 11, 2026

    @Colerar

    I just took a dive into this issue, and here are my thoughts. :D

    For this issue, I currently lean toward a runtime-agnostic TaskGroup, rather than a full lexical task scope.

    Why not a lexical task scope

    As in the Moro README - why do moro spawns only run concurrently, not parallel, under Rust’s current Future model, it is difficult for a completely safe, general-purpose API to provide all three of the following:

    • runtime independence;
    • child futures that borrow non-'static local data;
    • independently spawned child tasks that can run in parallel.

    There are two main approaches to implementing a lexical task scope.

    Have the scope poll child futures itself

    Pros:

    • runtime-agnostic
    • child task can borrow local data
    • child task cannot outlive the scope

    Cons:

    • only concurrency instead of parallelism
    • cannot be scheduled as independent tasks
    • closer to a future combinator than a conventional task group

    Spawn children onto an executor

    Pros:

    • independent tasks
    • parallelism
    • This better matches common task-group use cases.

    Cons:

    • child tasks usually needs to be 'static.
    • runtime-specified
    • semantics may differ between runtimes, or it's difficult to align them semantically.

    For these reasons, I do not currently favor making a lexical scope. A lexical scope API would still be possible but their use cases are limited.

    TaskGroup shape

    TaskGroup would not spawn tasks itself. Instead, it would wrap futures and let the caller choose the executor:

    let (group, registrar) = TaskGroup::new();
    
    executor.spawn(registrar.track(worker_a()));
    executor.spawn(registrar.track(worker_b()));
    
    group.close();
    group.wait().await;

    Pros

    • runtime-agnostic
    • Tasks can still run independently and in parallel.
    • Tracking is tied to the actual lifetime of the wrapped future.
    • A cloneable registrar can be used to register nested work.
    • close() distinguishes “currently empty” from “no more tasks will be added.”
    • It can compose with the cancellation primitive proposed in Define cooperative cancellation and its relation to shutdown #223.

    Cons

    • TaskGroup does not own the executor’s task handles.
    • cannot provide forced interruption.
    • only cooperative cancellation.
    • Panic representation remains undefined.
    • The registrar can escape, so this is not a strict lexical scope.

    Task results

    I do not think completion-only tracking and result-aware task groups need to be separate primitives. The same TaskGroup could support both:

    group.wait().await;      // Wait for completion and discard outputs.
    group.join_next().await; // Process one output in completion order.
    group.join().await;      // Collect all outputs.

    For completion-only use cases, tracked futures can simply return ().

    This means completion-only use cases may pay a small unnecessary result-delivery cost, but it keeps the API simpler and avoids substantial duplication. The implementation could be optimized later if benchmarks justify it.

    Result policies

    I favor an approach similar to futures-concurrency: TaskGroup provides completed outputs, while callers choose the desired policy.

    Operation Behavior
    join_next() Return one output in completion order and let the caller decide what to do next.
    wait() Wait for every task and discard the outputs.
    join() Wait for every task and collect all outputs.
    try_join() Let the first error determine the result and request cancellation of the remaining tasks.
    race() Let the first completed task determine the result and request cancellation of the remaining tasks.
    race_ok() Let the first successful task determine the result, continuing past failures.

    join_next() could be the foundational API, with the other operations built on top of it.

    Because TaskGroup does not own executor task handles, determining the final result early is not the same as the group having finished. To preserve structured-concurrency semantics, try_join() and race() should:

    determine the final result
    -> request cooperative cancellation
    -> wait for the remaining tracked tasks to exit
    -> return the result
    

    Cancellation

    Cancellation can remain the separate primitive proposed in #223, while TaskGroup composes with it at the API level:

    registrar.track(|context| async move {
        select! {
            result = work() => result,
            _ = context.cancelled() => cleanup().await,
        }
    });

    The responsibilities remain separate and orthogonal.

    Summary

    1. Is the target a runtime-agnostic future tracker, or may it spawn and therefore depend on a runtime?

    runtime-agnostic

    1. Is registration shareable with child tasks, restricted to one owner, or lexically scoped so handles cannot escape?

    Registration is provided through a cloneable registrar, allowing child tasks to register additional work. A single owner manages results, closing, and cancellation; no lexical non-escape guarantee is provided.

    1. Does joining only signal quiescence, return one result at a time, collect all results, or reduce them through a policy?

    The same TaskGroup can provide wait(), join_next(), and join(). join_next() should be the foundation, allowing callers to select or implement their own result policy.

    1. How are task errors and panics represented, and should the first failure cancel siblings?

    Application errors are represented by the future’s output type, such as TaskGroup<Result<T, E>>, and callers decide whether the first error cancels siblings. Because TaskGroup does not own executor task handles, precise panic information may still depend on the executor.

    1. What does dropping the owner do: detach, cancel, abort, or synchronously/asynchronously wait?

    Dropping the owner requests cooperative cancellation, but cannot abort tasks or wait asynchronously. Callers that require complete cleanup must explicitly call cancel() followed by wait().await.

    1. Is there an explicit close transition that prevents new top-level work? Can running children register nested work after close?

    An explicit close() transition is provided. To keep the first version simple, closing the group rejects all new registrations, including nested work initiated by running child tasks.

    1. Is bounded concurrency part of this primitive or an orthogonal concern?

    Bounded concurrency remains orthogonal and can be provided by Semaphore or another higher-level primitive.

    1. Does the design require one join owner, or are multiple completion observers meaningful?

    There is a single owner that consumes task results. If multiple completion-only observers prove useful, they can be added later through a separate completion watch.


    Feedback is very welcome! Going to sleep now, so I'll reply later. I’m planning to put together a PR this weekend.

  3. tisonkun commented on Sep 12, 2026

    @tisonkun
    MemberAuthor

    @Colerar Thanks for your feedback! Feel free to submit PR. I may find some time the next week to consider this issue or your upcoming PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions