Contracts and refinements
Rules about a function's inputs and outputs, and types with rules, checked whenever the code runs.
A contract is a rule about a function's inputs or output, written in its signature. requires states what callers must pass. ensures states what the function promises to return. Both are checked every time the code runs.
fn clamp(x: Int, lo: Int, hi: Int) -> Int
requires ordered: lo <= hi
ensures bounded: lo <= result && result <= hi
{
if x < lo { lo } else if x > hi { hi } else { x }
}
test "clamp keeps a value in range" {
expect_eq(clamp(12, 0, 10), 10)
expect_defect(fn() { clamp(1, 5, 0) })
}requires ordered: lo <= hiis checked whenclampis called.orderedis an optional name that shows up in error reports.ensures bounded: …is checked whenclampreturns.resultis the return value.clamp(1, 5, 0)breaksordered. That is a defect: a bug that stops the program, not a normal error. The test checks for it withexpect_defect.
Types say what shape a value has. Contracts say what is true about it. Both are in the signature, so both are what a reviewer reads.
Preconditions and postconditions
requiresis checked on entry. A violation is defectD020and blames the caller, pointing at the call.ensuresis checked once on a normal return. A violation is defectD021and blames the function. It is not checked when the function fails or stops, because there is noresult.- There is no
old(expr). Arguments never change, so a parameter named inensuresis exactly what was passed in.
A where refinement is checked when a value enters the type. A scalar literal is decided at compile time when the bounded evaluator can (V5004 on rejection); every other check stays at runtime unless sakura verify proves it.
Contracts work alongside typed errors:
error Insufficient
error Frozen
type WithdrawError = Insufficient | Frozen
type Account = { id: Uuid, balance: Int, frozen: Bool }
fn withdraw(from: Account, amount: Int) -> Account ! {Fail<WithdrawError>}
requires positive: amount > 0
ensures same_account: result.id == from.id
ensures debited: result.balance == from.balance - amount
ensures non_negative: result.balance >= 0
{
if from.frozen { fail Frozen }
if amount > from.balance { fail Insufficient }
Account { ..from, balance: from.balance - amount }
}A frozen account or a low balance can happen in normal use, so they are errors the caller handles. A negative amount is a bug in the caller, so it is a precondition, not an error.
Refinement types
A refinement is a type plus a rule, written with where. Inside the rule, it is the value.
type Email = String where String.len(it) <= 254 && String.contains(it, "@")
type Percent = Int where it >= 0 && it <= 100
type NonEmpty<T> = List<T> where List.len(it) > 0A Percent is its own type, stored like an Int. You can use a Percent anywhere an Int is expected. Going the other way needs a check.
Record fields can carry a rule too. It is checked when the record is built:
type Priority = Low | Normal | High
type Ticket = {
title: String where String.len(it) > 0 && String.len(it) <= 120,
priority: Priority,
}How values enter a refined type
A value becomes a Percent in one of four ways:
| Entry point | On failure |
|---|---|
Percent.validate(n) -> Result<Percent, Violation> | Returns Err(Violation { type_name, clause, value_summary }). |
Percent.from(n) -> Percent | Defect D010. Use only where failure would be a bug; sakura audit lists the calls. |
let p: T = Json.decode(text)? and other decoding, with the target named by the annotation | A typed DecodeError, never a defect. Nested field rules are checked. |
A literal, let p: Percent = 50 | Checked at compile time when possible (V5004 if it fails); otherwise once before main starts. |
Use validate for input you don't control:
type Percent = Int where it >= 0 && it <= 100
fn describe(input: Int) -> String {
match Percent.validate(input) {
Ok(p) => "{p}%",
Err(_) => "out of range",
}
}Once a value is a Percent, nothing checks it again. Values never change in place, so a checked value stays valid. Updating a record, Ticket { ..t, title: x }, with an already-checked x needs no new check.
Generic refinements
A generic refinement keeps its element type: NonEmpty<Int> can be used as a List<Int>. Use a type annotation to pick the element type:
import std/core.{Violation}
type NonEmpty<T> = List<T> where List.len(it) > 0
test "generic refinements keep their element type" {
let xs: NonEmpty<Int> = NonEmpty.from([3, 9, 4])
expect_eq(List.fold(xs, 0, fn(sum, n) { sum + n }), 16)
let empty: Result<NonEmpty<String>, Violation> = NonEmpty.validate([])
expect(empty.is_err())
}Validating untrusted input
Untrusted<T> marks data from outside the program. Untrusted.validate checks it against a refined type, named by an annotation, and returns Err(Violation) on failure:
import std/core.{Violation}
type Percent = Int where it >= 0 && it <= 100
fn read_percent(raw: Untrusted<Int>) -> Result<Percent, Violation> {
Untrusted.validate(raw)
}
test "untrusted input is checked" {
expect_eq(read_percent(Untrusted.of(50)), Ok(Percent.from(50)))
expect(read_percent(Untrusted.of(150)).is_err())
}The target must be a refined type over the wrapped type. An unknown target, a plain type, a different base type, or using Untrusted.validate as a function value is V5003.
Rules over lists
A contract can check every item of a list with List.all or List.any:
type NonEmpty<T> = List<T> where List.len(it) > 0
fn top_score(scores: NonEmpty<Int>) -> Int
ensures List.all(scores, fn(s) { s <= result })
{
let first = List.first(scores).expect("NonEmpty has a first element")
List.fold(scores, first, fn(best, s) { Int.max(best, s) })
}Such a check walks the whole list on every call, so the compiler warns once per clause that calls List.all, List.any or List.contains on a parameter or it (W5005). String.contains does not trigger the warning, so the Email type above is quiet.
Contracts are always checked
Contracts are checked at runtime in every build, on JavaScript and WebAssembly. sakura build removes a check only when sakura verify has proved it can never fail; see Static verification.
A broken contract is a defect, not an error. It stops the current task after open resources are cleaned up, and try cannot catch it. Task.scope and the test runner can observe it. A defect in main exits with status 70 and a structured report.
Contracts on pub functions are part of the signature shown by sakura doc, the MCP symbol_query tool and editor hover.
The guarantee model
Every claim Sakura Lang makes about a program has exactly one of four statuses:
| Status | Meaning | Who establishes it |
|---|---|---|
proved | Holds on every run, under the stated assumptions. | The type and effect checker; contracts proved by sakura verify. |
runtime_checked | A violation is caught where it happens and becomes a defect. The bad value never escapes. | Contract checks (requires, ensures, where), checked arithmetic. |
tested | Held on the inputs that were run. | sakura test (unit, property, snapshot, simulation). |
trusted | Assumed. | Foreign-function declarations, host handlers, @trust sites, the toolchain itself. |
The build manifest labels contract checks that stay in the program runtime_checked, and clauses whose checks were all removed using proofs proved. Compiling a program does not prove its contracts.
The contract subset
The rules in where, requires, ensures and property clauses must be pure, must finish, and must give the same answer every time. The compiler enforces this by syntax:
- No loops and no recursion.
- Calls only to pure functions marked
@totalor themselves in the subset, checked all the way down. Anything else isV5001. - Allowed: comparisons, checked arithmetic,
&&,||,!, field and tuple access,matchon variants,List.len,String.len, andList.all(xs, fn(x) { … })andList.any.
Arithmetic in a rule is checked, so a rule can itself hit a defect. That is reported as D011 (contract evaluation failed).
@total lets a function with recursion or a loop be used in a contract. It is a trusted claim that a pure function always finishes; the compiler does not prove it. The standard library marks a fixed list (List.len, List.get, List.all, List.any, List.contains, Map.get, String.len, String.contains, Option.is_some, Int.abs and a few more). You can mark your own functions, and sakura audit lists every @total you write, like every @trust:
@total // trusted: n / 10 moves toward 0 on every call
fn digits(n: Int) -> Int {
if n > -10 && n < 10 { 1 } else { 1 + digits(n / 10) }
}
type Pin = Int where it >= 0 && digits(it) == 4Literal refinements at compile time
When you write a literal where a refined type is expected, such as let p: Percent = 50, the compiler tries to check it right away. It evaluates Int, Float, String and Bool literals against the rule, with a fixed limit of 10,000 steps per literal. It understands arithmetic and comparisons, &&/||, if/let/blocks, pure functions built from those, and the string functions len, contains, starts_with and ends_with. String.len counts UTF-8 bytes.
- True: the literal is accepted, with no check at startup.
- False, or a defect while checking:
V5004, naming the literal and the rule. For example,let p: Percent = 150is rejected. - Can't decide: the literal is checked once when the module starts. A failure is defect
D010beforemainruns, even if the literal is inside a function that would only run later. There is no warning.
match, collection functions such as String.split, and running past the step limit all leave a runtime check. So does an intermediate integer beyond JavaScript's safe range, because backends differ there. V5002 is retired and never emitted; its explain page stays for old reports. sakura audit lists each literal it could not decide as a from site with reason: "literal"; see audit literal conversions.
Frozen specs during agent repair
An agent fixing a failing build must not "fix" it by weakening the rules. sakura fix, the MCP apply_patch tool and sakura check --frozen-specs <symbols|all> reject any patch that changes a frozen function's signature, effects, errors, requires/ensures/where clauses, or any test or property body. The error is V8020 (spec frozen) and names the clause.
Compiler fixes that touch a contract are marked impact: contract_change and are never applied automatically. See Diagnostics.
Property tests from contracts
sakura test --contracts writes tests for you. For each eligible pub fn with a refined parameter or a requires clause, it generates inputs that pass the rules, calls the function, and checks ensures and refinements. A defect fails the test. The smallest failing input is saved to tests/regressions/<fn>.json and replayed first on later runs. See the worked example and the limits.
Not supported
- Termination proofs.
sakura verifyproves rules assuming the function returns; it does not prove that it returns. - Narrowing by
if.if n >= 0does not turnninto a refined type. Usevalidateorfrom. old(expr)inensures. Nothing changes in place, so there is nothing to snapshot.- Proof syntax. The keywords
verify,proofandghostare reserved and rejected today (V0007).
Next
Static verification: prove contracts before the code runs.
Details for contributors: design §1.2, §4.3, §7.1, §7.5, §17.87, §17.90.
Last updated