# Modelling your domain

> Turning the tables you already have into events and facts, and choosing what to guard first.

Source: https://elephlanguage.vercel.app/docs/use/modelling

This is the only genuinely new thinking in adopting eleph. Everything else is
four method calls. Here you take the tables you already have and ask a
different question of them: not *what is the state*, but *what
happened*.

## The translation

Your database has a row per customer with columns on it. eleph has no columns.
A fact is a question asked of the history, every time.

| You have | You record | You ask |
|---|---|---|
| `users.active` (boolean) | `subscribed(u)`, `cancelled(u)` | `active(U) := subscribed(U) since_not cancelled(U)` |
| `charges.refunded_at` (nullable) | `refunded(u, c)` | `refunded(U, C) since_not charged(U, C)` |
| `sessions.user_id` | `authenticated(who, u)`, `logged_out(who, u)` | `authorised(Q, U) := authenticated(Q, U) since_not logged_out(Q, U)` |
| `reservations` (a table) | `make_reservation(p, f)`, `cancel_reservation(p, f)` | `count P: Passenger where has_reservation(P, F) < 2` |
| an `audit_log` beside the state | nothing extra | there is only the log; the state is derived |

The last row is the one that changes how a system is argued about. In an
ordinary design the audit log is a second artifact that is supposed to agree
with the first. Here there is no first.

## The one rule for events

> **PROVED: An event is something that happened, and it never un-happens**
>
> Never record a *state*. Record the *transition*. `set_active(u, false)` is a
> column with extra steps; `cancelled(u)` is an event.
>
> If you find yourself wanting to record the same event twice to mean "still
> true", you have modelled a state. Go back one step and find the thing that
> changed.

## Put in the event what the event decides

This is the trap that cost the worked example two runs, and it is worth the
whole page.

The first version of the refund rule read *"refundable = an open charge, and
the customer is not active"*:

```eleph
fact refundable(U, C) := charged(U, C) and not active(U)
```

Cancelling is permitted for an active customer. So:

```python
guard.require("refundable", "ana", "c1")   # Ungrounded, correctly

guard.require("active", "ana")             # permitted
guard.record("cancelled", "ana")

guard.require("refundable", "ana", "c1")   # now it passes
```

**Two permitted actions compose into a forbidden outcome.** Cancel today, and a
charge from three months ago becomes refundable. The model reached it on its
own, occasionally, by reading "I cancelled last month" as a request to cancel.

Both versions were proved for every history, before and after.

> **CAREFUL: A proof says each obligation holds. It does not say the policy is the one you meant.**
>
> Writing the rule down does not hand you the right rule. It hands you a rule you
> can interrogate, and interrogating it is what surfaced this. Without that, the
> hole would have shipped with the word `PROVADO` next to it, which is the worst
> combination available.

The fix is the pattern for anything the language cannot work out for itself:
**what makes a charge refundable is when it fell**, not the state of the
account at the moment somebody asks. So the charge carries that in its own
identity:

```eleph
event charged_while_active(u: User, c: Charge, amount: Number)
event charged_after_cancelling(u: User, c: Charge, amount: Number)

fact refundable(U: User, C: Charge) := charged_after_cancelling(U, C, amount > 0) since_not refunded(U, C)
```

Two events instead of one, and the composition is gone.

## Time

> **LIMIT: There is no wall clock**
>
> `since_not` knows **order**, not time. *"Refund within 24 hours of the charge"*
> is not expressible directly.
>
> The pattern that works, and the one the τ-bench audit uses, is for your system
> to emit the deadline as an event:
>
> ```python
> guard.record("charged_after_cancelling", user, charge, amount)
> guard.promise(user, "refunded", user, charge,
>               before=("refund_window_closed", (user, charge)))
>
> # ... your scheduler, 24 hours later
> guard.record("refund_window_closed", user, charge)
> ```
>
> The clock lives outside the logic, which is how event-sourced systems handle
> time anyway.

## Money and quantities

A comparison in an argument position constrains a numeric field, **at the
instant the event happens**:

```eleph
fact within_limit(U: User, C: Charge) := charged_after_cancelling(U, C, amount <= 200) since_not refunded(U, C)
```

That is what keeps the [completeness argument](https://elephlanguage.vercel.app/docs/concepts/completeness)
intact, and it is also the limit: you can ask whether *this charge* was over
200, not whether the sum of the last three was. **Aggregate arithmetic over the
history is not expressible.** If you need a running total, compute it in your
system and emit the conclusion as an event.

## Who is allowed to ask

The failure that cost 0/5 in the comparison was not a lie. The agent reported a
stranger's account truthfully. Every other obligation passed that run.

```eleph
fact authorised(Q: Party, U: User) := authenticated(Q, U) since_not logged_out(Q, U)

on question(Who, active(U)) permitted authorised(Who, U):
    answer Who with active(U)
```

Model authority as a fact about the log, like everything else. See
[permission](https://elephlanguage.vercel.app/docs/concepts/permission), including what it deliberately is not:
there are no roles, no hierarchy and no delegation.

## Where to start, concretely

- **Pick the tool that would cost you most to get wrong.** Money out the door,
data disclosed, something irreversible. Not the most frequent one.
- **Write down the sentence your team already says about it.** *"We only refund a
charge that fell after cancellation, has not been refunded, and is under R$
200."* If nobody can say that sentence, that is your finding, and it is worth
more than the integration.
- **Turn each clause into an event or a fact.** Three clauses, three facts. The
table at the top of this page is the whole translation.
- **Run `eleph check`.** If it does not prove, the rule contradicts itself and
you have learned something before writing any Python.
- **Run it as an observer over yesterday's traffic.** Record what happened, ask
the facts what was true, and see whether it ever disagrees with what your agent
did. It enforces nothing, so it cannot break anything.
- **Then turn on `require` for that one tool.** Add the next one when the first
is boring.

## Reading the proof

```out
$ eleph check support.eleph

8 eventos, 5 fatos, 2 handlers

2 obrigacoes derivadas do texto do programa
cada uma checada no seu limiar de completude (o maior: 6 eventos) -- exaustivo

PROVADO  -  2 obrigacoes valem para TODO historico, de qualquer tamanho
```

`PROVADO` means every obligation holds for **every** history, of any length,
not just the ones you thought to test. If you see `SEM CONTRAEXEMPLO` instead,
the run was not exhaustive and the tool is telling you so. The difference is on
[proof, not spot check](https://elephlanguage.vercel.app/docs/concepts/completeness).

## Next

- [**Python API**](https://elephlanguage.vercel.app/docs/python-api) — every method and exception.
- [**Temporal expressions**](https://elephlanguage.vercel.app/docs/reference/expressions) — for when
`since_not` and `count` are not enough.
- [**Honest limits**](https://elephlanguage.vercel.app/docs/limits) — verified, and worth reading before you
commit to this.
