---
title: "7.6 Data from outside: checking it once"
url: https://una-lang.org/en/learn/failure/data-from-outside-checking-it-once/
release: v0.4.0
edition: "0.2"
---

# 7.6 Data from outside: checking it once

## 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](https://una-lang.org/en/learn/contracts/requirements-rules-from-outside-the-code/#s5-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:

```una include="steps/22-unchecked-rate/src/rates.una#Percent..parse_rate" title="steps/22-unchecked-rate/src/rates.una"
--- 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)
  n
```

`una check .` refuses it:

```text include="steps/22-unchecked-rate/expected/rendered.txt"
[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:

```una include="steps/23-check-forms/src/rates.una#Percent..by_check" title="steps/23-check-forms/src/rates.una"
--- 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)
```

```toml include="steps/23-check-forms/una.toml" title="steps/23-check-forms/una.toml"
[package]
name = "rates"
version = "0.1.0"
edition = "0.2"

[run]
entry = "rates"
grants = ["console"]

[escape_budget]
checked_per_module = 1
```

### 7.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](https://una-lang.org/en/learn/failure/when-no-proof-can-decide-checked-and-opaque-predicates/#s7-5)). It counts against the module's escape budget, so its `una.toml` allows one.

### 7.6.3.3 Running the forms

```text include="steps/23-check-forms/expected/output.txt"
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:

:::steps
```una include="steps/24-boundary/src/rates.una" title="steps/24-boundary/src/rates.una" verified="check, run"
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"))
```

1. **`parse_rate(raw: Text) -> Percent`.** The only place where text becomes a `Percent`. It fails, with `RateError`, when the text is not a number or not between 0 and 100.
2. **`raw.trim.to_int()` and `if none fail NotANumber(raw)`.** `trim` removes the spaces at both ends, and `to_int` gives `None` for text that is not a number.
3. **`if n < 0 or n > 100` then `fail`, `else n`.** In the `else` branch, the verifier knows `0 <= n <= 100`, so it proves the result a `Percent`.
4. **`rest_of(rate: Percent) -> Percent = 100 - rate`.** Inside the program, nothing checks again: `100 - rate` is in range because `rate` is.
5. **`attempt parse_rate(raw)`.** In the `Ok(rate)` arm, `rate` is a `Percent`, with its fact, as after a direct call ([What an `Ok` value keeps](https://una-lang.org/en/learn/failure/failures-as-values-attempt-and-result/#what-an-ok-value-keeps)).
:::

`una run .` prints:

```text include="steps/24-boundary/expected/output.txt"
15% off: the customer pays 85%
150 is not between 0 and 100
'ten' is not a number
```

## 7.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](https://una-lang.org/en/learn/contracts/refined-kinds-and-predicates/#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](#a-discount-rate-typed-in-the-back-office). It reads a rate from text and passes it straight on, without `parse_rate`:

```una include="steps/25-quick-rest/src/rates.una#quick_rest" title="steps/25-quick-rest/src/rates.una"
--- 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?

:::answer Show the answer
It does not check:

```text include="steps/25-quick-rest/expected/rendered.txt#L1,L18"
[U5001] Error: refinement `n in 0..100` is refuted
    │ Note 2: counterexample: n = 101, raw = Text#1, raw.len = 0
```

`rest_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](#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.
:::
