Effects
How Sakura Lang lists every side effect and every expected failure in a function's signature.
An effect is anything a function does besides return a value: print, read the clock, query a database, call the network, or fail. In Sakura Lang, a function lists its effects in its signature, after !, and the compiler checks the list.
fn greet(name: String) -> Unit ! {Console, Clock} {
let now = Clock.now()
Console.print("hello, {name}; it is {Instant.format_iso(now)}")
}
pub fn main() -> Unit ! {Console, Clock} { greet("Sakura Lang") }sakura run prints something like:
hello, Sakura Lang; it is 2026-10-22T13:09:10.309Z! {Console, Clock}saysgreetmay print and may read the clock, and nothing else.- The list in braces is the function's effect row.
maincallsgreet, somainmust listConsoleandClocktoo. Effects can't hide inside a helper.
So you can read a signature and know what a function can touch, without reading its body.
Order does not matter: a row is a set. main gets Console and Clock from the host's root handlers; a with handler removes the effects it handles from the row around it.
Pure functions
A function with no ! is pure: it only computes its result.
fn total(prices: List<Int>) -> Int {
List.fold(prices, 0, fn(acc, p) { acc + p })
}No ! always means "no effects". Pure does not mean "can't crash": overflow and broken contracts are defects, which stop the program either way.
Calling an effect
You perform an effect operation with Effect.op(args), like Console.print("hi") or Clock.now(). Calling a function performs all the effects in its row. Creating a lambda performs nothing; calling it performs its effects.
The row is an upper limit. A body may do less than its row says, never more.
When the signature is missing an effect
If a body performs an effect its signature does not list, sakura check stops with V3001:
type User = { id: String, name: String, seen: Instant }
effect Db {
fn get_user(id: String) -> Option<User>
}
pub fn load_user(id: String) -> Option<User> ! {Clock} {
let now = Clock.now()
let found = Db.get_user(id)
Option.map(found, fn(u) { User { ..u, seen: now } })
}error[V3001]: function `load_user` performs `Db`, which its signature does not allow (allowed: `{Clock}`)
┌─ src/main.sak:7:8
│
7 │ pub fn load_user(id: String) -> Option<User> ! {Clock} {
│ ^^^^^^^^^
8 │ let now = Clock.now()
9 │ let found = Db.get_user(id)
│ --------------- `Db.get_user` performs `Db` here
│
= expected: {Clock}
= found: {Clock, Db}
= help: Add `Db` to the signature
= help: Handle the effect locally with `with`
= see `sakura explain V3001`
1 errorThere are two honest fixes. If load_user really should use the database, add Db to its signature; a reviewer sees that change. If it should not, handle Db locally with a handler. The compiler never applies the first fix on its own, because it widens what the function may do. sakura check --json prints the same error as JSON for agents; see Diagnostics.
Declaring your own effects
An effect lists operations as signatures, with no bodies:
type Table = String
error DbUnavailable(reason: String)
effect Db {
fn exists(table: Table, key: String) -> Bool
fn insert(table: Table, row: Json) -> Unit ! {Fail<DbUnavailable>}
}The declaration only says what operations exist. What they do is decided by a handler, which the caller picks. The same code can run against SQLite in production and an in-memory table in a test.
Failure: Fail<E> and error unions
There are no exceptions. A function that can fail lists Fail<E> in its row. E is an error union: one or more error tags you declared with error.
type Email = String where String.contains(it, "@")
error EmailTaken(email: Email)
error Banned
type SignupError = EmailTaken | Banned // union alias: tags onlyfail EmailTaken { email } stops the function with that error.
Failures pass up automatically. If you call a function that may fail with A, your function may fail with A too, and it must say so. No operator is needed.
To recover, use try/catch. Each catch branch matches error tags. Tags you catch are removed from your row; the rest keep passing up:
error NotFound(id: String)
error Forbidden
error Unavailable(reason: String)
type UserError = NotFound | Forbidden
type User = { id: String, owner: String, name: String }
effect Users {
fn get(id: String) -> Option<User> ! {Fail<Unavailable>}
}
pub fn view_user(caller: String, id: String) -> User ! {Users, Log, Fail<UserError>} {
let user = try {
Users.get(id)
} catch {
Unavailable { reason } => {
Log.event(Level.Warn, "users backend unavailable", [("reason", Json.String(reason))])
None
}
}
match user {
None => fail NotFound { id },
Some(u) if u.owner != caller => fail Forbidden,
Some(u) => u,
}
}view_user catches the internal Unavailable error and turns it into a log line, so callers only see NotFound or Forbidden. Other ways to move between failures and values:
| Form | Result |
|---|---|
try { body } with no catch | a Result<T, E>: Ok(value) or Err(error); the failure is gone from the row |
r? on r: Result<T, E> | the value, or fails with the error |
Option.or_fail(o, err) | the value, or fail err on None |
Some rules:
?works only on aResult. A call to a failing function needs no operator.- A
trybody cannot assign to avardeclared outside it (V2041), because the body might stop halfway. Assign after thetryinstead. - Errors never convert implicitly. A smaller union is accepted where a larger one is expected. When two different unions meet with nothing to say which is wanted, the compiler asks for a type annotation (
V2015). - A catch-all
_ => …branch is allowed but discouraged on open unions (W4010).
Defects are not effects
A defect is a bug, not an expected failure: an integer overflow, a broken contract, Option.expect on None. A defect stops the current task after cleaning up open resources. try cannot catch it.
try with no catch turns the failure into a Result<T, E>, and ? turns a Result back into Fail<E>. Task.scope and the test runner observe a defect as Outcome.Defect.
If main ends in a defect, the program exits with status 70 and writes a defect record to stderr. If an expected failure escapes main, the program exits with status 1 and prints error: main failed with <the error>.
| Code | Defect |
|---|---|
D001 | Int overflow |
D002 | division by zero |
D003 | Int beyond ±(2^53−1) on the JavaScript backend |
D010 | failed checked conversion, such as Email.from(s) |
D020 / D021 | requires broken (the caller's bug) / ensures broken (the function's bug) |
D030 | Option.expect on None |
You cannot raise a defect yourself. State a programming rule with requires or Option.expect instead. Task.scope and the test runner can observe a defect as Outcome.Defect(info).
Passing effects through
A function that takes another function, such as map, should not fix that function's effects. A lowercase type parameter like e is an effect-row variable: it stands for "whatever effects the argument has".
This is a declaration, not a standalone program.
fn map<A, B, e>(xs: List<A>, f: fn(A) -> B ! e) -> List<B> ! eIf f is pure, the call is pure. If f logs and may fail, the call logs and may fail. A row can also name some effects and leave the rest to a variable, written {Log | e}:
fn traced<T, e>(name: String, body: fn() -> T ! e) -> T ! {Log | e} {
Log.event(Level.Info, "start {name}", [])
let value = body()
Log.event(Level.Info, "end {name}", [])
value
}A top-level function declares its row variables (<e>). A function with fewer effects can be passed where more are allowed: fn() -> Int ! {Clock} fits fn() -> Int ! e, and e becomes {Clock}.
Standard effects
Each standard effect lives in its own std module (std/console, std/http, …). The first seven are in the prelude; import the rest by name, for example import std/http.{Http}.
| Effect | Operations | Purpose |
|---|---|---|
Console | print, read_line, eprint | Terminal IO (eprint writes to stderr) |
Clock | now, monotonic, sleep | Time |
Random | int, float, bytes, uuid | Randomness |
Env | get, secret | Environment variables: get returns Option<String>, secret returns Option<Secret<String>> |
Log | event | Structured logging |
Task | scope, spawn, join, all, race, yield_now | Structured concurrency |
Test | record_failure, output_lines, snapshot, … | Assertions inside test and property bodies |
Fs | read, read_text, write, list, exists, with_file | Files |
Http | send | HTTP client |
Serve | listen | HTTP server |
Sql | query, execute, transaction | SQL database |
Cli | args, exit | Command-line arguments and exit status |
Budget | reserve, settle | Token, cost and call limits |
Llm | generate, generate_text, stream | Language model calls |
Fail<E> | fail | Expected failure |
There is no Async effect. Any function may pause and resume; the handler decides whether a call waits. See Concurrency.
Effects say what, handlers say where
Fs in a row says "may use the filesystem". It does not say which files. The installed handler decides that, and handlers are built from capability values a program cannot forge. See Capabilities and security.
Reference
Rows are sets
A row is a set of labels plus an optional open tail: {Db, Clock | e}. A label is an effect plus its type arguments, such as Fail<SignupError>. Order does not matter; the formatter sorts labels alphabetically with Fail<…> last. Fail appears at most once in a row: when two failing expressions run in sequence, their errors join, Fail<A> and Fail<B> becoming Fail<A | B>.
What an operation may declare
An operation's row may contain Fail<…>, plus row variables of the operation's own type parameters that also appear in a function-typed parameter, so an operation that runs a callback performs what the callback performs (fn scope<T, e>(body: fn(Scope) -> T ! e) -> T ! e). Any other label is V3010. A handler's clauses run with the handlers outside it: an effect a clause performs goes to where the handler was installed, not where the operation was called.
How rows are inferred inside a body
| Form | Row |
|---|---|
literal, variable, lambda, constructor, handler {…} | {} |
f(a1..an) | rows of f and the arguments, plus f's own row |
Eff.op(args) | rows of the arguments, plus {Eff} and the operation's declared Fail |
fail e | row of e, plus Fail<tag(e)> |
if / match | condition or scrutinee, plus all branches |
with h1..hn { b } | row of b minus the handled effects, plus each handler's row |
try { b } catch { arms } | row of b with caught tags removed, plus the branches' rows |
try { b } | row of b minus Fail |
r? | row of r, plus Fail<E> |
An effect in a branch that never runs still counts. Evaluation is strict and left to right. Top-level rows are never inferred: every top-level fn states its row, so a change in a callee cannot silently change a caller's signature.
What the compiler checks
- The effects a body performs are a subset of its declared row. Each extra one is
V3001, pointing at the call that introduced it. - A label that a closed row does not allow is
V3002. - Every
Failtag is either caught or declared. Union mismatches without an expected type areV2015. - Effect operations declare only
Failand their callbacks' row variables (V3010). - Top-level rows and row variables are declared, never inferred.
Next
Handlers: how the caller decides what an effect actually does.
Details for contributors: design §5.2, §5.6, §5.7, §10.2, §12.2.
Last updated