Async Functions -- Internals
This page covers how async fn and await work under the hood: the state machine lowering, suspension mechanics, and runtime interaction.
The Async State Machine
When you write an async fn, the Vex compiler lowers it into a stackless coroutine -- a state machine that can suspend and resume. Potential suspension points determine the saved state; an immediately ready await can continue inline.
Source Code
async fn fetchAndProcess(url: string): Result<Data, Error> {
let response = await http.get(url)?
let parsed = await parse(response)?
return Ok(parsed)
}What the Compiler Does
The compiler:
- Identifies all
awaitpoints in the function body. - Partitions the code into basic blocks between
awaitpoints. - Generates a state machine that saves/restores live variables at each boundary.
- Generates a resume function that jumps to the correct state and continues execution.
Conceptually (not actual generated code):
// The compiler creates:
// - A struct holding all live variables across await points
// - A state enum tracking which await point is next
// - A resume function with a jump table to each stateSuspension Mechanics
What Happens at await
let result = await someAsyncFn()If the awaited operation is not ready:
- The current function's state (live variables, program counter) is saved.
- Control returns to the runtime scheduler.
- The runtime polls the awaited operation.
- When the operation completes, the runtime re-queues the task.
- On resume, the state machine restores live variables and continues from the next instruction.
Creating a Future is not awaiting it
An async { ... } expression captures its inputs and constructs a Future. Its body does not run at that point, and constructing it does not suspend the enclosing function. Suspension begins only when the Future is awaited or scheduled:
let pending = async {
return await loadRecord(id)
}
// Construction above did not run loadRecord or yield this task.
let record = await pendingThe Future owns or borrows its captures according to the normal ownership rules, so those inputs remain live for as long as the Future may use them. At await, the compiler transports the exact Future value through the suspension boundary and preserves any reference provenance carried by its result. This prevents an awaited view or reference from outliving the storage that produced it.
Suspension Safety
Borrow safety depends on origin, lifetime, mutability, and owner storage. A value kept across await must remain valid when the coroutine resumes. Neither &T nor &T! can be classified solely by its spelling.
| Case | Ownership obligation |
|---|---|
| Mutable reference to a local owner in an async frame | The owner and reference must remain valid in the frame; no conflicting access may occur while the mutable borrow is live. |
| Reference returned from an awaited call | The reference cannot escape the lifetime of the owner that backs it. Awaiting does not extend that owner's lifetime. |
| Reference backed by a caller-owned parameter | The caller must retain the owner for the entire borrow, including suspension and use of the result. |
| Detached task capture | The captured owner or reference must outlive every use by the independently scheduled task. |
The following function updates a frame-local record through a mutable reference and returns an owned integer result:
struct Cell { value: i32 }
async fn update(): i32 {
let! cell = Cell { value: 41 };
let reference = &cell!;
await sleep(1);
reference.value = reference.value + 1;
return reference.value;
}
fn main(): i32 {
let out: Channel<i32> = Channel.new(1);
go { out.send(await update()); };
return match out.recv() {
Some(42) => { $println("mutable frame: PASS"); 0 },
_ => 1,
};
}Expected output is mutable frame: PASS, with exit status 0. The go block communicates through a channel, and the parent waits for its result. Whether a particular await actually suspends depends on readiness; the owner must be valid on both the immediate and suspended paths.
The following is an intentionally invalid lifetime example: local belongs to bad, so returning a reference to it would leave a dangling reference once bad finishes. Passing that reference through await does not make it valid:
async fn borrow(input: &i32): &i32 { return input; }
async fn bad(): &i32 {
let local = 42;
return await borrow(&local);
}
fn main(): i32 { return 0; }SuspendSafe Contract
Suspension analysis uses compiler ownership and storage information. A type or marker name alone is not proof that a particular reference, view, or detached capture remains valid. Check the exact compiler and target; do not use pinning to bypass a lifetime or exclusivity error.
Pin and Async
An async frame can require address stability for values or references retained across a suspension. Pin is an address-stability mechanism, not a guarantee that arbitrary self-references are accepted or live long enough. For the tested examples and current limits, see Pin.
Runtime Integration
How the Scheduler Runs Async Tasks
User code: async fn myTask() { ... }
|
v
Compiler: State machine struct + resume function
|
v
Runtime: Task pushed to worker's local deque
Worker picks up task
Calls resume function
|
+-------+-------+
| |
Completes Hits await
| |
Task done Save state
Register with I/O poller
Yield to scheduler
|
I/O completes
|
Re-queue task on worker
|
Resume from saved stateKey Runtime Functions
The generated state machine cooperates with VexArch at each suspending await boundary. A ready await may continue inline; suspension saves state and hands the task back to the scheduler. The exact ABI is compiler/runtime-internal:
| Concept | Purpose |
|---|---|
| Task spawn | Push a new task to the scheduler |
| Task yield | Suspend current task, return to scheduler |
| Task resume | Re-queue a suspended task |
| Timer wait | Register an exact deadline in the hierarchical timer wheel |
| Poller wait | Block on I/O events (kqueue/epoll/IOCP) |
The full scheduler tracks an exact earliest timer deadline even when timers are stored in coarse wheel buckets. Workers reject future-deadline scans before contending on the wheel lock, ignore stale clock snapshots, and preserve chronological expiration across the internal millisecond-counter wrap. These are runtime representation guarantees, not application-visible timer APIs.
Long waits are not limited by the wheel's compact 32-bit bucket key. Vex keeps the exact saturating i64 monotonic deadline inside the active task and schedules bounded modular chunks. Expiration, cascade, and long scheduler pauses re-arm the next chunk without resuming user code; only the exact final deadline wakes the coroutine. This requires no extra task bytes or per-wait allocation.
Implementation detail: See
lib/runtime/VexArch/src/async/for the runtime implementation. Its reservedextern "VEX"ABI is not application API.
Async Function Rules
Lifetime and ownership rules
Use the suspension safety table above for the tested examples. Do not generalize from either shared or mutable references alone. Keep owners alive, preserve exclusivity, and test the exact compiler, target, and operation. Avoid holding a lock across a suspension unless its locking protocol explicitly supports it. FFI export and recursive async support also need their own target-specific validation.
Implicit suspension points
await is the explicit suspension form. Potentially blocking channel syntax is also a suspension point when it appears in a coroutine: channel send, channel receive, and a select without a default arm split the generated state machine. A select with default is non-blocking and therefore does not suspend.
The same channel operations inside an ordinary synchronous function may block the current OS thread, but they do not manufacture a coroutine frame or a synthetic yield. Borrow checking follows this distinction rather than treating every channel operation as async.
Async with ? Operator
An awaited Result can use ? to propagate a compatible error type. This fragment assumes the awaited calls return AppError; it does not establish automatic conversion from unrelated error enums:
async fn processRequest(req: Request): Result<Response, AppError> {
let user = await auth.verify(req.token)? // propagates AppError
let data = await db.query(user.id)? // propagates AppError
let result = await compute(data)? // propagates AppError
return Ok(Response.new(result))
}Comparison: Vex vs Rust Async
| Concept | Rust | Vex |
|---|---|---|
await syntax | Postfix: expr.await | Prefix: await expr |
| State machine type | impl Future with poll() | Compiler-generated struct + resume fn |
| Waker mechanism | std::task::Waker | Runtime-internal, not exposed |
| Trait | Future trait | No trait -- compiler intrinsic |
| Executor | External (tokio, async-std) | Built-in M:N scheduler |
| Pin requirement | Manual for self-referential | Compiler-detected in supported cases; validate the exact build |
Performance Characteristics
| Metric | Approximate | Notes |
|---|---|---|
| State machine size | Sum of live vars across await points | Compiler optimizes dead stores |
| Runtime task cell | 64 bytes | One cache line; frame is separate |
Ready await | No OS context switch | Continues through generated state |
Suspended await | Provider and workload dependent | Saves state and resumes later |
Straight-line async graphs use a compiler-selected cooperative-local scheduler. That mode has no external wake source. If live tasks remain after its runnable FIFO becomes empty, Vex reports a deterministic cooperative deadlock instead of spinning during program finalization. Full async graphs are different: an empty runnable set may be waiting on channels, timers, or native I/O, so their scheduler uses provider-aware parking and cancellation rather than this local terminal check.
The full scheduler becomes visible only after its native poller, global queue, and timer wheel have all initialized. These resources form one construction transaction: a failure releases every completed prefix and publishes no partial scheduler. Likewise, cooperative-local state can promote only before any task, frame, queue entry, or scheduler work exists. Live local frames can contain allocator and coroutine-context pointers, so Vex rejects a late promotion instead of copying an unsafe ownership graph; capability selection must choose the full scheduler before task publication. Timer suspension verifies its provider before marking the task waiting, preventing an allocation failure from turning into an invisible permanent suspension.
Task publication follows the same fail-closed rule. If scheduler/task storage, an inline reservation token, or queue ownership is unavailable, Vex emits an allocation-free runtime diagnostic and terminates before publication. It never reports success after silently dropping a go task or leaves an active task count with no reachable queue entry.
Cooperative-local frames use a thread-local VexArch allocator rather than libc malloc/free. Small blocks are reused from aligned size classes backed by raw 64 KiB pages; large frames use page-rounded direct extents. Bounds are checked before extent tagging and rounding, and cleanup is idempotent for both pooled and direct storage. Linux uses the target mmap/syscall provider, macOS uses the system VM provider, and Windows uses VirtualAlloc; this does not add a libc allocator dependency to freestanding runtime storage.
Best Practices
- Keep async functions focused -- each
awaitpoint adds to the state machine. - Keep borrowed owners alive across suspension; clone only when independent ownership is needed.
- Don't hold locks across
await-- restructure to acquire-release around suspension. - Use
goto schedule independent work and define completion and shutdown explicitly. - Be explicit about error types --
Result<T, E>composes well with?. - Avoid deep async call stacks -- each level adds state.
Related Pages
- Concurrency Overview -- goroutines and M:N scheduler
- Async -- async/await basics
- Channels -- message passing between tasks
- Runtime Architecture -- VUMM, event loop, channel internals
- Operators Reference -- channel send/receive operators