Concurrency
Structured concurrency with the Task effect, cooperative cancellation, timeouts, retries, budgets, and deterministic scheduling in Sakura Lang.
To do several things at once, you start tasks inside a scope. A task is a piece of work that runs alongside others. A scope is a block that waits for every task started in it, so no task is ever left running behind your back.
fn both() -> (Int, Int) ! {Task} {
Task.scope(fn(s) {
let a = Task.spawn(s, fn() { 1 + 1 })
let b = Task.spawn(s, fn() { 2 + 2 })
(Task.join(a), Task.join(b))
})
}
test "both tasks finish before the scope returns" {
with Task.deterministic(1) { expect_eq(both(), (2, 4)) }
}Task.scopeopens a scope and passes it to the callback ass.Task.spawn(s, work)starts a task in that scope and returns a fiber, a handle to the running task.Task.join(fiber)waits for that task and returns its result.bothuses tasks, so its signature lists theTaskeffect. The test installsTask.deterministic(1), a scheduler that runs tasks in the same order every time.
No async/await
Sakura Lang has no async/await and no Async effect. Any function may pause while it waits, for a timer or a network reply, and nothing in your code can tell whether it did. Whether a call waits is decided by its handler: Clock.sleep waits under the real clock and returns at once under Clock.fixed.
So you never mark functions as async. You only use Task when you want work to run at the same time.
Scopes
A realistic example fetches two URLs at once:
import std/http.{Http, RateLimited}
import std/response.{HttpError, Response}
import std/url.{Url}
fn load_both(a: Url, b: Url) -> (Response, Response) ! {Http, Task, Fail<HttpError | RateLimited>} {
Task.scope(fn(s) {
let fa = Task.spawn(s, fn() { Http.get(a) })
let fb = Task.spawn(s, fn() { Http.get(b) })
(Task.join(fa), Task.join(fb))
})
}The tasks' effects (Http, and the failures HttpError | RateLimited) become part of load_both's signature. Tasks never outlive their scope, which gives three rules:
- Failure spreads. If a task fails or hits a defect (a bug that stops it), the scope cancels the other tasks, waits for them, and passes the first failure on. Other failures are attached as
suppressedin the outcome. - Defects are observed, not caught.
Task.scopesees a task's defect asOutcome.Defect(info).trycannot catch it. - Resources are released. A fiber is a resource: it is used at most once and belongs to its scope.
Running many at once
Task.all runs a list of functions and returns their results in order. Task.race returns the result of the first to finish. Task.par_map maps over a list in parallel:
import std/http.{Http, RateLimited}
import std/response.{HttpError, Response}
import std/url.{Url}
fn fetch_all(urls: List<Url>) -> List<Response> ! {Http, Task, Fail<HttpError | RateLimited>} {
Task.par_map(urls, fn(u) { Http.get(u) })
}Cancellation is cooperative
A cancelled task stops at its next effect operation or at Task.yield_now(). A loop of pure computation cannot be interrupted, so a long one should call Task.yield_now() now and then:
fn total_size(chunks: List<List<Int>>) -> Int ! {Task} {
var total = 0
for chunk in chunks {
Task.yield_now()
total = total + List.sum(chunk)
}
total
}Timers: setTimeout, setInterval and clearTimeout
There are no timer ids. A timer is a task, or a loop, in a scope:
| In JavaScript | In Sakura Lang |
|---|---|
setTimeout(work, d) | Task.spawn(s, fn() { Clock.sleep(d); work() }) |
queueMicrotask(work) | Task.spawn(s, work) |
clearTimeout, AbortController.abort | Task.cancel(f) |
setInterval(work, period) | every(period, body) from std/task |
clearInterval | body returns false, or Task.cancel of the task running the loop |
AbortSignal.aborted | Task.cancelled(s) |
performance.now(), console.time | Clock.monotonic_micros() |
import std/task.{every}
fn heartbeat() -> Unit ! {Clock, Console, Task} {
Task.scope(fn(s) {
let reminder = Task.spawn(s, fn() {
Clock.sleep(Duration.seconds(30))
Console.print("still working")
})
every(Duration.seconds(1), fn(skipped) {
if skipped > 0 { Console.print("{skipped} ticks skipped") }
Clock.monotonic().to_millis() < 10_000
})
Task.cancel(reminder)
})
}Task.cancel(f)runs the task's cleanup before it returns. The fiber is then used up: a laterTask.join(f)is defectD095. Cancelling a finished task does nothing else.everynever overlaps ticks. A tick that comes due whilebodyruns is skipped, and the next call receives how many were skipped.Task.cancelled(s)is true when a task insfailed, so the scope is cancelling the others.- Under
Clock.virtual()the ticks are reproducible, so a test can check whatheartbeatprints without waiting.
Channels
A channel is a queue that one task writes to and another reads from. std/channel works like MessageChannel inside one program:
import std/channel
import std/channel.{Receiver, Sender}
fn sum_of_squares(n: Int) -> Int ! {Task} {
channel.with_channel(4, fn(tx: Sender<Int>, rx: Receiver<Int>) {
let results = Task.all([
fn() {
for i in List.range(0, n) { let _sent = tx.send(i * i) }
tx.close()
0
},
fn() {
var total = 0
var more = true
while more {
match rx.recv() {
Some(x) => { total = total + x },
None => { more = false },
}
}
total
},
])
results[1].unwrap_or(0)
})
}with_channel(capacity, body)givesbodyaSenderand aReceiverfor a queue of at mostcapacityitems. Here the producer runs at most four items ahead of the consumer.sendwaits while the queue is full;try_sendfails withFullinstead.recvwaits while the queue is empty, and returnsNoneonce the channel is closed and drained.- Both ends are resources, so neither can leave the callback (
V6003). The channel closes when the callback returns. - If every task is waiting, such as a
recvthat nosendorclosewill answer, the program ends with defectD090instead of hanging. - Under
Task.deterministic(seed)the order is the same on every run and every backend.
Source.buffer(src, capacity, body) and Source.tee(src, max_lag, body) from std/stream are built on channels. The source their body receives, like the one decompress_source hands its body, is Done once that callback returns, so read it inside the callback.
No data races
Values are copies and closures capture copies (see Memory model). There is no shared mutable memory, so data races cannot happen. Tasks communicate through their results (join, all, race), through handler state, and through channels.
Child tasks inherit the handlers installed when they were spawned. A handler's var state is accessed one operation at a time, so two tasks using the same effect take turns.
Logical races with the outside world are still possible, such as two tasks reading and then writing the same database row. The type system does not rule those out.
Timeouts, retries, and budgets
All three are ordinary library functions or handlers, not syntax:
retry(policy, action)runsactionagain when it fails with an error the policy accepts, waiting longer each time.timeout(limit, action)cancelsactionif it takes longer thanlimit, then fails withTimeout { limit }.Budget.limits(limits)is a handler that caps tokens, cost and calls for the code inside it.
This function fetches two URLs at once, retries rate-limited requests, and gives up after five seconds:
import std/http.{Http, RateLimited, Matcher}
import std/response.{HttpError, Response}
import std/url.{Url}
import std/retry.{Policy, retry}
import std/task.{Timeout, timeout}
fn fetch_both(a: Url, b: Url) -> (String, String) ! {Http, Task, Clock, Random, Fail<HttpError | RateLimited | Timeout>} {
let policy: Policy<HttpError | RateLimited> = Policy { retry_on: fn(e) { match e { RateLimited { .. } => true, _ => false } },
max_attempts: 3, backoff: Duration.millis(200), jitter: true, deadline: None }
timeout(Duration.seconds(5), fn() {
Task.scope(fn(s) {
let fa = Task.spawn(s, fn() { retry(policy, fn() { Response.text(Http.get(a), 1_000_000).trust(@trust("display only")) }) })
let fb = Task.spawn(s, fn() { retry(policy, fn() { Response.text(Http.get(b), 1_000_000).trust(@trust("display only")) }) })
(Task.join(fa), Task.join(fb))
})
})
}Retry.
- Each attempt is a new call; a failed one is never resumed.
retry_onis a pure function over the action's error typeE, which is whyPolicytakesEas a parameter.retry.policy(retry_on, max_attempts)builds a policy with default backoff, or set the record fields yourself.- The first retry waits
backoff, each later wait doubles,jitterrandomizes the wait, anddeadlinebounds the total time. - When attempts run out, the last error propagates.
- The standard HTTP client refuses to retry non-idempotent methods without an idempotency key.
Timeout. timeout cancels the action's task at its next effect operation, waits for it to finish its cleanup, then fails with Timeout { limit }. std/task.Timeout is the only timeout error in the standard library; LlmError reuses it.
Budget. Budget is an effect with reserve and settle, and Llm and Http handlers use it when it is installed. Exceeding it fails with BudgetExceeded, whose kind is Tokens, Usd, Calls, Bytes, or Time. Child tasks inherit the budget and split it. A budget is installed as a handler with a Limits record:
This excerpt is from a larger main; it is not a standalone program.
let limits = Limits { tokens: Some(20_000), usd: Some(0.50), calls: None }
with Llm.anthropic(key, Model.of("claude-sonnet-5-5")), Budget.limits(limits) {
let t = extract_ticket(Untrusted.of("Login page 500s since 9am, blocking all customers"))
Console.print("{t.priority}: {t.title}")
}Determinism
Time, randomness and scheduling are all effects, so a test can replace all three and get the same run every time:
test "deterministic under virtual time" {
with Http.scripted([(Matcher.Any, Response.status(200, "x"))]), Clock.virtual(), Random.seeded(1), Task.deterministic(1) {
expect_eq(fetch_both(Url.from("https://a"), Url.from("https://b")), ("x", "x"))
}
}Task.deterministic(seed)makes the task order reproducible.Clock.virtual()advances only when told to, so sleeps and timeouts cost no real time.- Evaluation is strict and left to right, and
MapandSetiterate in insertion order on every backend.
See Testing for more.
Workers (experimental)
Experimental
std/worker and the @worker attribute are outside the 1.0 contract and may change in any release. Live workers and topics run on every target: as node:worker_threads threads on JavaScript and on WebAssembly under Node, and as OS threads with a second instance on native. Worker.inline() runs on every target too.
A worker is like new Worker in JavaScript without shared memory: a second copy of the program, running one function marked @worker, with its own memory and its own permissions.
import std/worker.{Grants, Inbox, Message, Outbox, Worker, WorkerError}
@worker
fn sizes(inbox: Inbox<Bytes>, outbox: Outbox<Int>) -> Unit ! {Worker} {
var more = true
while more {
match Worker.recv(inbox) {
Message(b) => {
let _sent = Worker.send(outbox, b.len())
},
_ => { more = false },
}
}
}
fn total(parts: List<Bytes>) -> Result<Int, WorkerError> ! {Worker} {
Worker.spawn(sizes, Grants.none(), fn(w) {
for p in parts { let _sent = Worker.send(w, p) }
var sum = 0
for _ in parts {
match Worker.recv(w) {
Message(n) => { sum = sum + n },
_ => {},
}
}
sum
})
}
test "a worker measures each part" {
with Task.deterministic(1), Worker.inline() {
expect_eq(total([Bytes.from_list([1, 2]), Bytes.from_list([3, 4, 5])]), Ok(5))
}
}Worker.spawn(entry, grants, body)starts the worker and givesbodya handle. Whenbodyreturns, the worker is cancelled.send(postMessage) andrecv(onmessage) carry messages that are encoded and decoded, so closures, handlers, resources andSecretcannot cross.recvreturnsMessage(v),Finishedonce the worker's function has returned and its messages are read, orFailed(WorkerError)when it ended on a defect.- Grants. A worker's permissions are its
Grants:Grants.none(), orGrants.of(table)with lists shaped like[permissions]. They must be a subset of the parent's permissions and must cover every effect the worker declares, orspawnreturnsErr(WorkerError(GrantExceeded))and nothing runs. A worker can spawn its own workers within its grants. - Effects. The worker's effects are part of
spawn's effects, so a parent that spawns a worker declaringHttpdeclaresHttptoo. - Limits. At most 16 workers are live in an instance (
Limit), and each direction holds 64 unreceived messages beforesendwaits. - Topics.
Worker.topic(name)is likeBroadcastChannel:subscribe(topic, capacity, body)givesbodya bounded queue of what is published from then on, in any instance of the process.publishnever waits; a subscriber in this instance whose queue is full misses the message, andpublishreturnsErr(Full). - Tests.
Worker.inline()runs the worker as a task in the same instance, through the same encoding, so the test above needs no thread. It refuses any grant exceptnone(), and the worker uses the test's own handlers.
Detached work
Every task belongs to a scope. There is no fire-and-forget spawn and no supervisor for long-running work. A capability, or a handler that captured one, may not flow into a Task.spawn closure whose scope outlives the with that produced it (V6002).
Runtime model
The JavaScript backend is single-threaded. A live host operation, such as Clock.sleep or Http.send, pauses the program until the host answers. The experimental native backend targets single-thread execution; worker threads and cross-thread reference counting are not a current guarantee.
Not in v0
- An
Asynceffect,async/await, or async-only functions. - Durable workflows. They are planned as a later official package, not part of the language.
- Actors.
spawnandactorare reserved keywords (Task.spawnis legal because a reserved word is accepted after.). - Detached or supervised tasks, and timer ids (
setTimeoutis a task, above). - Shared mutable state or locks in user code.
What the compiler checks
- Code that uses
Taskoperations declaresTaskin its effects (V3001otherwise). - Child tasks' effects flow into the parent's effects.
- A capability or capturing handler does not escape into a task that outlives its scope (
V6002). - A fiber does not outlive its scope.
- A channel's
SenderorReceiveris not returned fromwith_channel's callback or kept in handler state (V6003). Worker.spawntakes a non-generic function declared@worker(V1010), and a worker's message types haveSchema(V2032).
Reference
The Task effect
This is the declaration from std/task; it is not a standalone program.
// std/task
pub type Scope // external, scoped
pub type Fiber<T> // external, scoped, affine
pub effect Task {
fn scope<T, e>(body: fn(Scope) -> T ! e) -> T ! e
fn spawn<T, e>(s: Scope, body: fn() -> T ! e) -> Fiber<T> ! e
fn join<T>(f: Fiber<T>) -> T
fn all<T, e>(bodies: List<fn() -> T ! e>) -> List<T> ! e
fn race<T, e>(bodies: List<fn() -> T ! e>) -> T ! e
fn yield_now() -> Unit
fn cancel<T>(f: Fiber<T>) -> Unit
fn cancelled(s: Scope) -> Bool
}
pub fn host() -> Handler<Task>
pub fn deterministic(seed: Int) -> Handler<Task>
pub fn every<e>(period: Duration, body: fn(Int) -> Bool ! e) -> Unit ! {Clock, Task | e}
pub fn par_map<A, B, e>(xs: List<A>, f: fn(A) -> B ! e) -> List<B> ! {Task | e}Scope and Fiber<T> are external types: the host owns them and your code cannot construct them. The lowercase e carries the tasks' effects into the caller's effects.
Retry, timeout and budget signatures
These are declarations from std/retry, std/task and std/budget; they are not a standalone program.
// std/retry
type Policy<E> = { retry_on: fn(E) -> Bool, max_attempts: Int, backoff: Duration, jitter: Bool, deadline: Option<Duration> }
fn policy<E>(retry_on: fn(E) -> Bool, max_attempts: Int) -> Policy<E> requires max_attempts >= 1
fn retry<T, E, e>(p: Policy<E>, action: fn() -> T ! {Fail<E> | e}) -> T ! {Clock, Random, Fail<E> | e}
// std/task
error Timeout(limit: Duration)
fn timeout<T, e>(limit: Duration, action: fn() -> T ! e) -> T ! {Clock, Task, Fail<Timeout> | e}
// std/budget: a handler, not a wrapper function
type Limits = { tokens: Option<Int>, usd: Option<Float>, calls: Option<Int> } // None = unlimited
fn limits(l: Limits) -> Handler<Budget>Next
Embedding a library in Node: call Sakura Lang functions from a Node program.
Details for contributors: design §5.4–§5.6, §5.9, §8.1, §8.4, §8.7, §13.3, §15.7, §15.10, §16.14.
Last updated
Memory model
Value semantics, var rebinding, compiler-inserted reference counting with Perceus reuse, cycles through Graph, scope-bound resources, and backends in Sakura Lang.
Embedding a library in Node
Call a Sakura Lang library's public functions from a Node program, on the WebAssembly or the JavaScript build, with callEntry, the entry rule, permissions and the value mapping.