---
title: "Tasks"
description: "Task[T] — the typed handle spawn returns, how await consumes it, and what you owe every handle you hold."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.atoll.workreef.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Tasks

> **This runs**
>
> `spawn`, `await`, `join` and `cancel` run end to end on the shipping pair:
> `crates/atoll-codegen` compiles them and `crates/atoll-runtime` schedules
> them. `crates/atoll/tests/every_awaited_task_answers_its_awaiter.rs` and
> `a_cancelled_task_answers_none.rs` drive the cases below and check the heap
> on every row.

`Task[T]` is the typed handle for a spawned computation that will produce `T`.
You get one from `spawn`, and you consume it with `.await()`. Neither needs an
import — `spawn` is syntax and the methods come with the handle — but the type
is the `task` module's, so a file that writes it out, as `t: task.Task[int]`
does here, says `import task`.

```atoll
import task

fn calculate_total(items []int) int {
    mut sum := 0
    for v in items {
        sum = sum + v
    }
    return sum
}

fn run() int {
    t: task.Task[int] = spawn { calculate_total([1, 2, 3, 4]) }
    return t.await().unwrap_or(0)
}
```

The handle carries the result *type* but not the result itself. The child owns
its own execution frame until it completes and the parent copies the value out.

## `await` answers `T?`, and `None` means cancelled

That is the only thing it means. A task that ran to its end always answers
`Some`, whatever it computed — including a `T` that is itself an `Option`.
`Some(None)` is a task that finished and produced nothing; `None` is a task
that never finished. They nest rather than collapsing, because they are
different facts.

```atoll
fn work() int { return 9 }

fn run() int {
    task := spawn { work() }
    match task.await() {
        Some(value) => return value
        None => return -1        // somebody cancelled it
    }
}
```

The reason is that a cancelled body **never returned**, so there is no `T` in
existence to give back. Every alternative invents one: the result slot holds
whatever the frame was built over, which for a `T` that owns a reference is a
handle nobody wrote; a zeroed `T` is drop-safe for scalars and handles and not
for a value enum whose zero tag is a real variant; and refusing at run time
turns "stop this and see what happened" into a crash.

If nothing in your program cancels, `None` never occurs and
`.unwrap_or(fallback)` is the honest way to say so.

## The whole surface

`Task[T]` has four methods. That is the entire API.

| Method | Result | Effect it contributes | Purpose |
| --- | --- | --- | --- |
| `await()` | `T?` | `Suspend` | Join, take the result, reap the frame |
| `join()` | `bool` | `Suspend` | Wait until it has stopped; `false` if cancelled |
| `cancel()` | `void` | `Cancel` | Request cooperative cancellation |
| `raw_handle()` | `u64` | none | Scheduler token for runtime integration |

`join` is the wait without the value — for when the question is *has it
stopped* rather than *what did it produce*. `t.cancel()` followed by
`t.join()` is the "stop it, and do not carry on until it has actually
stopped" pattern, and it costs no result delivery.

```atoll
fn work() int { return 7 }

fn stop_and_wait() bool {
    task := spawn { work() }
    task.cancel()
    return task.join()       // false: it was cancelled
}
```

```atoll
fn work() int { return 7 }

fn inspect() u64 {
    task := spawn { work() }
    handle := task.raw_handle()
    task.cancel()
    return handle
}
```

