---
title: "Execution"
description: "Invocation entry, continuation scheduling, task trees, and cancellation."
---

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

# Execution

> **Written against the retired host**
>
> This page was written against `atoll-runtime-wasm`, and that host is **gone** —
> it is on the workspace `exclude` list and no longer builds. What runs is
> `crates/atoll-runtime`: one wasmtime `Store` per reactor, with host bodies as
> ordinary `async fn`s reached through the generated imports in `atoll-hosts`.
>
> The **surface** below is current: it is what `stdlib/` declares and what a
> program can name. Statements about *how the host answers* have not all been
> re-measured against the shipping reactor, so read those as the contract a host
> owes rather than as a description of what it does today.

Atoll lowers suspendable code into continuation-passing form. A generated
scheduler, driven by the host trampoline, advances ready work until the root
task finishes, an asynchronous operation must be polled, or execution yields
cooperatively.

The result is stackful source semantics over explicit arena-resident frames and
task control blocks.

## Invocation path

```text
route invocation
  → select Unit instance
  → copy payload into its arena
  → reset root TCB
  → call method entry
  → scan and dispatch ready continuations
  → poll host I/O when no task is ready
  → complete, suspend, yield, or terminate
```

The root TCB and persistent arena belong to the Unit instance. Continuation
frames allocated after the recorded frame-region boundary belong to the current
invocation and are released on ordinary completion.

## Continuations

A continuation is identified by a compiled function ID and an arena-relative
frame offset. The frame stores:

- its caller continuation;
- a packed program counter;
- a result tag and result value;
- its parent continuation;
- a call-link state used during stack reconstruction and completion.

Function IDs are dense within one build. They are not portable symbols and
cannot be assumed stable after redeploy.

