Sakura Lang

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") }

Open in playground

sakura run prints something like:

hello, Sakura Lang; it is 2026-10-22T13:09:10.309Z
  • ! {Console, Clock} says greet may print and may read the clock, and nothing else.
  • The list in braces is the function's effect row.
  • main calls greet, so main must list Console and Clock too. Effects can't hide inside a helper.

So you can read a signature and know what a function can touch, without reading its body.

Rows add up through calls: a function's row is the union of what its body performs, and a handler subtracts what it handles.Clock.now(): performs Clock. Then fn greet(…) ! {Console, Clock}. Console.print(…): performs Console. fn greet(…) ! {Console, Clock}: the union of its body; a missing label is V3001. Then fn main() ! {Console, Clock} or with Clock.fixed(t) { greet(…) }. fn main() ! {Console, Clock}: calling greet performs greet's row. This path ends here. with Clock.fixed(t) { greet(…) }: the handler takes Clock; {Console} is left.Clock.now()performs ClockConsole.print(…)performs Consolefn greet(…) !{Console,Clock}the union of itsbody; a missinglabel is V3001fn main() !{Console,Clock}calling greetperforms greet'srowwithClock.fixed(t){ greet(…) }the handler takesClock; {Console}is left

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.

Rows add up through calls: a function's row is the union of what its body performs, and a handler subtracts what it handles.

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 error

There 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 only

fail 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:

FormResult
try { body } with no catcha 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 a Result. A call to a failing function needs no operator.
  • A try body cannot assign to a var declared outside it (V2041), because the body might stop halfway. Assign after the try instead.
  • 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.

A typed failure is part of the signature and can be recovered; a defect is a bug and ends the task.typed failure: fail NotFound { id }: adds Fail<NotFound> to the row. Then catch { NotFound { id } => … } or caller: Fail<NotFound>. catch { NotFound { id } => … }: a matching arm recovers; the tag leaves the row. This path ends here. caller: Fail<NotFound>: no arm matches: it propagates; out of main, exit 1. This path ends here. defect: D002: a bug such as division by zero; try cannot catch it. finalizers: open resources are closed. Outcome.Defect(info): the task ends; out of main, exit 70.typed failurefail NotFound{ id }addsFail<NotFound> tothe rowcatch {NotFound{ id } => … }a matching armrecovers; the tagleaves the rowcaller:Fail<NotFound>no arm matches: itpropagates; out ofmain, exit 1defectD002a bug such asdivision by zero;try cannot catchitfinalizersopen resources areclosedOutcome.Defect(info)the task ends; outof main, exit 70

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.

A typed failure is part of the signature and can be recovered; a defect is a bug and ends the task.

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

CodeDefect
D001Int overflow
D002division by zero
D003Int beyond ±(2^53−1) on the JavaScript backend
D010failed checked conversion, such as Email.from(s)
D020 / D021requires broken (the caller's bug) / ensures broken (the function's bug)
D030Option.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> ! e

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

EffectOperationsPurpose
Consoleprint, read_line, eprintTerminal IO (eprint writes to stderr)
Clocknow, monotonic, sleepTime
Randomint, float, bytes, uuidRandomness
Envget, secretEnvironment variables: get returns Option<String>, secret returns Option<Secret<String>>
LogeventStructured logging
Taskscope, spawn, join, all, race, yield_nowStructured concurrency
Testrecord_failure, output_lines, snapshot, …Assertions inside test and property bodies
Fsread, read_text, write, list, exists, with_fileFiles
HttpsendHTTP client
ServelistenHTTP server
Sqlquery, execute, transactionSQL database
Cliargs, exitCommand-line arguments and exit status
Budgetreserve, settleToken, cost and call limits
Llmgenerate, generate_text, streamLanguage model calls
Fail<E>failExpected 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

FormRow
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 erow of e, plus Fail<tag(e)>
if / matchcondition 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 Fail tag is either caught or declared. Union mismatches without an expected type are V2015.
  • Effect operations declare only Fail and 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.

Edit on GitHub

Last updated

On this page