Home / Learn / 7 Results and failures
7.6 Data from outside: checking it once
Page 7 of 12
7.6.1 Where the program meets the world
Inside a program, contracts are checked where code meets code. At each call, the caller proves the callee's requires and gets its ensures in return. A refined kind is a meeting point too: a value is checked once, where it enters the kind, and every function after that may rely on it.
A boundary is where the program meets something it does not control: text typed by a person, a line of a file, a field sent by another system. No proof can say what a person will type. So at the boundary, the program tests the data once, and gives it a refined kind if it passes. (The rules a contract comes from, such as a billing policy, cross a boundary too; section 5.5 records them.)
Think of the receiving dock of a warehouse. Goods arrive from many suppliers, and each delivery is checked once, at the dock, against the order. Inside the warehouse, nobody checks the boxes again: a box on a shelf has passed the dock.
7.6.2 Why outside data needs a check
A discount rate is typed into the back office as text. Here is a function that turns the text into a Percent, and checks only that it is a number:
--- A share in whole percent.
kind Percent = Int in 0..100
--- Why a typed rate was refused.
kind RateError = | NotANumber(raw: Text)
--- A discount rate typed into the back office. It checks that the text is a number, and
--- nothing more.
parse_rate(raw: Text) -> Percent
fails RateError
=
let n = raw.trim.to_int()
if none fail NotANumber(raw)
nuna check . refuses it:
[U5001] Error: refinement `result in 0..100` is refuted
╭─[ src/rates.una:16:3 ]
│
4 │ kind Percent = Int in 0..100
│ ───┬──
│ ╰──── range
│
16 │ n
│ ┬
│ ╰── refinement `result in 0..100` is refuted
│
│ Help 1: repair 1: add a guard (`if` or a `when` arm) that handles the values where `result in 0..100` does not hold
│
│ Help 2: repair 2 (escape: checked; a runtime test replaces the static proof: the program fails at run time where the proof would have rejected it; it counts against [escape_budget] and is listed in the build report): check the value with `checked(value, result in 0..100) else fail <Variant>`
│
│ Note 1: obligation ob-2b8bb19e1487 (refinement) is refuted: result in 0..100
│
│ Note 2: counterexample: raw = Text#1, raw.len = 0, result = 101
│
│ Note 3: run `una explain U5001` for an explanation
────╯The goal is the condition of Percent for the returned value: result in 0..100. The counterexample says what the solver tried: raw = Text#1, some text, and result = 101. The solver does not know what to_int gives for that text, beyond an Int, so 101 is possible. That is the honest answer: a person can type 101, or -5, or 150.
Without the check, the program has two bad choices. It can trust the text, and carry a "percent" of 150 into every function that computes a price. Or every function that receives a rate can test it again, and one of them will forget. Una takes a third way: one function checks, and gives the value its kind.
7.6.3 How to check data once
A function at the boundary takes the raw value, tests it, and either gives it back with its refined kind or fails. The step of this part shows the two ways to test:
--- A share in whole percent.
kind Percent = Int in 0..100
--- Why a rate was refused.
kind RateError = | OutOfRange(value: Int)
--- A guard: the code tests the value, and fails when it does not fit.
by_guard(n: Int) -> Percent
fails RateError
=
if n < 0 or n > 100 then fail OutOfRange(value: n) else n
--- `checked`: a test at run time that gives the value its kind, or fails.
by_check(n: Int) -> Percent
fails RateError
=
checked(n, it in 0..100) else fail OutOfRange(value: n)[package]
name = "rates"
version = "0.1.0"
edition = "0.2"
[run]
entry = "rates"
grants = ["console"]
[escape_budget]
checked_per_module = 17.6.3.1 A guard that fails
by_guard tests the value with an if, and fails with a variant of its error kind when the value does not fit. In the else branch, the verifier knows 0 <= n and n <= 100, so it proves that n is a Percent. Nothing runs that the proof did not cover.
7.6.3.2 checked
by_check writes the test as checked(n, it in 0..100) else fail OutOfRange(value: n): the value, the condition with it for the value, and the failure (section 7.5). It counts against the module's escape budget, so its una.toml allows one.
7.6.3.3 Running the forms
guard: Ok(15) Err(OutOfRange(150))
checked: Ok(15) Err(OutOfRange(-5))Both forms give the same results here. The guard is the better choice when, as here, the test is in the refinement language: it needs no budget. checked is for a test the solver cannot follow, such as the format of a SKU.
7.6.4 A discount rate typed in the back office
Now a whole boundary: the back office types a rate, and the program tells a number from text that is not one, and a rate in range from one out of it:
module rates
--- A share in whole percent.
kind Percent = Int in 0..100
--- Why a typed rate was refused.
kind RateError = NotANumber(raw: Text) | OutOfRange(value: Int)
--- A discount rate typed into the back office. This is where text from a person becomes a
--- `Percent`, so this is where it is checked.
parse_rate(raw: Text) -> Percent
fails RateError
=
let n = raw.trim.to_int()
if none fail NotANumber(raw)
if n < 0 or n > 100
fail OutOfRange(value: n)
else
n
--- What is left of 100 percent after the rate. A `Percent` needs no second check.
rest_of(rate: Percent) -> Percent = 100 - rate
--- Why a rate was refused, for a person to read.
explain(failure: RateError) -> Text
=
when failure
is NotANumber(raw) -> "'{raw}' is not a number"
is OutOfRange(value) -> "{value} is not between 0 and 100"
describe(raw: Text) -> Text
=
let outcome = attempt parse_rate(raw)
when outcome
is Ok(rate) -> "{rate}% off: the customer pays {rest_of(rate)}%"
is Err(failure) -> explain(failure)
--- Shows three typed rates.
pub main() -> Unit
uses @console: Console[print]
=
@console.print(describe("15"))
@console.print(describe("150"))
@console.print(describe("ten"))parse_rate(raw: Text) -> Percent. The only place where text becomes aPercent. It fails, withRateError, when the text is not a number or not between 0 and 100.raw.trim.to_int()andif none fail NotANumber(raw).trimremoves the spaces at both ends, andto_intgivesNonefor text that is not a number.if n < 0 or n > 100thenfail,else n. In theelsebranch, the verifier knows0 <= n <= 100, so it proves the result aPercent.rest_of(rate: Percent) -> Percent = 100 - rate. Inside the program, nothing checks again:100 - rateis in range becauserateis.attempt parse_rate(raw). In theOk(rate)arm,rateis aPercent, with its fact, as after a direct call (What anOkvalue keeps).
una run . prints:
15% off: the customer pays 85%
150 is not between 0 and 100
'ten' is not a number7.6.5 How a check at the boundary behaves
7.6.5.1 One way in
Once parse_rate exists, a Percent can come from nowhere but a proof: a literal the verifier checks, a computation it proves, or this function, whose else branch is itself a proof.
Security
A refined kind turns "every function must remember to check the rate" into "one function checks it, and the checker refuses every unproven way in". A new function that takes a Percent cannot receive 150, whoever calls it.
7.6.5.2 The fact survives attempt and when
attempt keeps the callee's promise on the Ok path, and the arm is Ok(rate) gives rate its kind. So the caller of a boundary function handles the failure once, and from then on works with a value that needs no check.
7.6.5.3 Fail, do not return an Option
A boundary function fails with a reason, rather than giving back None. The reason tells a person what to fix. And in edition 0.2 an Option[Percent] is not even allowed: a refined kind cannot be a type argument, as Refinements of refinements, and type arguments says.
7.6.6 Check yourself: boundaries
Someone adds a function to the back-office module of A discount rate typed in the back office. It reads a rate from text and passes it straight on, without parse_rate:
--- A rest computed from typed text, without `parse_rate`.
quick_rest(raw: Text) -> Percent
=
let n = raw.trim.to_int()
if none use 0
rest_of(n)Does it check? If not, what is the obligation, and what is the fix?
Show the answer
It does not check:
[U5001] Error: refinement `n in 0..100` is refuted
│ Note 2: counterexample: n = 101, raw = Text#1, raw.len = 0rest_of takes a Percent, so the call raises a refinement obligation: n in 0..100. Nothing tells the verifier what to_int gave back, so it refutes the goal with a value out of range, 101, as in Why outside data needs a check. The fix is the boundary itself: get the rate from parse_rate, with attempt or a handling clause, and pass on the Percent it gives back. The checker leaves no other way in.