See [ABI](https://docs.atoll.workreef.dev/runtime/abi/) for the exact frame layout.

## Task tree

Every invocation starts with a root task control block. Spawned tasks become
children in an arena-resident tree:

```text
root TCB
├─ child TCB
│  └─ grandchild TCB
└─ child TCB
```

The tree carries completion, cancellation, detach, frame, and waiter state. The
trampoline scans it root-first in depth-first order, skips cancelled subtrees,
and dispatches ready work.

A TCB offset can be reused after deallocation. Debug identity therefore pairs
the offset with its `debug_stamp`; the offset alone is vulnerable to an ABA
mistake.

## Ready work

The scheduler distinguishes several queues:

- ready resume nodes continue a suspended frame with a tagged result;
- ready loop nodes re-enter loop or yield continuations;
- awaiter chains wake tasks waiting on child completion or selection;
- stream control blocks coordinate consumer and producer waiters.

Nodes live in the same arena as the frames they reference, so relocation
preserves their relationships. The host keeps only typed offsets and rebuilds
absolute addresses from the current arena base.

## Trampoline

The host trampoline repeatedly:

1. activates the Unit instance's link group and arena;
2. asks generated scheduling code for the next ready continuation;
3. resolves its build-local function ID through the group's cached function
   table;
4. calls the generated resume or loop function;
5. services growth, collection, cancellation, debug, and preemption
   safepoints;
6. polls exact I/O slots when no generated task is immediately ready.

There is no operating-system thread per Atoll task. Tasks interleave
cooperatively on their Store reactor, while different Stores can run in
parallel.

## Suspension

A suspendable host call creates an I/O slot associated with the Unit instance
and records a resume target. If the operation is pending, generated code returns
to the trampoline. The Store reactor later polls the future.

Completion creates a ready-resume node containing:

```text
(tcb, resume_function, frame)
```

The next scheduler pass dispatches that continuation with the operation's
result tag and value. Exact-slot wakers notify only the relevant operation; the
runtime does not spawn one Tokio task for every I/O call.

See [Host I/O](https://docs.atoll.workreef.dev/runtime/host-io/) for buffer and resource lifetimes.

## Streams

A stream control block holds queue metadata plus the **heads** of its consumer
and producer waiter chains — one word each, at offsets 4 and 28, which
`task.Stream.new` zeroes. The waiter records themselves are host-side: nothing about
a wait is allocated in the guest. The head is in the block because it is the
only way to get from *a stream* to *its waiters* without looking at anybody
else's.

A `select` handle carries its kind in the **top four bits**: a task, a stream,
or a deadline. The low bit was tried and is not a kind — an odd number is not a
tag, and half of all task ids are odd, so a stream handle and a task handle were
drawn from one space and the scheduler had no way to ask which it had.

Backpressure is represented in the task graph: a consumer suspends when no item
is available, and a producer can suspend when capacity is exhausted. Closing a
stream records closure and wakes waiters through scheduler nodes.

## Cancellation

Cancellation is hierarchical. Marking a TCB cancelled causes traversal to skip
that task's subtree, and pending operations associated with cancelled work are
dropped or reaped according to their host contract.

Cancellation returns the `CANCELLED` result tag at a generated boundary. A
task parked when it is cancelled is resumed with that tag at once. A task
running when it is cancelled — by its own code, or while preempted or
stopped — has the instance context's `park` word set, and its next suspending
`@host` call runs its body and then resumes on its cancel edge; see
[Cancellation](https://docs.atoll.workreef.dev/language/concurrency/cancellation/). It does not roll back
arbitrary external effects that completed before the cancellation was
observed.

Termination is stronger than cancellation. A trap, forced stop, or interrupted
ownership update can make the instance untrustworthy. The runtime poisons that
instance and evicts its arena instead of attempting normal continuation.

## Completion

The root task's completion determines the invocation result. Detached tasks are
not allowed to keep the caller waiting forever.

After the root completes, the trampoline drains work that is already ready for
detached tasks, with a current bound of 4,096 steps. It does not wait for new
detached I/O after root completion. Long-lived background responsibility should
belong to a Unit or explicit runtime service, not an invocation-scoped detached
task.

## Preemption

Preemption is cooperative. The compiler places poll sites in generated code,
and a poll that finds the preempt word set returns control to the scheduler so
another invocation can make progress. Preemption preserves the Unit instance
and continuation state.

Time is sliced by default. `atoll run`, `atoll test` and every reactor an
embedder builds stop a task that has run for 1 ms while another task can run,
at its next poll site, and the other task runs: a loop that waits on another
task's write ends. A ticker thread sets the preempt word when the quantum
expires. Nothing else is compiled in for it: a run with a quantum runs the
same machine code as a run without one, and the deterministic every-poll mode
needs no flag.

`ATOLL_PREEMPT_QUANTUM_US` sets another quantum in microseconds, and `0`
turns slicing off; an embedder arms another with `Reactor::preempt_quantum`
or turns it off with `Reactor::preempt_off`. A run being recorded or replayed
is not sliced unless the variable asks: a stop made by the clock is not one a
replay can make again.

The ticker counts a quantum only while another task can run: one ready, one
stopped at a poll earlier, one asleep whose deadline has passed, or one whose
host call has answered on another thread. While a host call is parked it also
stops the running task every four quanta, so that a call answered by the
runtime's own I/O, which is looked at only between tasks, is seen. A task with
nobody else to run is not stopped, and the thread is not started until a second task becomes ready,
so a quantum costs such a run nothing. A policy that wants its stops anyway,
one that budgets the running task's own time, says so with
`PreemptPolicy::stops_when_alone`.

Termination uses a separate control path and can poison the instance. Code and
operators must not treat “yielded” and “terminated” as equivalent events.

### Without poll sites

`--no-preempt` on `atoll build`, `run`, `test` or `bench`, or
`[build] preempt = false` in the manifest, compiles the program with no poll
sites at all. A task then switches only at its own suspending calls, and the
rest follows from there being nowhere else to stop:

- A loop that makes no suspending call cannot be interrupted, by the quantum
  or anything else, until it ends.
- A running task's cancel still lands at its next suspending call, as it does
  for a task stopped mid-computation in a polled build. A deadline is seen
  there too.
- Cycles are collected between tasks, so a long task that never suspends
  collects none until it suspends or ends.
- `intrinsics.switch_soon()` arms a word nothing reads, and a map's growth
  is never interrupted, so a task never waits on another's.

The runtime starts no ticker for such a program. A stop asked of it —
`ATOLL_PREEMPT_QUANTUM_US` above `0`, `Reactor::preempt_quantum`,
`Reactor::preempt_every_poll` — is refused when the run starts, naming what
asked, rather than promised and never kept. `--debug` and a trace are refused
with it, because a debug build stops at the poll sites it leaves out.

## Debug stops

Debug-instrumented code adds source safepoints. An armed breakpoint or step can
suspend the invocation's coroutine, capture its task and continuation stack,
and shelve it in the Store. The reactor remains able to run unrelated
instances, but the stopped Unit instance stays busy and cannot be reused.

See [Debugger](https://docs.atoll.workreef.dev/runtime/debugger/) for stepping and concurrency rules.

## Result tags

The frozen result-tag values are:

| Tag | Meaning |
|---:|---|
| `0` | `OK` |
| `1` | `ERR` |
| `2` | `CANCELLED` |
| `3` | `TIMEOUT` |
| `4` | `ERR_FLAT` |

The associated value lane is interpreted by the called operation and generated
type metadata.

## Invariants

- generated code mutates one Unit instance on one Store reactor;
- every suspended continuation has a live frame and TCB root;
- all scheduler links are arena-relative offsets;
- cancelled subtrees are not dispatched;
- root completion bounds post-root detached work;
- cooperative yield preserves state, while forced termination may poison it;
- an invocation result does not imply rollback of completed external effects.

Source: https://docs.atoll.workreef.dev/runtime/execution/index.mdx