There is no `is_complete` and no multi-await today. There *is* `detach()` —
see [Ownership](#ownership) below, where it is the opt-out from cancel-on-drop.

A **timeout** there is: `t.with_timeout(d)` answers `time`'s `Timed[T]` —
`Ready(v)`, `Over` for a task that was cancelled, `TimedOut` for one still
running. It bounds the wait and leaves the task alone, so giving up on the work
as well as on waiting for it is a `cancel` you write yourself. The general form
is a `time.after(d)` arm in a [`select`](https://docs.atoll.workreef.dev/language/concurrency/select/#timeouts),
which is what `with_timeout` is written over.

## Awaiting

`await` is a method, not a keyword, and it does three things at once:

1. it may suspend the caller while the child is still running;
2. it returns `Some` of the child's `T`, or `None` if the child was cancelled;
3. it reaps the completed task's frame and control block.

```atoll
struct Report {
    rows  int
    label string
}

fn build_report(rows int) Report {
    return Report { rows: rows, label: "monthly" }
}

fn summarize() string {
    task := spawn { build_report(120) }
    report := task.await().unwrap_or(Report { rows: 0, label: "cancelled" })
    return "${report.label}: ${report.rows} rows"
}
```

`T` can be any type. A wide result — a struct, tuple, list, or string — is copied
out of the child's frame before that frame is reclaimed, but the contract at the
source level is identical to returning an `int`. The `Option` around it is the
same one whatever the width: `Some` for a body that returned, `None` for one
that was cancelled and therefore never built a `T` at all.

Treat a task as **single-consumer**. Do not await it twice, do not put the same
handle in two `select` arms, and do not use it after a selection consumed it. The
compiler does not currently reject a double `await`, so this is a discipline you
keep, not one it keeps for you.

If the child has already finished, `await()` takes a synchronous fast path and
returns without yielding. The static row still says `Suspend`, because the caller
cannot know which case it is in.

## Completion order

Joining in source order does not serialize the work, as long as every task was
started first.

```atoll
fn fetch_left() int { println("left") return 1 }
fn fetch_right() int { println("right") return 2 }

fn overlapped() int {
    left := spawn { fetch_left() }
    right := spawn { fetch_right() }

    left_value := left.await().unwrap_or(0)
    right_value := right.await().unwrap_or(0)
    return left_value + right_value
}
```

Both children are eligible to run before the first join completes. The joins only
choose the order in which the parent *collects*. Nothing here cancels, so neither
`await` can answer `None` and `.unwrap_or(0)` says exactly that.

If the parent only needs the work to be *over* — a shutdown barrier, say — use
`join()` instead and skip the result delivery entirely:

```atoll
fn fetch_left() int { println("left") return 1 }
fn fetch_right() int { println("right") return 2 }

fn drain() bool {
    left := spawn { fetch_left() }
    right := spawn { fetch_right() }

    left_done := left.join()
    right_done := right.join()
    return left_done && right_done
}
```

Contrast that with joining each task at its spawn site, which is strictly
sequential:

```atoll
fn fetch_left() int { println("left") return 1 }
fn fetch_right() int { println("right") return 2 }

fn serialized() int {
    left_value := (spawn { fetch_left() }).await().unwrap_or(0)
    right_value := (spawn { fetch_right() }).await().unwrap_or(0)
    return left_value + right_value
}
```

Same result, no overlap. A spawn awaited at once skips the scheduler's round
trip: the compiler runs its body as a call, on a task of its own that the
runtime starts on the caller's stack, for a few runtime calls rather than a
frame allocation, a queue turn and a join. The body still sees everything a spawned task
does: its own task identity (a host that keys state on the calling task, such
as an open SQL transaction, sees a different task), its own copy of the
locale, no deadline, and a cancel of the parent reaching it. The await still
waits for any task the body leaves running.

## Fallible children

`Task[T]` preserves whatever the body returns. A body of type
`Record ! LoadError` gives you `Task[Result[Record, LoadError]]`, so awaiting
hands back `Result[Record, LoadError]?` — two layers that answer two different
questions. The outer one is *did this task finish at all*; the inner one is *did
the body succeed*. Peel the outer, then match or `?` the inner as usual.

```atoll
error LoadError {
    NotFound { id: int }
    Corrupt
}

struct Record { id int, body string }

fn load(id int) Record ! LoadError {
    if id < 0 { error NotFound { id: id } }
    return Record { id: id, body: "payload" }
}

fn load_one(id int) Record ! LoadError {
    task := spawn { load(id) }
    match task.await() {
        Some(result) => return result?
        None => error Corrupt        // cancelled: it never produced a Result
    }
}

fn load_or_default(id int) Record {
    task := spawn { load(id) }
    match task.await() {
        Some(value) => {
            result: Result[Record, LoadError] = value
            return result catch {
                NotFound { id: _ } => return Record { id: 0, body: "" }
                Corrupt => return Record { id: 0, body: "" }
            }
        }
        None => return Record { id: 0, body: "" }
    }
}
```

`load_one` has to decide what a cancellation *means* to its own contract, and
there is no way around that: `?` propagates an `Err`, and a cancelled task never
made one. Picking an error is a domain decision, which is the point.

The annotated local in `load_or_default` is not decoration either. `catch`
applied directly to `task.await()` is now a plain type mismatch — an `Option` is
not a `Result` — and even the unwrapped value does not currently let `catch` see
through the generic result type:

```atoll refused=ATOLL2002
error LoadError { NotFound, Corrupt }
struct Record { id int, body string }

fn load(id int) Record ! LoadError {
    if id < 0 { error NotFound }
    return Record { id: id, body: "payload" }
}

fn load_or_default(id int) Record {
    task := spawn { load(id) }
    return task.await() catch {
        NotFound => return Record { id: 0, body: "" }
        Corrupt => return Record { id: 0, body: "" }
    }
}
```

That reports `ATOLL2002: catch requires a Result[T, E] expression`. Bind the
awaited `Some` payload to a local with an explicit `Result[T, E]` annotation
first, or use `match`, `?`, or `unwrap_or` on it, all of which work directly:

```atoll
error LoadError { NotFound, Corrupt }
struct Record { id int, body string }

fn load(id int) Record ! LoadError {
    if id < 0 { error NotFound }
    return Record { id: id, body: "payload" }
}

fn fallback() Record {
    return Record { id: 0, body: "" }
}

fn by_unwrap(id int) Record {
    task := spawn { load(id) }
    match task.await() {
        Some(result) => return result.unwrap_or(fallback())
        None => return fallback()
    }
}

fn by_match(id int) int {
    task := spawn { load(id) }
    match task.await() {
        Some(result) => {
            match result {
                Ok(record) => return record.id
                Err(err) => return -1
            }
        }
        None => return -1
    }
}
```

Cancellation is *not* encoded as an automatic `Err` member of `T`. It is the
outer `None`, and it stays outside your error type: `Some(Err(e))` is a body that
ran and failed, `None` is a body that never ran to a verdict. Define an
application error for the second one only when task lifetime genuinely belongs in
that API's domain contract.

## Collections of handles

`Task[T]` is an ordinary value, so it can live in a list or a struct field. That
is how you fan out over a runtime-determined width.

```atoll
import task

fn score(candidate int) int {
    return candidate * candidate
}

fn best_of(candidates []int) int {
    mut running: []task.Task[int] = []
    for c in candidates {
        running.push(spawn { score(c) })
    }

    mut best := 0
    for Some(t) := running.pop() {
        value := t.await().unwrap_or(0)
        if value > best {
            best = value
        }
    }
    return best
}
```

`pop()` hands the tasks over last-first. A `for` awaits them in the order they
were started. It lends each task where it sits, so the list still holds them
afterwards, finished — dropping it then has nothing left to cancel:

```atoll
import task

fn score(candidate int) int {
    return candidate * candidate
}

fn scores(candidates []int) []int {
    mut running: []task.Task[int] = []
    for c in candidates {
        running.push(spawn { score(c) })
    }
    mut out: []int = []
    for t in running {
        out.push(t.await().unwrap_or(0))
    }
    return out
}
```

What a lent task cannot be is **given away**. Keeping it somewhere else — in
another list, a field, a `return` — takes a copy, and a `Task` owns its task:
two of it would both cancel it. So that is refused, at the give-away:

```atoll refused=ATOLL1089
import task

fn work() int {
    return 1
}

fn main() void {
    tasks := [spawn { work() }, spawn { work() }]
    mut kept: []task.Task[int] = []
    for t in tasks {
        kept.push(t)
    }
}
```

To hand each one over, take the list apart with `drain()`, which gives the loop
each task in order and leaves nothing behind:

```atoll
import task

fn work() int {
    return 1
}

fn main() void {
    tasks := [spawn { work() }, spawn { work() }]
    mut kept: []task.Task[int] = []
    for t in tasks.drain() {
        kept.push(t)
    }
    for t in kept {
        println("${t.await().unwrap_or(0)}")
    }
}
```

A list nothing else names — a literal, `for t in [a, b, c]`, or a call's result —
is taken apart that way without being asked, so its tasks are the loop's to
keep.

Pairing a handle with the identity it belongs to is often worth a small struct,
because `Task[T]` itself carries no label:

```atoll
import task

struct Shard {
    name string
    work task.Task[int]
}

fn count_rows(shard &string) int {
    return shard.len()
}

fn tally(names []string) string {
    mut shards: []Shard = []
    for name in names {
        shards.push(Shard { name: name.clone(), work: spawn { count_rows(name) } })
    }

    mut out := ""
    for Some(shard) := shards.pop() {
        out += "${shard.name}=${shard.work.await().unwrap_or(0)} "
    }
    return out
}
```

## Raw handles

`raw_handle()` exposes the scheduler's token as a `u64`. It exists for the
compiler's selectable protocol and for low-level runtime integration.

`u64` and not `usize`, and the difference is not cosmetic: a `usize` is the
type that *addresses* memory and is pointer-width, and a handle is not an
address — it is whatever the scheduler answers, so its width follows the ABI's
rather than the target's. At a 32-bit pointer width the two differ, and a
handle narrowed there would lose the tag that says which kind of source it
names.

```atoll
fn work() int { return 1 }

fn token() u64 {
    task := spawn { work() }
    handle := task.raw_handle()
    task.join()
    return handle
}
```

`join` rather than `await` here because the token is what this function wants and
the result is not — waiting is the whole obligation, so there is no value to
unwrap and nothing to discard.

A raw handle transfers neither the result type, nor the right to consume the
result, nor the reaping obligation. Do not persist it, serialize it, compare it
for business identity, or try to rebuild a `Task[T]` from it — it is an
arena-relative token whose encoding belongs to the runtime ABI. Keep the typed
handle instead.

## Ownership

Dropping the source-level handle **cancels the child**, and its subtree with
it. A handle is the right to the result, so losing the right and leaving the
work running is the combination that has no owner: nobody can join it, nobody
can stop it, and it holds whatever it captured until the run ends.

A handle can reach the task it names, or one of that task's descendants: sent
through a stream, or passed to a child as an argument. Dropping it there
**releases the handle and cancels nothing**. The task keeps running, in its
parent's tree as before, so a task never stops itself by holding its own
handle, or an ancestor's, and not using it. To stop itself, a task calls
`cancel()` on that handle, and unwinds at its next suspending call.

`detach()` is the opt-out, and it is the word for fire-and-forget:

```atoll
fn audit_log() void {
    println("audited")
}

fn fire_and_forget() void {
    task := spawn { audit_log() }
    task.detach()
}
```

A detached child is no longer reachable through a handle and no longer blocks
its parent's completion. Run teardown still cancels it like any other task —
detaching opts out of the *drop* edge, not out of the task tree.

Keep the handle when completion, errors, or targeted shutdown matter. Detach
only for deliberately best-effort work that handles its own failures.

Before a scope that started tasks exits, account for:

- every handle whose result is required;
- siblings still running after an earlier join failed;
- tasks that a `select` already consumed;
- cancellation requests whose cleanup is still in flight;
- fallible results that would otherwise go unobserved.

`cancel()` only *asks*, so the fourth of those is what `join()` is for: it
returns once the task is genuinely over, whether it finished or unwound, and it
does not oblige you to name a fallback value for work you are throwing away.

The runtime's task tree keeps detachment from becoming memory-unsafe. It cannot
choose your application's result, retry, or shutdown policy.

## A composed example

Fan out to a set of replicas, collect what succeeded, and count both the failures
and the cancellations rather than letting either vanish.

```atoll
import task

error ReplicaError {
    Unreachable { replica: int }
    Stale
}

struct Sample {
    replica int
    value   int
}

fn probe(replica int) Sample ! ReplicaError {
    if replica % 3 == 0 { error Unreachable { replica: replica } }
    println("probing ${replica}")
    return Sample { replica: replica, value: replica * 10 }
}

struct Survey {
    total     int
    ok        int
    failed    int
    cancelled int
}

fn survey(replicas int) Survey {
    mut probes: []task.Task[Result[Sample, ReplicaError]] = []
    for i in 0..replicas {
        probes.push(spawn { probe(i) })
    }

    mut total := 0
    mut ok := 0
    mut failed := 0
    mut cancelled := 0
    for Some(t) := probes.pop() {
        match t.await() {
            Some(result) => {
                match result {
                    Ok(sample) => {
                        total = total + sample.value
                        ok = ok + 1
                    }
                    Err(err) => failed = failed + 1
                }
            }
            None => cancelled = cancelled + 1
        }
    }
    return Survey { total: total, ok: ok, failed: failed, cancelled: cancelled }
}
```

Note `task.Task[Result[Sample, ReplicaError]]` written out in the annotation — that is
what `spawn { probe(i) }` produces, so `await` on it answers
`Result[Sample, ReplicaError]?` and the match has two layers. Both are how an
outcome gets observed instead of silently discarded, and they are counted apart
on purpose: a replica that reported a failure and a probe that was called off
before it could report anything are not the same operational fact.

Source: https://docs.atoll.workreef.dev/language/concurrency/tasks/index.mdx
