diff --git a/packages/alchemy-bend/.dockerignore b/packages/alchemy-bend/.dockerignore new file mode 100644 index 00000000000..339938901a2 --- /dev/null +++ b/packages/alchemy-bend/.dockerignore @@ -0,0 +1,2 @@ +**/build +*.journal diff --git a/packages/alchemy-bend/.gitignore b/packages/alchemy-bend/.gitignore new file mode 100644 index 00000000000..801cde25d76 --- /dev/null +++ b/packages/alchemy-bend/.gitignore @@ -0,0 +1,5 @@ +build/ +*.journal +.wrangler/ +examples/bank/durable-object/Server.mjs +!examples/bank/clock.js diff --git a/packages/alchemy-bend/Dockerfile b/packages/alchemy-bend/Dockerfile new file mode 100644 index 00000000000..c698d943561 --- /dev/null +++ b/packages/alchemy-bend/Dockerfile @@ -0,0 +1,23 @@ +# The bank server: compiled by Bend to JavaScript, run by bun. +# +# docker build -t bend-bank . && docker run -p 8788:8788 -v bank:/data bend-bank +FROM debian:bookworm-slim AS build +RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates \ + && rm -rf /var/lib/apt/lists/* +RUN curl -fsSL https://bend-lang.com/install.sh | sh +WORKDIR /src +COPY Domain.bend Model.bend ./ +COPY examples ./examples +RUN cd examples/bank && BEND_NO_TELEMETRY=1 /root/.bend/bin/bend Server.bend -o /bank.js \ + && mv /bank.js /bank.cjs + +FROM oven/bun:1-slim +# curl is how the server calls the outside systems at FRAUD_URL and PAYMENTS_URL. +RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates \ + && rm -rf /var/lib/apt/lists/* +COPY --from=build /bank.cjs /app/bank.cjs +ENV BANK_HOST=0.0.0.0 +WORKDIR /data +VOLUME /data +EXPOSE 8788 +CMD ["bun", "/app/bank.cjs"] diff --git a/packages/alchemy-bend/Domain.bend b/packages/alchemy-bend/Domain.bend new file mode 100644 index 00000000000..1010a7ff486 --- /dev/null +++ b/packages/alchemy-bend/Domain.bend @@ -0,0 +1,55 @@ +# alchemy-bend: the pieces every aggregate shares. +# +# An aggregate is a module with a state, a command, an event and a rejection +# type, and two functions. decide answers a command with the events it +# records or a rejection, given a context (who asks, and when). evolve +# applies one event to the state. The templates here take those two +# functions and give back the rest. + +import Base + +# What decide answers. +type Decided<-E: Data, -R: Data> is Data: + Reject{why: R} + Record{events: +List} + +# A command with the context it is sent in. +type Sent<-X: Data, -C: Data> is Data: + Sent{context: X, command: C} + +# The state after every event, in order, all recorded in one context. +def apply(~X: Data, ~S: Data, ~E: Data, ~evolve: X -> S -> E -> S, events: +List, +context: X, state: S) -> S: + match events: + case Nil{}: + state + case e <> es: + apply(~X, ~S, ~E, ~evolve, es, context, evolve(context, state, e)) + +# The state a decision leaves: unchanged when the command is rejected. +def settle(~X: Data, ~S: Data, ~E: Data, ~R: Data, ~evolve: X -> S -> E -> S, +context: X, +state: S, decided: Decided) -> S: + match decided: + case Reject{why}: + state + case Record{events}: + apply(~X, ~S, ~E, ~evolve, events, context, state) + +# The state after one command. +def step( + ~X: Data, ~S: Data, ~C: Data, ~E: Data, ~R: Data, + ~decide: X -> S -> C -> Decided, ~evolve: X -> S -> E -> S, + +context: X, +state: S, command: C +) -> S: + settle(~X, ~S, ~E, ~R, ~evolve, context, state, decide(context, state, command)) + +# The state after every command, in order. +def replay( + ~X: Data, ~S: Data, ~C: Data, ~E: Data, ~R: Data, + ~decide: X -> S -> C -> Decided, ~evolve: X -> S -> E -> S, + commands: List>, +state: S +) -> S: + match commands: + case Nil{}: + state + case Sent{+context, command} <> rest: + replay(~X, ~S, ~C, ~E, ~R, ~decide, ~evolve, rest, + step(~X, ~S, ~C, ~E, ~R, ~decide, ~evolve, context, state, command)) diff --git a/packages/alchemy-bend/Model.bend b/packages/alchemy-bend/Model.bend new file mode 100644 index 00000000000..988dac0fab8 --- /dev/null +++ b/packages/alchemy-bend/Model.bend @@ -0,0 +1,404 @@ +# alchemy-bend: an engine for any model. +# +# A model says what its commands, events, saga steps, outside calls and +# answers are, and gives four functions: what a command records, what the +# policies do about an event, what a saga step does, and what an answer from +# outside does. The templates here take those and give back the rest: the +# world, one step of it, settling, and running a sequence of moves. +# +# C a command, with who sends it and to what +# E an event one instance recorded +# W a saga's next step +# K a call to an outside system, waiting for its answer +# A an answer from an outside system +# R where a saga's run stands +# +# The world keeps every command that was sent, with when. An instance's state +# is its commands replayed, so a rule proved for every sequence of commands an +# aggregate can be sent holds for every instance in every world. + +import Base + +# A command, and when it was sent. +type Stamped<-C: Data> is Data: + Stamped{time: U32, command: C} + +# A command to send at a time. +type Scheduled<-C: Data> is Data: + Scheduled{due: U32, command: C} + +type World<-C: Data, -E: Data, -W: Data, -K: Data, -R: Data> is Data: + World{ + now: U32, + sent: +List>, + log: +List, + inbox: +List, + work: +List, + calls: +List, + runs: +List, + schedule: +List>} + +# What can happen to a model, one thing at a time. +type Move<-C: Data, -A: Data> is Data: + # A caller sends a command. + Send{command: C} + # The undelivered event at this place in the inbox reaches the policies. + Deliver{index: Nat} + # A fault: the event at this place in the log reaches the policies again. + Redeliver{seq: Nat} + # The saga step at this place in the work takes place. + Advance{index: Nat} + # An outside system answers. + Answer{answer: A} + Pass{seconds: U32} + +def start(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data) -> World: + World{0, [], [], [], [], [], [], []} + +# Reading the world +# ================= + +def now_of(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World) -> U32: + match world: + case World{now, sent, log, inbox, work, calls, runs, schedule}: + now + +def sent_of(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World) + -> +List>: + match world: + case World{now, sent, log, inbox, work, calls, runs, schedule}: + sent + +def log_of(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World) + -> +List: + match world: + case World{now, sent, log, inbox, work, calls, runs, schedule}: + log + +def inbox_of(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World) + -> +List: + match world: + case World{now, sent, log, inbox, work, calls, runs, schedule}: + inbox + +def work_of(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World) + -> +List: + match world: + case World{now, sent, log, inbox, work, calls, runs, schedule}: + work + +def calls_of(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World) + -> +List: + match world: + case World{now, sent, log, inbox, work, calls, runs, schedule}: + calls + +def runs_of(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World) + -> +List: + match world: + case World{now, sent, log, inbox, work, calls, runs, schedule}: + runs + +def schedule_of(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World) + -> +List>: + match world: + case World{now, sent, log, inbox, work, calls, runs, schedule}: + schedule + +# Changing one part of the world +# ============================== + +def with_now(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World, + now: U32) -> World: + match world: + case World{old, sent, log, inbox, work, calls, runs, schedule}: + World{now, sent, log, inbox, work, calls, runs, schedule} + +def with_inbox(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World, + inbox: +List) -> World: + match world: + case World{now, sent, log, old, work, calls, runs, schedule}: + World{now, sent, log, inbox, work, calls, runs, schedule} + +def with_work(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World, + work: +List) -> World: + match world: + case World{now, sent, log, inbox, old, calls, runs, schedule}: + World{now, sent, log, inbox, work, calls, runs, schedule} + +# A saga's next step joins the work. +def add_work(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World, + next: W) -> World: + match world: + case World{now, sent, log, inbox, work, calls, runs, schedule}: + World{now, sent, log, inbox, List.append(&2, W, work, [next]), calls, runs, schedule} + +def with_calls(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World, + calls: +List) -> World: + match world: + case World{now, sent, log, inbox, work, old, runs, schedule}: + World{now, sent, log, inbox, work, calls, runs, schedule} + +# A call to an outside system starts waiting for its answer. +def add_call(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World, + call: K) -> World: + match world: + case World{now, sent, log, inbox, work, calls, runs, schedule}: + World{now, sent, log, inbox, work, List.append(&2, K, calls, [call]), runs, schedule} + +# A saga's run stands somewhere new: the newest entry is where it stands. +def add_run(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World, + run: R) -> World: + match world: + case World{now, sent, log, inbox, work, calls, runs, schedule}: + World{now, sent, log, inbox, work, calls, List.append(&2, R, runs, [run]), schedule} + +def with_schedule(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, + world: World, schedule: +List>) -> World: + match world: + case World{now, sent, log, inbox, work, calls, runs, old}: + World{now, sent, log, inbox, work, calls, runs, schedule} + +# A command is to be sent later. +def later(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World, + after: U32, command: C) -> World: + match world: + case World{+now, sent, log, inbox, work, calls, runs, schedule}: + World{now, sent, log, inbox, work, calls, runs, + List.append(&2, Scheduled, schedule, [Scheduled{U32.add(now, after), command}])} + +def send.go(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, world: World, + command: C, +new: +List) -> World: + match world: + case World{+now, sent, log, inbox, work, calls, runs, schedule}: + World{now, List.append(&2, Stamped, sent, [Stamped{now, command}]), + List.append(&2, E, log, new), List.append(&2, E, inbox, new), work, calls, runs, schedule} + +# Sends a command: it joins the commands sent, and the events it records join +# the log and the inbox. `emit` says what a command records, as things stand. +def send( + ~C: Data, ~E: Data, ~W: Data, ~K: Data, ~R: Data, + ~emit: @+w: World -> @+c: C -> +List, + +world: World, +command: C +) -> World: + send.go(C, E, W, K, R, world, command, emit(world, command)) + +# Steps +# ===== + +def at(-T: Data, items: +List, index: Nat) -> Maybe<&2, T>: + match items index: + case Nil{} _: + None{} + case x <> rest 0n: + Some{x} + case x <> rest 1n+p: + at(T, rest, p) + +def without(-T: Data, items: +List, index: Nat) -> +List: + match items index: + case Nil{} _: + [] + case x <> rest 0n: + rest + case x <> rest 1n+p: + x <> without(T, rest, p) + +def due_now.keep(-C: Data, due: Bool, command: C, rest: +List) -> +List: + match due: + case True{}: + command <> rest + case False{}: + rest + + +def due_now(-C: Data, schedule: +List>, +now: U32) -> +List: + match schedule: + case Nil{}: + [] + case Scheduled{due, command} <> rest: + due_now.keep(C, U32.is_le(due, now), command, due_now(C, rest, now)) + +def not_due.keep(-C: Data, due: Bool, entry: Scheduled, rest: +List>) + -> +List>: + match due: + case True{}: + rest + case False{}: + entry <> rest + +# Sends each of the commands, in order. + +def not_due(-C: Data, schedule: +List>, +now: U32) -> +List>: + match schedule: + case Nil{}: + [] + case Scheduled{+due, command} <> rest: + not_due.keep(C, U32.is_le(due, now), Scheduled{due, command}, not_due(C, rest, now)) + +def send_all( + ~C: Data, ~E: Data, ~W: Data, ~K: Data, ~R: Data, + ~emit: @+w: World -> @+c: C -> +List, + commands: +List, +world: World +) -> World: + match commands: + case Nil{}: + world + case +c <> rest: + send_all(~C, ~E, ~W, ~K, ~R, ~emit, rest, send(~C, ~E, ~W, ~K, ~R, ~emit, world, c)) + +def step.react( + ~C: Data, ~E: Data, ~W: Data, ~K: Data, ~R: Data, + ~react: @+w: World -> E -> World, + +world: World, event: Maybe<&2, E> +) -> World: + match event: + case None{}: + world + case Some{e}: + react(world, e) + +def step.advance( + ~C: Data, ~E: Data, ~W: Data, ~K: Data, ~R: Data, + ~advance: @+w: World -> W -> World, + +world: World, work: Maybe<&2, W> +) -> World: + match work: + case None{}: + world + case Some{w}: + advance(world, w) + +def step.pass( + ~C: Data, ~E: Data, ~W: Data, ~K: Data, ~R: Data, + ~emit: @+w: World -> @+c: C -> +List, + +world: World, +now: U32 +) -> World: + send_all(~C, ~E, ~W, ~K, ~R, ~emit, due_now(C, schedule_of(C, E, W, K, R, world), now), + with_schedule(C, E, W, K, R, with_now(C, E, W, K, R, world, now), + not_due(C, schedule_of(C, E, W, K, R, world), now))) + +# One thing happens. +def step( + ~C: Data, ~E: Data, ~W: Data, ~K: Data, ~R: Data, ~A: Data, + ~emit: @+w: World -> @+c: C -> +List, + ~react: @+w: World -> E -> World, + ~advance: @+w: World -> W -> World, + ~answer: @+w: World -> A -> World, + +world: World, move: Move +) -> World: + match move: + case Send{+command}: + send(~C, ~E, ~W, ~K, ~R, ~emit, world, command) + case Deliver{+index}: + step.react(~C, ~E, ~W, ~K, ~R, ~react, + with_inbox(C, E, W, K, R, world, without(E, inbox_of(C, E, W, K, R, world), index)), + at(E, inbox_of(C, E, W, K, R, world), index)) + case Redeliver{seq}: + step.react(~C, ~E, ~W, ~K, ~R, ~react, world, at(E, log_of(C, E, W, K, R, world), seq)) + case Advance{+index}: + step.advance(~C, ~E, ~W, ~K, ~R, ~advance, + with_work(C, E, W, K, R, world, without(W, work_of(C, E, W, K, R, world), index)), + at(W, work_of(C, E, W, K, R, world), index)) + case Answer{given}: + answer(world, given) + # Time passes: every scheduled command that is now due is sent. + case Pass{seconds}: + step.pass(~C, ~E, ~W, ~K, ~R, ~emit, world, + U32.add(now_of(C, E, W, K, R, world), seconds)) + +# The world after every step, in order: nothing is delivered or advanced +# unless a step says so. +def steps( + ~C: Data, ~E: Data, ~W: Data, ~K: Data, ~R: Data, ~A: Data, + ~emit: @+w: World -> @+c: C -> +List, + ~react: @+w: World -> E -> World, + ~advance: @+w: World -> W -> World, + ~answer: @+w: World -> A -> World, + moves: List>, +world: World +) -> World: + match moves: + case Nil{}: + world + case move <> rest: + steps(~C, ~E, ~W, ~K, ~R, ~A, ~emit, ~react, ~advance, ~answer, rest, + step(~C, ~E, ~W, ~K, ~R, ~A, ~emit, ~react, ~advance, ~answer, world, move)) + +# Settling +# ======== + +def is_empty(-T: Data, items: +List) -> Bool: + match items: + case Nil{}: + True{} + case x <> rest: + False{} + +def next.pick(-C: Data, -A: Data, inbox_empty: Bool, work_empty: Bool) -> Maybe<&2, Move>: + match inbox_empty work_empty: + case False{} _: + Some{Deliver{0n}} + case True{} False{}: + Some{Advance{0n}} + case True{} True{}: + None{} + +# What to do next when nobody says: the oldest undelivered event, then the +# oldest saga step. +def next(-C: Data, -E: Data, -W: Data, -K: Data, -R: Data, -A: Data, world: World) + -> Maybe<&2, Move>: + match world: + case World{now, sent, log, inbox, work, calls, runs, schedule}: + next.pick(C, A, is_empty(E, inbox), is_empty(W, work)) + +def settle.go( + ~C: Data, ~E: Data, ~W: Data, ~K: Data, ~R: Data, ~A: Data, + ~emit: @+w: World -> @+c: C -> +List, + ~react: @+w: World -> E -> World, + ~advance: @+w: World -> W -> World, + ~answer: @+w: World -> A -> World, + fuel: Nat, +world: World, move: Maybe<&2, Move> +) -> World: + match fuel move: + case 0n _: + world + case 1n+p None{}: + world + case 1n+p Some{+m}: + settle.go(~C, ~E, ~W, ~K, ~R, ~A, ~emit, ~react, ~advance, ~answer, p, + step(~C, ~E, ~W, ~K, ~R, ~A, ~emit, ~react, ~advance, ~answer, world, m), + next(C, E, W, K, R, A, + step(~C, ~E, ~W, ~K, ~R, ~A, ~emit, ~react, ~advance, ~answer, world, m))) + +def fuel() -> Nat: + 64n + +# The world after a move, once everything that follows from it has run. +def play( + ~C: Data, ~E: Data, ~W: Data, ~K: Data, ~R: Data, ~A: Data, + ~emit: @+w: World -> @+c: C -> +List, + ~react: @+w: World -> E -> World, + ~advance: @+w: World -> W -> World, + ~answer: @+w: World -> A -> World, + +world: World, +move: Move +) -> World: + settle.go(~C, ~E, ~W, ~K, ~R, ~A, ~emit, ~react, ~advance, ~answer, fuel(), + step(~C, ~E, ~W, ~K, ~R, ~A, ~emit, ~react, ~advance, ~answer, world, move), + next(C, E, W, K, R, A, + step(~C, ~E, ~W, ~K, ~R, ~A, ~emit, ~react, ~advance, ~answer, world, move))) + +# The world after every move, each followed by everything that follows from it. +def run( + ~C: Data, ~E: Data, ~W: Data, ~K: Data, ~R: Data, ~A: Data, + ~emit: @+w: World -> @+c: C -> +List, + ~react: @+w: World -> E -> World, + ~advance: @+w: World -> W -> World, + ~answer: @+w: World -> A -> World, + moves: List>, +world: World +) -> World: + match moves: + case Nil{}: + world + case move <> rest: + run(~C, ~E, ~W, ~K, ~R, ~A, ~emit, ~react, ~advance, ~answer, rest, + play(~C, ~E, ~W, ~K, ~R, ~A, ~emit, ~react, ~advance, ~answer, world, move)) diff --git a/packages/alchemy-bend/README.md b/packages/alchemy-bend/README.md new file mode 100644 index 00000000000..cb949ddeaa4 --- /dev/null +++ b/packages/alchemy-bend/README.md @@ -0,0 +1,97 @@ +# alchemy-bend + +A domain model in [Bend 2](https://github.com/bendlang/bend): aggregates as pure functions, rules as laws, and proofs the compiler checks. A prototype, not a published package. + +`examples/bank` is the bank from `examples/cloudflare-domain`. Money is whole cents and time is whole seconds, as there. Ids are numbers. + +| File | What it holds | +|---|---| +| `Domain.bend` | What every aggregate shares: `Decided`, `Sent`, and the templates `apply`, `settle`, `step` and `replay` | +| `Model.bend` | An engine for any model: the world, and the templates `send`, `step`, `play`, `run` and `steps`, which take a model's `emit`, `react`, `advance` and `answer` | +| `examples/bank/Account.bend` | The account: ten commands, `decide`, `evolve` | +| `examples/bank/Transfer.bend` | The transfer, with approval and expiry | +| `examples/bank/Customer.bend` | The customer, the username claim, the registration decision across both, and the registry | +| `examples/bank/Bank.bend` | The bank, given to the engine: its commands, events and saga steps, what a command records, the five policies, the ExecuteTransfer saga one step at a time with its compensation, and the answers from outside systems | +| `examples/bank/Views.bend` | The reads: summary, statement, ledger, activity, account card, dashboard, transfer status, transfers by account, each with who may read it | +| `examples/bank/Api.bend` | What customers and support agents may send | +| `examples/bank/Stories.bend` | The worlds the stories end in, each a sequence of moves | +| `examples/bank/LAWS.bend` | 59 laws: the rules, and what each story leaves | +| `examples/bank/PROOF.bend` | Their proofs | +| `examples/bank/Search.bend` | A search for the shortest sequence of moves that breaks a rule | +| `examples/bank/Server.bend` | The bank over HTTP, kept in a journal file, with pages that are functions of the bank, and a wall clock of its own (`clock.c`, `clock.js`) | +| `examples/bank/durable-object/` | The proved bank on a Cloudflare Durable Object, its journal in the object's storage | +| `examples/bank/host.mjs` | The proved bank driven from JavaScript | + +## Check it + +```sh +curl -fsSL https://bend-lang.com/install.sh | sh +cd examples/bank +bend PROOF.bend # ALL PROOFS CHECK +bend PROOF.bend --verdict # the same, rechecked by the kernel that has a proof in Lean (needs Lean 4.34.0) +bend Search.bend # the rules about a settled bank, and two rules that are false +bend Server.bend # serves http://127.0.0.1:8788, kept in ./bank.journal +bend Server.bend -o build/bank # a native binary; -o build/bank.js for one that bun runs +bend Bank.bend -o build/Bank.mjs && node host.mjs +``` + +## What a step is + +`Bank.step` is one thing that can happen: a caller sends a command, an undelivered event reaches the policies (whichever one), an event already delivered reaches them again, the saga takes its next step (whichever one is ready), an outside system answers, time passes. `Bank.play` is a step and then everything that follows from it. + +## What is proved + +For any sequence of steps: + +- every account is within its daily limit; +- every transfer is between two different accounts; +- a customer is registered under a name exactly when that name is claimed for them, so no two customers hold one name. + +About one command or one decision: + +- a closed account stays closed, a frozen account refuses a withdrawal, and only an agent changes an owner; +- a transfer that ended stays as it ended, and one that waits for approval can always expire; +- a claimed username stays with its holder, a registered customer is not registered again, and the name goes to who registered. + +And: + +- some sequence of moves leaves a customer with money, with the sequence as the witness; +- each of the 22 stories, a law with no parameters proved by running it. Two of them step the saga by hand: the destination closes between the debit and the credit, and a request is delivered three times. + +## What is checked, not proved + +`Search.bend` checks these in every sequence of up to four of nine moves, one of them a redelivery, once the bank has settled: no transfer loses money, none is left pending, and every one has ended once the approval window closes. A rule that is false gives the shortest sequence that breaks it. `@alchemy.run/domain` checks the same rules the same way. + +## The server + +`bend Server.bend` serves the bank and writes each request that changes it to `bank.journal` before applying it. At the start it replays the journal, so the bank is where it was, with every saga where it stood. The clock follows the wall clock, and each move of it is in the journal too. + +A request's path says who asks and what for: `/c/1/account/101/deposit/5000`, `/a/7/transfer/1/approve`, `/c/1/account/101/summary`. The Apis decide what each caller may send, and each read is guarded. `/app/c/1` is customer 1's page and `/app/a/7` an agent's: each is a function of the bank and of who is looking, and each link on it sends a command. A page stays live: it watches `/version` and loads again when anything is recorded. + +```sh +docker build -t bend-bank . && docker run -p 8788:8788 -v bank:/data bend-bank +``` + +### Outside systems + +For each call the bank waits on, the server asks the service at `FRAUD_URL` or `PAYMENTS_URL` (with curl), and writes the answer to the journal as a line of its own, so a replay never asks again. With neither set, stand-ins answer. + +### On a Durable Object + +Bend compiles the bank's pure functions to a JavaScript module, and `durable-object/worker.mjs` hosts them: one object is one writer, its journal is the object's storage, and it replays the journal when it wakes. It calls the outside systems with `fetch`. + +```sh +bend Server.bend -o durable-object/Server.mjs +cd durable-object && npx wrangler dev --local +``` + +This has run locally under workerd, across a restart. It has not been deployed. + +## How it differs from the TypeScript and Lean models + +- **The engine is generic, by templates.** `Model.bend` takes a model's four functions at compile time. A Bend closure is used at most once and there are no type classes, so a policy or a saga is still a function of the world, not a value in a list. +- **State is the commands replayed.** The world keeps every command that was sent. That is what makes a rule about one aggregate a rule about every instance. +- **Ids are numbers,** not strings. +- **Sums wrap.** Money and time are 32-bit, so a sum past 4,294,967,295 wraps. Bend's unbounded numbers are unary, and the proven kernel cannot run stories with six-digit amounts on them. +- **Outside calls are answered in order.** +- **Nothing here has been deployed.** The server runs as a process, in a container, and on a local Durable Object. diff --git a/packages/alchemy-bend/examples/bank/Account.bend b/packages/alchemy-bend/examples/bank/Account.bend new file mode 100644 index 00000000000..03d5e4806ef --- /dev/null +++ b/packages/alchemy-bend/examples/bank/Account.bend @@ -0,0 +1,264 @@ +# A bank account: its state, commands, events and rejections, and the two +# pure functions that define it. + +import Base +import ../../Domain.bend as Domain +import ./Types.bend as T + +type AccountState is Data: + Unopened{} + # frozen: whether it is frozen. day, withdrawn: the day of the last + # withdrawal, and what was withdrawn that day. + Open{customer: Nat, balance: U32, frozen: Bool, day: U32, withdrawn: U32} + Closed{} + +type AccountCommand is Data: + OpenAccount{customer: Nat} + # Hand the account to another customer. Only an agent may. + ChangeOwner{customer: Nat} + DepositMoney{amount: U32} + WithdrawMoney{amount: U32} + FreezeAccount{} + CloseAccount{} + # Take a transfer's money out, on behalf of whoever asked for the transfer. + DebitTransfer{transfer: Nat, amount: U32, requested_by: T.Actor} + CreditTransfer{transfer: Nat, amount: U32} + # Give a transfer's money back. It reports a fact, so it is never rejected. + RefundTransfer{transfer: Nat, amount: U32} + # Money arrived from the payment processor. Never rejected. + RecordSettlement{settlement: Nat, amount: U32} + +type AccountEvent is Data: + AccountOpened{customer: Nat} + OwnerChanged{previous: Nat, customer: Nat} + MoneyDeposited{amount: U32, balance_after: U32} + MoneyWithdrawn{amount: U32, balance_after: U32} + AccountFrozen{} + AccountClosed{} + TransferDebited{transfer: Nat, amount: U32, balance_after: U32} + TransferCredited{transfer: Nat, amount: U32, balance_after: U32} + TransferRefunded{transfer: Nat, amount: U32, balance_after: U32} + # A refund arrived at an account that is no longer open. + RefundStranded{transfer: Nat, amount: U32} + SettlementReceived{settlement: Nat, amount: U32, balance_after: U32} + SettlementOnClosedAccount{settlement: Nat, amount: U32} + +type AccountRejection is Data: + AlreadyOpen{} + NotOpen{} + NotOwner{} + NotPermitted{} + Frozen{} + InsufficientFunds{balance: U32, requested: U32} + DailyLimitExceeded{remaining: U32} + BalanceNotZero{balance: U32} + +def Decided() -> Data: + Domain.Decided + +# The most an account may withdraw in a day, in cents. +def daily_limit() -> U32: + 100000 + +def initial() -> AccountState: + Unopened{} + +# What was withdrawn so far today. +def withdrawn_on(same_day: Bool, withdrawn: U32) -> U32: + match same_day: + case True{}: + withdrawn + case False{}: + 0 + +# Each command on an open account is decided from the checks already made, so +# that a proof can name each check. + +def change_owner.go(agent: Bool, previous: Nat, customer: Nat) -> Decided(): + match agent: + case True{}: + Domain.Record{[OwnerChanged{previous, customer}]} + case False{}: + Domain.Reject{NotPermitted{}} + +def deposit.go(may: Bool, balance: U32, +amount: U32) -> Decided(): + match may: + case True{}: + Domain.Record{[MoneyDeposited{amount, U32.add(balance, amount)}]} + case False{}: + Domain.Reject{NotOwner{}} + +def withdraw.go( + may: Bool, frozen: Bool, enough: Bool, within: Bool, + +balance: U32, +used: U32, +amount: U32 +) -> Decided(): + match may frozen enough within: + case False{} _ _ _: + Domain.Reject{NotOwner{}} + case True{} True{} _ _: + Domain.Reject{Frozen{}} + case True{} False{} False{} _: + Domain.Reject{InsufficientFunds{balance, amount}} + case True{} False{} True{} False{}: + Domain.Reject{DailyLimitExceeded{U32.sub(daily_limit(), used)}} + case True{} False{} True{} True{}: + Domain.Record{[MoneyWithdrawn{amount, U32.sub(balance, amount)}]} + +def freeze.go(may: Bool, frozen: Bool) -> Decided(): + match may frozen: + case False{} _: + Domain.Reject{NotOwner{}} + case True{} True{}: + Domain.Record{[]} + case True{} False{}: + Domain.Record{[AccountFrozen{}]} + +def close.go(may: Bool, empty: Bool, balance: U32) -> Decided(): + match may empty: + case False{} _: + Domain.Reject{NotOwner{}} + case True{} False{}: + Domain.Reject{BalanceNotZero{balance}} + case True{} True{}: + Domain.Record{[AccountClosed{}]} + +def debit.go( + may: Bool, frozen: Bool, enough: Bool, transfer: Nat, +balance: U32, +amount: U32 +) -> Decided(): + match may frozen enough: + case False{} _ _: + Domain.Reject{NotOwner{}} + case True{} True{} _: + Domain.Reject{Frozen{}} + case True{} False{} False{}: + Domain.Reject{InsufficientFunds{balance, amount}} + case True{} False{} True{}: + Domain.Record{[TransferDebited{transfer, amount, U32.sub(balance, amount)}]} + +# A command on an account that is not open. +def decide.not_open(unopened: Bool, command: AccountCommand) -> Decided(): + match unopened command: + case True{} OpenAccount{customer}: + Domain.Record{[AccountOpened{customer}]} + case False{} OpenAccount{customer}: + Domain.Reject{AlreadyOpen{}} + case _ RefundTransfer{transfer, amount}: + Domain.Record{[RefundStranded{transfer, amount}]} + case _ RecordSettlement{settlement, amount}: + Domain.Record{[SettlementOnClosedAccount{settlement, amount}]} + case _ _: + Domain.Reject{NotOpen{}} + +# A command on an open account. +def decide.open( + +actor: T.Actor, +today: U32, + +customer: Nat, +balance: U32, +frozen: Bool, day: U32, withdrawn: U32, + command: AccountCommand +) -> Decided(): + match command: + case OpenAccount{_}: + Domain.Reject{AlreadyOpen{}} + case ChangeOwner{to}: + change_owner.go(T.is_agent(actor), customer, to) + case DepositMoney{amount}: + deposit.go(T.may_act(actor, customer), balance, amount) + case WithdrawMoney{+amount}: + +used = withdrawn_on(U32.is_eq(day, today), withdrawn) + withdraw.go( + T.may_act(actor, customer), frozen, U32.is_le(amount, balance), + U32.is_le(U32.add(used, amount), daily_limit()), + balance, used, amount) + case FreezeAccount{}: + freeze.go(T.may_act(actor, customer), frozen) + case CloseAccount{}: + close.go(T.may_act(actor, customer), U32.is_eq(balance, 0), balance) + case DebitTransfer{transfer, +amount, requested_by}: + debit.go(T.may_act(requested_by, customer), frozen, U32.is_le(amount, balance), + transfer, balance, amount) + case CreditTransfer{transfer, +amount}: + Domain.Record{[TransferCredited{transfer, amount, U32.add(balance, amount)}]} + case RefundTransfer{transfer, +amount}: + Domain.Record{[TransferRefunded{transfer, amount, U32.add(balance, amount)}]} + case RecordSettlement{settlement, +amount}: + Domain.Record{[SettlementReceived{settlement, amount, U32.add(balance, amount)}]} + +def decide(context: T.Context, state: AccountState, command: AccountCommand) -> Decided(): + match context state: + case T.Context{actor, today} Unopened{}: + decide.not_open(True{}, command) + case T.Context{actor, today} Closed{}: + decide.not_open(False{}, command) + case T.Context{actor, today} Open{customer, balance, frozen, day, withdrawn}: + decide.open(actor, today, customer, balance, frozen, day, withdrawn, command) + +# Events carry the outcome decide worked out, so evolve only copies it. +def evolve.open( + +today: U32, customer: Nat, balance: U32, frozen: Bool, day: U32, withdrawn: U32, + event: AccountEvent +) -> AccountState: + match event: + case OwnerChanged{previous, to}: + Open{to, balance, frozen, day, withdrawn} + case MoneyDeposited{amount, after}: + Open{customer, after, frozen, day, withdrawn} + case MoneyWithdrawn{amount, after}: + Open{customer, after, frozen, today, + U32.add(withdrawn_on(U32.is_eq(day, today), withdrawn), amount)} + case AccountFrozen{}: + Open{customer, balance, True{}, day, withdrawn} + case AccountClosed{}: + Closed{} + case TransferDebited{transfer, amount, after}: + Open{customer, after, frozen, day, withdrawn} + case TransferCredited{transfer, amount, after}: + Open{customer, after, frozen, day, withdrawn} + case TransferRefunded{transfer, amount, after}: + Open{customer, after, frozen, day, withdrawn} + case SettlementReceived{settlement, amount, after}: + Open{customer, after, frozen, day, withdrawn} + case _: + Open{customer, balance, frozen, day, withdrawn} + +def evolve.unopened(event: AccountEvent) -> AccountState: + match event: + case AccountOpened{customer}: + Open{customer, 0, False{}, 0, 0} + case _: + Unopened{} + +def evolve(context: T.Context, state: AccountState, event: AccountEvent) -> AccountState: + match context state: + case T.Context{actor, today} Unopened{}: + evolve.unopened(event) + case T.Context{actor, today} Closed{}: + Closed{} + case T.Context{actor, today} Open{customer, balance, frozen, day, withdrawn}: + evolve.open(today, customer, balance, frozen, day, withdrawn, event) + +def Sent() -> Data: + Domain.Sent + +# The state after one command: unchanged when the command is rejected. +def step(+context: T.Context, +state: AccountState, command: AccountCommand) -> AccountState: + Domain.step(~T.Context, ~AccountState, ~AccountCommand, ~AccountEvent, ~AccountRejection, + ~decide, ~evolve, context, state, command) + +# The state after every command, in order. +def replay(commands: List, +state: AccountState) -> AccountState: + Domain.replay(~T.Context, ~AccountState, ~AccountCommand, ~AccountEvent, ~AccountRejection, + ~decide, ~evolve, commands, state) + +# RULE: an open account has withdrawn no more than the daily limit. +def within_limit(state: AccountState) -> Bool: + match state: + case Open{customer, balance, frozen, day, withdrawn}: + U32.is_le(withdrawn, daily_limit()) + case _: + True{} + +def is_closed(state: AccountState) -> Bool: + match state: + case Closed{}: + True{} + case _: + False{} diff --git a/packages/alchemy-bend/examples/bank/Api.bend b/packages/alchemy-bend/examples/bank/Api.bend new file mode 100644 index 00000000000..0bd5344c8b3 --- /dev/null +++ b/packages/alchemy-bend/examples/bank/Api.bend @@ -0,0 +1,37 @@ +# The Apis: what each audience may send. Who is asking is the actor each move +# carries, so a session is an argument, not a setting. + +import Base +import ./Types.bend as T +import ./Account.bend as Account +import ./Transfer.bend as Transfer +import ./Customer.bend as Customer +import ./Bank.bend as Bank + +# What customers may send: register, deposit, withdraw, close, ask for a transfer. +def customer_api(move: Bank.Move) -> Bool: + match move: + case Bank.Register{actor, command}: + True{} + case Bank.ToAccount{id, actor, Account.DepositMoney{amount}}: + True{} + case Bank.ToAccount{id, actor, Account.WithdrawMoney{amount}}: + True{} + case Bank.ToAccount{id, actor, Account.CloseAccount{}}: + True{} + case Bank.ToTransfer{id, actor, Transfer.RequestTransfer{source, destination, amount}}: + True{} + case _: + False{} + +# What support agents may send: freeze, reassign, approve. +def support_api(move: Bank.Move) -> Bool: + match move: + case Bank.ToAccount{id, actor, Account.FreezeAccount{}}: + True{} + case Bank.ToAccount{id, actor, Account.ChangeOwner{customer}}: + True{} + case Bank.ToTransfer{id, actor, Transfer.ApproveTransfer{}}: + True{} + case _: + False{} diff --git a/packages/alchemy-bend/examples/bank/Bank.bend b/packages/alchemy-bend/examples/bank/Bank.bend new file mode 100644 index 00000000000..e73d47ac5a4 --- /dev/null +++ b/packages/alchemy-bend/examples/bank/Bank.bend @@ -0,0 +1,562 @@ +# The bank: every aggregate, the registration decision, the policies, the +# ExecuteTransfer saga, the calls to outside systems and the clock. +# +# The bank says what its commands, events, saga steps and outside calls are, +# and gives the engine in Model.bend four functions: what a command records +# (`emit`), what the policies do about an event (`react`), what a saga step +# does (`advance`), and what an answer from outside does (`answer`). The +# engine gives back the world, `step`, `play` and `run`. + +import Base +import ../../Domain.bend as Domain +import ../../Model.bend as Model +import ./Types.bend as T +import ./Account.bend as Account +import ./Transfer.bend as Transfer +import ./Customer.bend as Customer + +# A command, with who sends it and to what. +type Command is Data: + ForAccount{id: Nat, actor: T.Actor, command: Account.AccountCommand} + ForTransfer{id: Nat, actor: T.Actor, command: Transfer.TransferCommand} + # The registration decision: it records on a customer and on a username. + ForRegistration{actor: T.Actor, command: Customer.RegisterCustomer} + +# An event one instance recorded. An account's says when, and where it sits in +# the log. +type Emitted is Data: + FromAccount{id: Nat, event: Account.AccountEvent, time: U32, seq: Nat} + FromTransfer{id: Nat, event: Transfer.TransferEvent} + FromCustomer{id: Nat, event: Customer.CustomerEvent} + FromClaim{username: Nat, event: Customer.ClaimEvent} + +# A call to a system outside the bank, waiting for its answer. +type Call is Data: + # FraudCheck.score + FraudScore{account: Nat, total: U32} + # Payments.refund + Refund{settlement: Nat, amount: U32} + +# What a system outside the bank answers. It answers the oldest waiting call, +# if that call is one of its own. +type Answer is Data: + FraudAnswer{risk: Nat} + RefundAnswer{} + +# The next step of the ExecuteTransfer saga for one transfer. +type Work is Data: + Debit{transfer: Nat, details: Transfer.Details} + Credit{transfer: Nat, details: Transfer.Details} + # The compensation: give back what was debited. + GiveBack{transfer: Nat, details: Transfer.Details} + Complete{transfer: Nat} + Abort{transfer: Nat, reason: Transfer.Reason} + +# Where the saga stands for one transfer. +type Run is Data: + WaitingForApproval{} + Running{} + Finished{} + FailedBecause{reason: Transfer.Reason} + +type SagaRun is Data: + SagaRun{transfer: Nat, run: Run} + +def World() -> Data: + Model.World + +def start() -> World(): + Model.start(Command, Emitted, Work, Call, SagaRun) + +# What the policies and the saga act as. +def system() -> T.Actor: + T.BySystem{0n} + +# The account opened for a customer when they register. +def main_account(customer: Nat) -> Nat: + Nat.add(100n, customer) + +# How long a support agent has to approve a large transfer: 24 hours. +def approval_window() -> U32: + 86400 + +# Daily outflow above which an account's activity is reviewed, in cents. +def review_threshold() -> U32: + 50000 + +# The fraud score above which an account is frozen, out of 100. +def risk_limit() -> Nat: + 80n + +# Reading the world +# ================= + +def now_of(world: World()) -> U32: + Model.now_of(Command, Emitted, Work, Call, SagaRun, world) + +def sent_of(world: World()) -> +List>: + Model.sent_of(Command, Emitted, Work, Call, SagaRun, world) + +def log_of(world: World()) -> +List: + Model.log_of(Command, Emitted, Work, Call, SagaRun, world) + +def calls_of(world: World()) -> +List: + Model.calls_of(Command, Emitted, Work, Call, SagaRun, world) + +def account_sends.keep(same: Bool, sent: Account.Sent(), rest: List) + -> List: + match same: + case True{}: + sent <> rest + case False{}: + rest + +# The commands one account was sent, in order, each with its context. +def account_sends(sent: +List>, +id: Nat) -> List: + match sent: + case Nil{}: + [] + case Model.Stamped{time, ForAccount{to, actor, command}} <> rest: + account_sends.keep(Nat.is_eq(to, id), + Domain.Sent{T.Context{actor, T.day(time)}, command}, account_sends(rest, id)) + case _ <> rest: + account_sends(rest, id) + +# An account's state: the commands it was sent, replayed. +def account(world: World(), id: Nat) -> Account.AccountState: + Account.replay(account_sends(sent_of(world), id), Account.initial()) + +def transfer_sends.keep(same: Bool, sent: Transfer.Sent(), rest: List) + -> List: + match same: + case True{}: + sent <> rest + case False{}: + rest + +def transfer_sends(sent: +List>, +id: Nat) -> List: + match sent: + case Nil{}: + [] + case Model.Stamped{time, ForTransfer{to, actor, command}} <> rest: + transfer_sends.keep(Nat.is_eq(to, id), + Domain.Sent{T.Context{actor, T.day(time)}, command}, transfer_sends(rest, id)) + case _ <> rest: + transfer_sends(rest, id) + +# A transfer's state: the commands it was sent, replayed. +def transfer(world: World(), id: Nat) -> Transfer.TransferState: + Transfer.replay(transfer_sends(sent_of(world), id), Transfer.initial()) + +def registrations(sent: +List>, newest: +List) + -> +List: + match sent: + case Nil{}: + newest + case Model.Stamped{time, ForRegistration{actor, command}} <> rest: + registrations(rest, Customer.Registering{actor, command} <> newest) + case _ <> rest: + registrations(rest, newest) + +# Every registration that was sent, newest first. +def registrations_of(world: World()) -> +List: + registrations(sent_of(world), []) + +# A customer's state: the registrations that were sent, decided in order. +def customer(world: World(), id: Nat) -> Customer.CustomerState: + Customer.customer_of(registrations_of(world), id) + +def claim(world: World(), username: Nat) -> Customer.ClaimState: + Customer.claim_of(registrations_of(world), username) + +def run_in.pick(same: Bool, found: Run, earlier: Maybe<&2, Run>) -> Maybe<&2, Run>: + match same: + case True{}: + Some{found} + case False{}: + earlier + +def run_in(sagas: +List, +id: Nat, found: Maybe<&2, Run>) -> Maybe<&2, Run>: + match sagas: + case Nil{}: + found + case SagaRun{transfer, run} <> rest: + run_in(rest, id, run_in.pick(Nat.is_eq(transfer, id), run, found)) + +# Where the saga stands for a transfer: None when it never started. +def saga(world: World(), id: Nat) -> Maybe<&2, Run>: + run_in(Model.runs_of(Command, Emitted, Work, Call, SagaRun, world), id, None{}) + +def add_work(world: World(), next: Work) -> World(): + Model.add_work(Command, Emitted, Work, Call, SagaRun, world, next) + +def add_call(world: World(), call: Call) -> World(): + Model.add_call(Command, Emitted, Work, Call, SagaRun, world, call) + +def with_calls(world: World(), calls: +List) -> World(): + Model.with_calls(Command, Emitted, Work, Call, SagaRun, world, calls) + +# A transfer's run stands here from now on. +def set_run(world: World(), id: Nat, run: Run) -> World(): + Model.add_run(Command, Emitted, Work, Call, SagaRun, world, SagaRun{id, run}) + +# What commands record +# ==================== + +def emit_account(events: +List, +id: Nat, +time: U32, +seq: Nat) + -> +List: + match events: + case Nil{}: + [] + case e <> rest: + FromAccount{id, e, time, seq} <> emit_account(rest, id, time, 1n+seq) + +def emit_transfer(events: +List, +id: Nat) -> +List: + match events: + case Nil{}: + [] + case e <> rest: + FromTransfer{id, e} <> emit_transfer(rest, id) + +def events_of(decided: Account.Decided()) -> +List: + match decided: + case Domain.Reject{why}: + [] + case Domain.Record{events}: + events + +def transfer_events_of(decided: Transfer.Decided()) -> +List: + match decided: + case Domain.Reject{why}: + [] + case Domain.Record{events}: + events + +# The context a command is sent in now. +def context(world: World(), actor: T.Actor) -> T.Context: + T.Context{actor, T.day(now_of(world))} + +# What an account answers a command, as things stand. +def ask_account(+world: World(), +id: Nat, actor: T.Actor, command: Account.AccountCommand) + -> Account.Decided(): + Account.decide(context(world, actor), account(world, id), command) + +def ask_transfer(+world: World(), +id: Nat, actor: T.Actor, command: Transfer.TransferCommand) + -> Transfer.Decided(): + Transfer.decide(context(world, actor), transfer(world, id), command) + +# What a registration answers, as things stand. +def ask_register(+world: World(), actor: T.Actor, command: Customer.RegisterCustomer) + -> Customer.Registration: + match command: + case Customer.RegisterCustomer{+id, +username}: + Customer.register(actor, customer(world, id), claim(world, username), + Customer.RegisterCustomer{id, username}) + +def emit_registration(id: Nat, username: Nat, registration: Customer.Registration) + -> +List: + match registration: + case Customer.Refused{why}: + [] + case Customer.Accepted{on_customer, on_claim}: + [FromCustomer{id, on_customer}, FromClaim{username, on_claim}] + +# What a command records, as things stand: nothing, when it is rejected. +def emit(+world: World(), +command: Command) -> +List: + match command: + case ForAccount{+id, actor, command}: + emit_account(events_of(ask_account(world, id, actor, command)), id, now_of(world), + List.length(&2, Emitted, log_of(world))) + case ForTransfer{+id, actor, command}: + emit_transfer(transfer_events_of(ask_transfer(world, id, actor, command)), id) + case ForRegistration{actor, Customer.RegisterCustomer{+id, +username}}: + emit_registration(id, username, + ask_register(world, actor, Customer.RegisterCustomer{id, username})) + +def send(+world: World(), +command: Command) -> World(): + Model.send(~Command, ~Emitted, ~Work, ~Call, ~SagaRun, ~emit, world, command) + +def send_account(+world: World(), id: Nat, actor: T.Actor, command: Account.AccountCommand) + -> World(): + send(world, ForAccount{id, actor, command}) + +def send_transfer(+world: World(), id: Nat, actor: T.Actor, command: Transfer.TransferCommand) + -> World(): + send(world, ForTransfer{id, actor, command}) + +# The ExecuteTransfer saga +# ======================== +# +# Moves money between two accounts on behalf of the requester: debits the +# source, credits the destination, and refunds the debit if the credit fails. +# The outcome is recorded on the Transfer either way. Each step is taken on +# its own, so anything may happen between two of them. + +# Why a debit was refused, as a reason the transfer failed. +def why_not_debited(why: Account.AccountRejection) -> Transfer.Reason: + match why: + case Account.NotOpen{}: + Transfer.SourceNotOpen{} + case Account.NotOwner{}: + Transfer.NotYourAccount{} + case Account.Frozen{}: + Transfer.SourceFrozen{} + case Account.InsufficientFunds{balance, requested}: + Transfer.InsufficientFunds{} + case _: + Transfer.Refused{} + +def debit.next(world: World(), +id: Nat, details: Transfer.Details, answer: Account.Decided()) + -> World(): + match answer: + case Domain.Reject{why}: + add_work(world, Abort{id, why_not_debited(why)}) + case Domain.Record{events}: + add_work(world, Credit{id, details}) + +def credit.next(world: World(), +id: Nat, details: Transfer.Details, answer: Account.Decided()) + -> World(): + match answer: + case Domain.Reject{why}: + add_work(world, GiveBack{id, details}) + case Domain.Record{events}: + add_work(world, Complete{id}) + +# One step of the saga. +def advance(+world: World(), work: Work) -> World(): + match work: + # Debit first: if the credit fails, the money is refunded, so it is never created. + case Debit{+id, Transfer.Details{+source, +destination, +amount, +by}}: + debit.next( + send_account(world, source, system(), Account.DebitTransfer{id, amount, by}), + id, Transfer.Details{source, destination, amount, by}, + ask_account(world, source, system(), Account.DebitTransfer{id, amount, by})) + case Credit{+id, Transfer.Details{+source, +destination, +amount, +by}}: + credit.next( + send_account(world, destination, system(), Account.CreditTransfer{id, amount}), + id, Transfer.Details{source, destination, amount, by}, + ask_account(world, destination, system(), Account.CreditTransfer{id, amount})) + case GiveBack{+id, Transfer.Details{source, destination, amount, by}}: + add_work(send_account(world, source, system(), Account.RefundTransfer{id, amount}), + Abort{id, Transfer.DestinationNotOpen{}}) + case Complete{+id}: + set_run(send_transfer(world, id, system(), Transfer.CompleteTransfer{}), id, Finished{}) + case Abort{+id, +reason}: + set_run(send_transfer(world, id, system(), Transfer.FailTransfer{reason}), id, + FailedBecause{reason}) + +# Policies +# ======== + +# TransferExecution and TransferApprovalDeadline, for a transfer whose run has +# not started: a small one starts at once; a large one waits, and is set to +# expire if nobody approves it in time. An event delivered twice starts nothing. +def on_requested( + +world: World(), +id: Nat, details: Transfer.Details, needs_approval: Bool, + run: Maybe<&2, Run> +) -> World(): + match needs_approval run: + case _ Some{earlier}: + world + case False{} None{}: + add_work(set_run(world, id, Running{}), Debit{id, details}) + case True{} None{}: + Model.later(Command, Emitted, Work, Call, SagaRun, set_run(world, id, WaitingForApproval{}), + approval_window(), ForTransfer{id, system(), Transfer.ExpireTransfer{}}) + +# An approval starts the run that waited for it, once. +def on_approved(+world: World(), +id: Nat, details: Transfer.Details, run: Maybe<&2, Run>) -> World(): + match run: + case Some{WaitingForApproval{}}: + add_work(set_run(world, id, Running{}), Debit{id, details}) + case _: + world + +# A transfer that expired while its run waited ends the run. +def on_failed(+world: World(), +id: Nat, run: Maybe<&2, Run>) -> World(): + match run: + case Some{WaitingForApproval{}}: + set_run(world, id, Finished{}) + case _: + world + +def react_transfer(+world: World(), +id: Nat, event: Transfer.TransferEvent) -> World(): + match event: + case Transfer.TransferRequested{details, needs_approval}: + on_requested(world, id, details, needs_approval, saga(world, id)) + case Transfer.TransferApproved{details, approved_by}: + on_approved(world, id, details, saga(world, id)) + case Transfer.TransferFailed{reason}: + on_failed(world, id, saga(world, id)) + case Transfer.TransferCompleted{}: + world + +def outflow.one(counts: Bool, event: Account.AccountEvent) -> U32: + match counts event: + case True{} Account.MoneyWithdrawn{amount, after}: + amount + case True{} Account.TransferDebited{transfer, amount, after}: + amount + case _ _: + 0 + +# DailyOutflow: the money out of an account on a day. +def outflow(log: +List, +id: Nat, +day: U32) -> U32: + match log: + case Nil{}: + 0 + case FromAccount{on, event, time, seq} <> rest: + U32.add(outflow.one(Nat.is_eq(on, id) && U32.is_eq(T.day(time), day), event), + outflow(rest, id, day)) + case _ <> rest: + outflow(rest, id, day) + +def take(log: +List, n: Nat) -> +List: + match log n: + case Nil{} _: + [] + case e <> rest 0n: + [] + case e <> rest 1n+p: + e <> take(rest, p) + +def review.go(world: World(), crossed: Bool, id: Nat, total: U32) -> World(): + match crossed: + case True{}: + add_call(world, FraudScore{id, total}) + case False{}: + world + +# FraudReview: when an account's outflow for the day crosses the threshold, +# ask the fraud system to score it. Split withdrawals are caught too. +def review(+world: World(), +id: Nat, +amount: U32, +time: U32, seq: Nat) -> World(): + +before = outflow(take(log_of(world), seq), id, T.day(time)) + review.go(world, + U32.is_lt(before, review_threshold()) && U32.is_le(review_threshold(), U32.add(before, amount)), + id, U32.add(before, amount)) + +def react_account(+world: World(), +id: Nat, event: Account.AccountEvent, +time: U32, seq: Nat) + -> World(): + match event: + case Account.MoneyWithdrawn{amount, after}: + review(world, id, amount, time, seq) + case Account.TransferDebited{transfer, amount, after}: + review(world, id, amount, time, seq) + # SettlementRefund: money that settles on a closed account is refunded. + case Account.SettlementOnClosedAccount{settlement, amount}: + add_call(world, Refund{settlement, amount}) + case _: + world + +# What the policies do about one event. +def react(+world: World(), event: Emitted) -> World(): + match event: + # MainAccountProvisioning: whenever a customer registers, open their main account. + case FromCustomer{+id, Customer.CustomerRegistered{username}}: + send_account(world, main_account(id), system(), Account.OpenAccount{id}) + case FromClaim{username, e}: + world + case FromTransfer{id, e}: + react_transfer(world, id, e) + case FromAccount{id, e, time, seq}: + react_account(world, id, e, time, seq) + +# Answers from outside +# ==================== + +def answer_fraud.freeze(+world: World(), risky: Bool, account: Nat) -> World(): + match risky: + case True{}: + send_account(world, account, system(), Account.FreezeAccount{}) + case False{}: + world + +def answer_fraud(+world: World(), calls: +List, risk: Nat) -> World(): + match calls: + case FraudScore{account, total} <> rest: + answer_fraud.freeze(with_calls(world, rest), Nat.is_lt(risk_limit(), risk), account) + case _: + world + +def answer_refund(+world: World(), calls: +List) -> World(): + match calls: + case Refund{settlement, amount} <> rest: + with_calls(world, rest) + case _: + world + +def answer(+world: World(), given: Answer) -> World(): + match given: + case FraudAnswer{risk}: + answer_fraud(world, calls_of(world), risk) + case RefundAnswer{}: + answer_refund(world, calls_of(world)) + +# Moves +# ===== + +# What can happen to the bank, one thing at a time. +type Move is Data: + ToAccount{id: Nat, actor: T.Actor, command: Account.AccountCommand} + ToTransfer{id: Nat, actor: T.Actor, command: Transfer.TransferCommand} + Register{actor: T.Actor, command: Customer.RegisterCustomer} + # The undelivered event at this place in the inbox reaches the policies. + Deliver{index: Nat} + # A fault: the event at this place in the log reaches the policies again. + Redeliver{seq: Nat} + # The saga step at this place in the work takes place. + Advance{index: Nat} + # The fraud system answers the oldest waiting call, if it is one of its own. + AnswerFraud{risk: Nat} + # The payment processor answers the oldest waiting call, if it is one of its own. + AnswerRefund{} + Pass{seconds: U32} + +# The move, as the engine takes it. +def to_model(move: Move) -> Model.Move: + match move: + case ToAccount{id, actor, command}: + Model.Send{ForAccount{id, actor, command}} + case ToTransfer{id, actor, command}: + Model.Send{ForTransfer{id, actor, command}} + case Register{actor, command}: + Model.Send{ForRegistration{actor, command}} + case Deliver{index}: + Model.Deliver{index} + case Redeliver{seq}: + Model.Redeliver{seq} + case Advance{index}: + Model.Advance{index} + case AnswerFraud{risk}: + Model.Answer{FraudAnswer{risk}} + case AnswerRefund{}: + Model.Answer{RefundAnswer{}} + case Pass{seconds}: + Model.Pass{seconds} + +# One thing happens. +def step(+world: World(), move: Move) -> World(): + Model.step(~Command, ~Emitted, ~Work, ~Call, ~SagaRun, ~Answer, ~emit, ~react, ~advance, ~answer, + world, to_model(move)) + +# The world after a move, once everything that follows from it has run. +def play(+world: World(), move: Move) -> World(): + Model.play(~Command, ~Emitted, ~Work, ~Call, ~SagaRun, ~Answer, ~emit, ~react, ~advance, ~answer, + world, to_model(move)) + +# The world after every step, in order: nothing is delivered or advanced +# unless a step says so. +def steps(moves: List, +world: World()) -> World(): + match moves: + case Nil{}: + world + case move <> rest: + steps(rest, step(world, move)) + +# The world after every move, each followed by everything that follows from it. +def run(moves: List, +world: World()) -> World(): + match moves: + case Nil{}: + world + case move <> rest: + run(rest, play(world, move)) diff --git a/packages/alchemy-bend/examples/bank/Customer.bend b/packages/alchemy-bend/examples/bank/Customer.bend new file mode 100644 index 00000000000..ef74e568d5f --- /dev/null +++ b/packages/alchemy-bend/examples/bank/Customer.bend @@ -0,0 +1,208 @@ +# A customer, a username, and the decision that registers one under the other. + +import Base +import ./Types.bend as T + +type CustomerState is Data: + New{} + Registered{username: Nat} + +type CustomerEvent is Data: + CustomerRegistered{username: Nat} + +# A customer decides nothing alone: registering involves the username too, so +# the Registration decision records CustomerRegistered here. +def evolve_customer(state: CustomerState, event: CustomerEvent) -> CustomerState: + match event: + case CustomerRegistered{username}: + Registered{username} + +# One username, and who holds it. Uniqueness spans every customer, so the +# rule has an aggregate of its own, keyed by the username. +type ClaimState is Data: + Free{} + Claimed{customer: Nat} + +type ClaimEvent is Data: + UsernameClaimed{customer: Nat} + +def evolve_claim(state: ClaimState, event: ClaimEvent) -> ClaimState: + match event: + case UsernameClaimed{customer}: + Claimed{customer} + +# Registration +# ============ + +type RegisterCustomer is Data: + RegisterCustomer{customer: Nat, username: Nat} + +type RegistrationRejection is Data: + AlreadyRegistered{} + # A customer may only register themselves. + NotTheCustomer{} + # Someone else holds this username. + UsernameTaken{} + +# What a registration answers: both events, or a rejection. Never one event. +type Registration is Data: + Refused{why: RegistrationRejection} + Accepted{on_customer: CustomerEvent, on_claim: ClaimEvent} + +def is_registered(state: CustomerState) -> Bool: + match state: + case New{}: + False{} + case Registered{username}: + True{} + +def is_claimed(state: ClaimState) -> Bool: + match state: + case Free{}: + False{} + case Claimed{customer}: + True{} + +def register.go(may: Bool, registered: Bool, taken: Bool, +customer: Nat, username: Nat) + -> Registration: + match may registered taken: + case False{} _ _: + Refused{NotTheCustomer{}} + case True{} True{} _: + Refused{AlreadyRegistered{}} + case True{} False{} True{}: + Refused{UsernameTaken{}} + case True{} False{} False{}: + Accepted{CustomerRegistered{username}, UsernameClaimed{customer}} + +# Register a customer and claim their username together: it reads both +# instances, and records on both or on neither. +def register(actor: T.Actor, customer: CustomerState, claim: ClaimState, command: RegisterCustomer) + -> Registration: + match command: + case RegisterCustomer{+id, username}: + register.go(T.may_act(actor, id), is_registered(customer), is_claimed(claim), id, username) + +# The customer after a registration. +def customer_after(state: CustomerState, registration: Registration) -> CustomerState: + match registration: + case Refused{why}: + state + case Accepted{on_customer, on_claim}: + evolve_customer(state, on_customer) + +# The username after a registration. +def claim_after(state: ClaimState, registration: Registration) -> ClaimState: + match registration: + case Refused{why}: + state + case Accepted{on_customer, on_claim}: + evolve_claim(state, on_claim) + +# The registry +# ============ +# +# Every registration that was sent, newest first. A customer's state and a +# username's state are those registrations decided in order, so a rule proved +# for every list of registrations holds for every bank. + +type Registering is Data: + Registering{actor: T.Actor, command: RegisterCustomer} + +# What one customer or one username holds: a customer holds the name they +# registered under, and a username holds the customer it is claimed for. +type Slot is Data: + Vacant{} + Holds{value: Nat} + +def is_held(slot: Slot) -> Bool: + match slot: + case Vacant{}: + False{} + case Holds{value}: + True{} + +def is_accepted(registration: Registration) -> Bool: + match registration: + case Refused{why}: + False{} + case Accepted{on_customer, on_claim}: + True{} + +def pick(first: Bool, a: Nat, b: Nat) -> Nat: + match first: + case True{}: + a + case False{}: + b + +def slot_next(accepted: Bool, hit: Bool, value: Nat, earlier: Slot) -> Slot: + match accepted hit: + case True{} True{}: + Holds{value} + case _ _: + earlier + +# What a customer (of_customer) or a username holds after the registrations. +def slot(sent: +List, +of_customer: Bool, +key: Nat) -> Slot: + match sent: + case Nil{}: + Vacant{} + case Registering{actor, RegisterCustomer{+id, +username}} <> +older: + slot_next( + is_accepted(register.go(T.may_act(actor, id), is_held(slot(older, True{}, id)), + is_held(slot(older, False{}, username)), id, username)), + Nat.is_eq(pick(of_customer, id, username), key), + pick(of_customer, username, id), + slot(older, of_customer, key)) + +def customer_from(slot: Slot) -> CustomerState: + match slot: + case Vacant{}: + New{} + case Holds{value}: + Registered{value} + +def claim_from(slot: Slot) -> ClaimState: + match slot: + case Vacant{}: + Free{} + case Holds{value}: + Claimed{value} + +# A customer's state, after the registrations. +def customer_of(sent: +List, id: Nat) -> CustomerState: + customer_from(slot(sent, True{}, id)) + +# A username's state, after the registrations. +def claim_of(sent: +List, name: Nat) -> ClaimState: + claim_from(slot(sent, False{}, name)) + +def holds(slot: Slot, what: Nat) -> Bool: + match slot: + case Vacant{}: + False{} + case Holds{value}: + Nat.is_eq(value, what) + +# b, when the flag is up. +def when(flag: Bool, b: Bool) -> Bool: + match flag: + case True{}: + b + case False{}: + False{} + +def same(a: Bool, b: Bool) -> Bool: + match a b: + case True{} True{}: + True{} + case False{} False{}: + True{} + case _ _: + False{} + +# RULE: a customer is registered under a name exactly when the name is claimed +# for that customer. +def names_agree(+sent: +List, +id: Nat, +name: Nat) -> Bool: + same(holds(slot(sent, True{}, id), name), holds(slot(sent, False{}, name), id)) diff --git a/packages/alchemy-bend/examples/bank/LAWS.bend b/packages/alchemy-bend/examples/bank/LAWS.bend new file mode 100644 index 00000000000..becba448939 --- /dev/null +++ b/packages/alchemy-bend/examples/bank/LAWS.bend @@ -0,0 +1,377 @@ +# The rules of the bank. A person states them; PROOF.bend must prove them. + +import Base +import ../../Domain.bend as Domain +import ./Types.bend as T +import ./Account.bend as Account +import ./Transfer.bend as Transfer +import ./Customer.bend as Customer +import ./Bank.bend as Bank +import ./Views.bend as Views +import ./Stories.bend as Stories +import ./Api.bend as Api + +# The account +# =========== + +# RULE: whatever an account is sent, by whoever, on whatever days, it never +# withdraws more than the daily limit in a day. +law within_daily_limit: + for commands: List + {Account.within_limit(Account.replay(commands, Account.initial())) == True{} : Bool} + +# RULE: a closed account stays closed, whatever it is sent. +law a_closed_account_stays_closed: + for context: T.Context + for command: Account.AccountCommand + {Account.step(context, Account.Closed{}, command) == Account.Closed{} : Account.AccountState} + +# RULE: only an agent changes who an account belongs to. +law only_an_agent_changes_the_owner: + for customer: Nat + for day: U32 + for state: Account.AccountState + for to: Nat + {Account.step(T.Context{T.ByCustomer{customer}, day}, state, Account.ChangeOwner{to}) == state + : Account.AccountState} + +# RULE: a frozen account pays nothing out. +law a_frozen_account_refuses_a_withdrawal: + for context: T.Context + for customer: Nat + for balance: U32 + for day: U32 + for withdrawn: U32 + for amount: U32 + {Account.step(context, Account.Open{customer, balance, True{}, day, withdrawn}, + Account.WithdrawMoney{amount}) + == Account.Open{customer, balance, True{}, day, withdrawn} : Account.AccountState} + +# The transfer +# ============ + +# RULE: a transfer that completed stays completed, whatever it is sent. +law a_completed_transfer_stays_completed: + for context: T.Context + for command: Transfer.TransferCommand + {Transfer.step(context, Transfer.Completed{}, command) == Transfer.Completed{} + : Transfer.TransferState} + +# RULE: a transfer that failed stays failed, for the reason it failed. +law a_failed_transfer_stays_failed: + for context: T.Context + for reason: Transfer.Reason + for command: Transfer.TransferCommand + {Transfer.step(context, Transfer.Failed{reason}, command) == Transfer.Failed{reason} + : Transfer.TransferState} + +# RULE (eventually): no transfer waits for ever. One that waits for approval +# is ended by expiry, whoever sends it and whenever. +law an_unapproved_transfer_can_always_expire: + for context: T.Context + for details: Transfer.Details + {Transfer.step(context, Transfer.AwaitingApproval{details}, Transfer.ExpireTransfer{}) + == Transfer.Failed{Transfer.NotApprovedInTime{}} : Transfer.TransferState} + +# Registration +# ============ + +# RULE: the username goes to the customer who registered under it. +law the_name_goes_to_who_registered: + for +id: Nat + for +username: Nat + {(Customer.customer_after(Customer.New{}, + Customer.register(T.ByCustomer{id}, Customer.New{}, Customer.Free{}, + Customer.RegisterCustomer{id, username})), + Customer.claim_after(Customer.Free{}, + Customer.register(T.ByCustomer{id}, Customer.New{}, Customer.Free{}, + Customer.RegisterCustomer{id, username}))) + == (Customer.Registered{username}, Customer.Claimed{id}) + : Customer.CustomerState & Customer.ClaimState} + +# RULE: once somebody holds a name, no registration gives it to anybody else. +law a_claimed_name_stays_with_its_holder: + for actor: T.Actor + for customer: Customer.CustomerState + for holder: Nat + for command: Customer.RegisterCustomer + {Customer.claim_after(Customer.Claimed{holder}, + Customer.register(actor, customer, Customer.Claimed{holder}, command)) + == Customer.Claimed{holder} : Customer.ClaimState} + +# RULE: a registered customer is not registered again. +law a_registered_customer_stays_as_registered: + for actor: T.Actor + for username: Nat + for claim: Customer.ClaimState + for command: Customer.RegisterCustomer + {Customer.customer_after(Customer.Registered{username}, + Customer.register(actor, Customer.Registered{username}, claim, command)) + == Customer.Registered{username} : Customer.CustomerState} + +# The bank +# ======== +# +# These hold after any sequence of steps: whatever callers send, whichever +# event is delivered next or delivered again, whichever saga step runs next, +# whatever the outside systems answer, and however much time passes. + +# RULE: no account in the bank ever withdraws more than the daily limit. +law every_account_within_its_limit: + for moves: List + for id: Nat + {Account.within_limit(Bank.account(Bank.steps(moves, Bank.start()), id)) == True{} : Bool} + +# RULE: every transfer in the bank is between two different accounts. +law every_transfer_between_two_accounts: + for moves: List + for id: Nat + {Transfer.between_two_accounts(Bank.transfer(Bank.steps(moves, Bank.start()), id)) == True{} + : Bool} + +# RULE: a customer is registered under a name exactly when that name is +# claimed for them. So no two customers hold one name, and nobody is +# registered under a name they do not hold. +law names_always_agree: + for moves: List + for +id: Nat + for +name: Nat + {Customer.names_agree(Bank.registrations_of(Bank.steps(moves, Bank.start())), id, name) + == True{} : Bool} + +# RULE (sometimes): the bank can be used. Some sequence of moves leaves a +# customer with money in an account. +law an_account_can_hold_money: + exs moves: List + {Bank.account(Bank.run(moves, Bank.start()), 101n) + == Account.Open{1n, 100, False{}, 0, 0} : Account.AccountState} + +# RULE: customers cannot credit an account, whichever one and however much. +law customers_cannot_credit_an_account: + for id: Nat + for actor: T.Actor + for transfer: Nat + for amount: U32 + {Api.customer_api(Bank.ToAccount{id, actor, Account.CreditTransfer{transfer, amount}}) + == False{} : Bool} + +# Stories +# ======= +# +# Each law says what the bank looks like after a story in Stories.bend. + +# STORY: registering claims the username with it, then opens a main account. +law registering.customer: + {Bank.customer(Stories.registering(), 1n) == Customer.Registered{7n} : Customer.CustomerState} + +law registering.username: + {Bank.claim(Stories.registering(), 7n) == Customer.Claimed{1n} : Customer.ClaimState} + +law registering.main_account: + {Views.account_events(Bank.log_of(Stories.registering()), 101n) + == [Account.AccountOpened{1n}] : +List} + +law registering.dashboard: + {Views.dashboard([101n], Bank.log_of(Stories.registering()), 1n) + == [Views.Holding{101n, 0}] : +List} + +# STORY: a taken username rejects the registration. +law a_taken_username: + {Bank.ask_register(Stories.registering(), Stories.alex(), Customer.RegisterCustomer{2n, 7n}) + == Customer.Refused{Customer.UsernameTaken{}} : Customer.Registration} + +# STORY: a customer may only register themselves. +law registering_someone_else: + {Bank.ask_register(Bank.start(), Stories.alex(), Customer.RegisterCustomer{1n, 7n}) + == Customer.Refused{Customer.NotTheCustomer{}} : Customer.Registration} + +# STORY: withdraw updates the account, its summary and its statement. +law withdrawing.events: + {Views.account_events(Bank.log_of(Stories.withdrawing()), 1n) + == [Account.AccountOpened{1n}, Account.MoneyDeposited{100, 100}, + Account.MoneyWithdrawn{30, 70}] : +List} + +law withdrawing.summary: + {Views.summary(Bank.log_of(Stories.withdrawing()), 1n) + == Views.Summary{True{}, 1n, 70, False{}, False{}} : Views.Summary} + +law withdrawing.statement: + {Views.statement(Bank.log_of(Stories.withdrawing()), 1n) + == [Views.Line{Views.Deposit{}, 100, 100}, Views.Line{Views.Withdrawal{}, 30, 70}] + : +List} + +# STORY: an overdraft is rejected with evidence. +law an_overdraft: + {Bank.ask_account(Stories.sams_account(50), 1n, Stories.sam(), Account.WithdrawMoney{80}) + == Domain.Reject{Account.InsufficientFunds{50, 80}} : Account.Decided()} + +# STORY: a customer can't withdraw from someone else's account. +law someone_elses_account: + {Bank.ask_account(Stories.sams_account(100), 1n, Stories.alex(), Account.WithdrawMoney{30}) + == Domain.Reject{Account.NotOwner{}} : Account.Decided()} + +# STORY: the daily limit follows the clock. +law the_daily_limit.today: + {Bank.ask_account(Stories.two_withdrawals(), 1n, Stories.sam(), Account.WithdrawMoney{30000}) + == Domain.Reject{Account.DailyLimitExceeded{20000}} : Account.Decided()} + +law the_daily_limit.tomorrow: + {Bank.account(Stories.the_next_day(), 1n) + == Account.Open{1n, 190000, False{}, 1, 30000} : Account.AccountState} + +# STORY: freezing twice records one event. +law freezing_twice: + {Views.account_events(Bank.log_of(Stories.frozen_by_support()), 1n) + == [Account.AccountOpened{1n}, Account.MoneyDeposited{100, 100}, Account.AccountFrozen{}] + : +List} + +# STORY: a risky withdrawal freezes the account, once the fraud system answers. +law a_risky_withdrawal.call: + {Bank.calls_of(Stories.a_risky_withdrawal()) == [Bank.FraudScore{1n, 60000}] : +List} + +law a_risky_withdrawal.frozen: + {Bank.account(Stories.found_risky(), 1n) + == Account.Open{1n, 30000, True{}, 0, 60000} : Account.AccountState} + +law a_risky_withdrawal.refused: + {Bank.ask_account(Stories.found_risky(), 1n, Stories.sam(), Account.WithdrawMoney{10}) + == Domain.Reject{Account.Frozen{}} : Account.Decided()} + +# STORY: split withdrawals that cross the daily threshold are reviewed. +law split_withdrawals: + {Bank.calls_of(Stories.split_withdrawals()) == [Bank.FraudScore{1n, 60000}] : +List} + +# STORY: the account is closed while the fraud check is pending. +law closed_while_checked.events: + {Views.account_events(Bank.log_of(Stories.closed_while_checked()), 1n) + == [Account.AccountOpened{1n}, Account.MoneyDeposited{60000, 60000}, + Account.MoneyWithdrawn{60000, 0}, Account.AccountClosed{}] + : +List} + +law closed_while_checked.summary: + {Views.summary(Bank.log_of(Stories.closed_while_checked()), 1n) + == Views.Summary{True{}, 1n, 0, False{}, True{}} : Views.Summary} + +# STORY: a transfer completes: the saga drives both accounts. +law a_transfer.source: + {Bank.account(Stories.a_transfer(), 1n) + == Account.Open{1n, 60, False{}, 0, 0} : Account.AccountState} + +law a_transfer.destination: + {Bank.account(Stories.a_transfer(), 2n) + == Account.Open{2n, 40, False{}, 0, 0} : Account.AccountState} + +law a_transfer.transfer: + {Views.transfer_events(Bank.log_of(Stories.a_transfer()), 1n) + == [Transfer.TransferRequested{Transfer.Details{1n, 2n, 40, Stories.sam()}, False{}}, + Transfer.TransferCompleted{}] : +List} + +law a_transfer.saga: + {Bank.saga(Stories.a_transfer(), 1n) == Some{Bank.Finished{}} : Maybe<&2, Bank.Run>} + +law a_transfer.status: + {Views.transfer_status(Stories.a_transfer(), 1n) == Views.Completed{} : Views.Progress} + +law a_transfer.shown_on_both: + {(Views.moved(Bank.log_of(Stories.a_transfer()), 1n), + Views.moved(Bank.log_of(Stories.a_transfer()), 2n)) + == ([Views.Moved{1n, 40, False{}}], [Views.Moved{1n, 40, True{}}]) + : +List & +List} + +# STORY: a customer can't move money out of someone else's account. +law someone_elses_money.account: + {Bank.account(Stories.someone_elses_money(), 1n) + == Account.Open{1n, 100, False{}, 0, 0} : Account.AccountState} + +law someone_elses_money.transfer: + {Bank.transfer(Stories.someone_elses_money(), 1n) + == Transfer.Failed{Transfer.NotYourAccount{}} : Transfer.TransferState} + +# STORY: a large transfer waits for a support agent's approval. +law a_large_transfer.waits: + {(Bank.saga(Stories.a_large_transfer(), 1n), Bank.account(Stories.a_large_transfer(), 1n)) + == (Some{Bank.WaitingForApproval{}}, Account.Open{1n, 50000, False{}, 0, 0}) + : Maybe<&2, Bank.Run> & Account.AccountState} + +law a_large_transfer.customers_cannot_approve: + {Bank.ask_transfer(Stories.a_large_transfer(), 1n, Stories.sam(), Transfer.ApproveTransfer{}) + == Domain.Reject{Transfer.NotPermitted{}} : Transfer.Decided()} + +law a_large_transfer.approved: + {(Bank.transfer(Stories.approved(), 1n), + (Bank.account(Stories.approved(), 1n), Bank.account(Stories.approved(), 2n))) + == (Transfer.Completed{}, + (Account.Open{1n, 30000, False{}, 0, 0}, Account.Open{2n, 20000, False{}, 0, 0})) + : Transfer.TransferState & (Account.AccountState & Account.AccountState)} + +# STORY: an unapproved transfer expires when its approval window closes. +law an_unapproved_transfer_expires: + {(Bank.transfer(Stories.expired(), 1n), Bank.account(Stories.expired(), 1n)) + == (Transfer.Failed{Transfer.NotApprovedInTime{}}, Account.Open{1n, 50000, False{}, 0, 0}) + : Transfer.TransferState & Account.AccountState} + +law an_unapproved_transfer_expires.too_late: + {Bank.ask_transfer(Stories.expired(), 1n, Stories.support(), Transfer.ApproveTransfer{}) + == Domain.Reject{Transfer.NotAwaitingApproval{}} : Transfer.Decided()} + +# STORY: a transfer to a closed account is compensated. +law to_a_closed_account.refunded: + {Views.account_events(Bank.log_of(Stories.to_a_closed_account()), 1n) + == [Account.AccountOpened{1n}, Account.MoneyDeposited{100, 100}, + Account.TransferDebited{1n, 40, 60}, Account.TransferRefunded{1n, 40, 100}] + : +List} + +law to_a_closed_account.failed: + {(Bank.transfer(Stories.to_a_closed_account(), 1n), Bank.saga(Stories.to_a_closed_account(), 1n)) + == (Transfer.Failed{Transfer.DestinationNotOpen{}}, + Some{Bank.FailedBecause{Transfer.DestinationNotOpen{}}}) + : Transfer.TransferState & Maybe<&2, Bank.Run>} + +# STORY: the destination closes between the saga's debit and its credit, so +# the debit is refunded. +law closed_between_two_steps: + {(Bank.account(Stories.closed_between_two_steps(), 1n), + Bank.transfer(Stories.closed_between_two_steps(), 1n)) + == (Account.Open{1n, 100, False{}, 0, 0}, Transfer.Failed{Transfer.DestinationNotOpen{}}) + : Account.AccountState & Transfer.TransferState} + +# STORY: a request delivered three times moves the money once. +law requested_three_times: + {(Bank.account(Stories.requested_three_times(), 1n), + Bank.account(Stories.requested_three_times(), 2n)) + == (Account.Open{1n, 60, False{}, 0, 0}, Account.Open{2n, 40, False{}, 0, 0}) + : Account.AccountState & Account.AccountState} + +# STORY: a settlement on a closed account can't be rejected, so it is refunded. +law a_settlement_on_a_closed_account: + {Bank.calls_of(Stories.a_settlement_on_a_closed_account()) == [Bank.Refund{9n, 500}] + : +List} + +# STORY: only agents reassign accounts, and the dashboards re-key. +law reassigning.customers_cannot: + {Bank.ask_account(Stories.sams_account(100), 1n, Stories.sam(), Account.ChangeOwner{2n}) + == Domain.Reject{Account.NotPermitted{}} : Account.Decided()} + +law reassigning.dashboards: + {(Views.dashboard([1n], Bank.log_of(Stories.reassigned()), 1n), + Views.dashboard([1n], Bank.log_of(Stories.reassigned()), 2n)) + == ([], [Views.Holding{1n, 100}]) : +List & +List} + +law reassigning.activity: + {Views.read_activity(Stories.support(), Bank.log_of(Stories.reassigned()), 1n) + == Views.Allowed{[Account.OwnerChanged{1n, 2n}]} : Views.Read<+List>} + +# STORY: the ledger is as private as the account. +law the_ledger_is_private.owner: + {Views.account_ledger(Stories.sam(), Bank.log_of(Stories.withdrawing()), 1n) + == Views.Allowed{[Views.Line{Views.Deposit{}, 100, 100}, + Views.Line{Views.Withdrawal{}, 30, 70}]} : Views.Read<+List>} + +law the_ledger_is_private.another_customer: + {Views.account_ledger(Stories.alex(), Bank.log_of(Stories.withdrawing()), 1n) + == Views.Forbidden{} : Views.Read<+List>} + +# STORY: the AccountCards projection appends a card on every balance change. +law the_account_card: + {Views.cards(Bank.log_of(Stories.withdrawing()), 1n) + == [Views.Card{1n, 100, False{}}, Views.Card{1n, 70, False{}}] : +List} diff --git a/packages/alchemy-bend/examples/bank/PROOF.bend b/packages/alchemy-bend/examples/bank/PROOF.bend new file mode 100644 index 00000000000..40beddc01a7 --- /dev/null +++ b/packages/alchemy-bend/examples/bank/PROOF.bend @@ -0,0 +1,834 @@ +# The proofs of LAWS.bend. Written by the agent; `bend PROOF.bend` checks them. + +import Base +import ../../Domain.bend as Domain +import ./Types.bend as T +import ./Account.bend as Account +import ./Transfer.bend as Transfer +import ./Customer.bend as Customer +import ./Bank.bend as Bank +import ./Views.bend as Views +import ./Stories.bend as Stories +import ./Api.bend as Api +import ./LAWS.bend as Laws + +# Account +# ======= + +# The account after a decision. +def account_after( + +context: T.Context, +state: Account.AccountState, decided: Account.Decided() +) -> Account.AccountState: + Domain.settle(~T.Context, ~Account.AccountState, ~Account.AccountEvent, + ~Account.AccountRejection, ~Account.evolve, context, state, decided) + +# "The account is within its limit." +def Within(state: Account.AccountState) -> Type: + {Account.within_limit(state) == True{} : Bool} + +# A command on an account that is not open keeps the limit. +def not_open_keeps(+context: T.Context, unopened: Bool, command: Account.AccountCommand) + -> Within(account_after(context, Account.Unopened{}, Account.decide.not_open(unopened, command))): + match context unopened command: + case T.Context{actor, today} True{} Account.OpenAccount{customer}: + {==} + case T.Context{actor, today} False{} Account.OpenAccount{customer}: + {==} + case T.Context{actor, today} True{} Account.RefundTransfer{transfer, amount}: + {==} + case T.Context{actor, today} False{} Account.RefundTransfer{transfer, amount}: + {==} + case T.Context{actor, today} True{} Account.RecordSettlement{settlement, amount}: + {==} + case T.Context{actor, today} False{} Account.RecordSettlement{settlement, amount}: + {==} + case T.Context{actor, today} True{} Account.ChangeOwner{customer}: + {==} + case T.Context{actor, today} False{} Account.ChangeOwner{customer}: + {==} + case T.Context{actor, today} True{} Account.DepositMoney{amount}: + {==} + case T.Context{actor, today} False{} Account.DepositMoney{amount}: + {==} + case T.Context{actor, today} True{} Account.WithdrawMoney{amount}: + {==} + case T.Context{actor, today} False{} Account.WithdrawMoney{amount}: + {==} + case T.Context{actor, today} True{} Account.FreezeAccount{}: + {==} + case T.Context{actor, today} False{} Account.FreezeAccount{}: + {==} + case T.Context{actor, today} True{} Account.CloseAccount{}: + {==} + case T.Context{actor, today} False{} Account.CloseAccount{}: + {==} + case T.Context{actor, today} True{} Account.DebitTransfer{transfer, amount, by}: + {==} + case T.Context{actor, today} False{} Account.DebitTransfer{transfer, amount, by}: + {==} + case T.Context{actor, today} True{} Account.CreditTransfer{transfer, amount}: + {==} + case T.Context{actor, today} False{} Account.CreditTransfer{transfer, amount}: + {==} + +# A command on a closed account keeps the limit: it stays closed. +def closed_stays(+context: T.Context, command: Account.AccountCommand) + -> {account_after(context, Account.Closed{}, Account.decide.not_open(False{}, command)) + == Account.Closed{} : Account.AccountState}: + match context command: + case T.Context{actor, today} Account.OpenAccount{customer}: + {==} + case T.Context{actor, today} Account.RefundTransfer{transfer, amount}: + {==} + case T.Context{actor, today} Account.RecordSettlement{settlement, amount}: + {==} + case T.Context{actor, today} Account.ChangeOwner{customer}: + {==} + case T.Context{actor, today} Account.DepositMoney{amount}: + {==} + case T.Context{actor, today} Account.WithdrawMoney{amount}: + {==} + case T.Context{actor, today} Account.FreezeAccount{}: + {==} + case T.Context{actor, today} Account.CloseAccount{}: + {==} + case T.Context{actor, today} Account.DebitTransfer{transfer, amount, by}: + {==} + case T.Context{actor, today} Account.CreditTransfer{transfer, amount}: + {==} + +# "An open account with this much withdrawn is within its limit." +def Under(withdrawn: U32) -> Type: + {U32.is_le(withdrawn, Account.daily_limit()) == True{} : Bool} + +def change_owner_keeps( + +context: T.Context, agent: Bool, -customer: Nat, -balance: U32, -frozen: Bool, -day: U32, + -withdrawn: U32, -to: Nat, old: Under(withdrawn) +) -> Within(account_after(context, Account.Open{customer, balance, frozen, day, withdrawn}, + Account.change_owner.go(agent, customer, to))): + match context agent: + case T.Context{actor, today} True{}: + old + case T.Context{actor, today} False{}: + old + +def deposit_keeps( + +context: T.Context, may: Bool, -customer: Nat, -balance: U32, -frozen: Bool, -day: U32, + -withdrawn: U32, -amount: U32, old: Under(withdrawn) +) -> Within(account_after(context, Account.Open{customer, balance, frozen, day, withdrawn}, + Account.deposit.go(may, balance, amount))): + match context may: + case T.Context{actor, today} True{}: + old + case T.Context{actor, today} False{}: + old + +# A withdrawal keeps the limit: it is recorded only when the check passed. +def withdraw_keeps( + -actor: T.Actor, -today: U32, may: Bool, frozen: Bool, enough: Bool, within: Bool, + -customer: Nat, -balance: U32, -day: U32, -withdrawn: U32, -amount: U32, + old: Under(withdrawn), + new: {U32.is_le( + U32.add(Account.withdrawn_on(U32.is_eq(day, today), withdrawn), amount), + Account.daily_limit()) == within : Bool} +) -> Within(account_after(T.Context{actor, today}, + Account.Open{customer, balance, frozen, day, withdrawn}, + Account.withdraw.go(may, frozen, enough, within, balance, + Account.withdrawn_on(U32.is_eq(day, today), withdrawn), amount))): + match may frozen enough within: + case False{} True{} _ _: + old + case False{} False{} _ _: + old + case True{} True{} _ _: + old + case True{} False{} False{} _: + old + case True{} False{} True{} False{}: + old + case True{} False{} True{} True{}: + new + +def freeze_keeps( + +context: T.Context, may: Bool, frozen: Bool, -customer: Nat, -balance: U32, -day: U32, + -withdrawn: U32, old: Under(withdrawn) +) -> Within(account_after(context, Account.Open{customer, balance, frozen, day, withdrawn}, + Account.freeze.go(may, frozen))): + match context may frozen: + case T.Context{actor, today} False{} True{}: + old + case T.Context{actor, today} False{} False{}: + old + case T.Context{actor, today} True{} True{}: + old + case T.Context{actor, today} True{} False{}: + old + +def close_keeps( + +context: T.Context, may: Bool, empty: Bool, -customer: Nat, -balance: U32, -frozen: Bool, + -day: U32, -withdrawn: U32, old: Under(withdrawn) +) -> Within(account_after(context, Account.Open{customer, balance, frozen, day, withdrawn}, + Account.close.go(may, empty, balance))): + match context may empty: + case T.Context{actor, today} False{} _: + old + case T.Context{actor, today} True{} False{}: + old + case T.Context{actor, today} True{} True{}: + {==} + +def debit_keeps( + +context: T.Context, may: Bool, frozen: Bool, enough: Bool, -customer: Nat, -balance: U32, + -day: U32, -withdrawn: U32, -transfer: Nat, -amount: U32, old: Under(withdrawn) +) -> Within(account_after(context, Account.Open{customer, balance, frozen, day, withdrawn}, + Account.debit.go(may, frozen, enough, transfer, balance, amount))): + match context may frozen enough: + case T.Context{actor, today} False{} True{} _: + old + case T.Context{actor, today} False{} False{} _: + old + case T.Context{actor, today} True{} True{} _: + old + case T.Context{actor, today} True{} False{} False{}: + old + case T.Context{actor, today} True{} False{} True{}: + old + +# A command on an open account keeps the limit. +def open_keeps( + +actor: T.Actor, +today: U32, +customer: Nat, +balance: U32, +frozen: Bool, +day: U32, + +withdrawn: U32, command: Account.AccountCommand, old: Under(withdrawn) +) -> Within(account_after(T.Context{actor, today}, + Account.Open{customer, balance, frozen, day, withdrawn}, + Account.decide.open(actor, today, customer, balance, frozen, day, withdrawn, command))): + match command: + case Account.OpenAccount{to}: + old + case Account.ChangeOwner{to}: + change_owner_keeps(T.Context{actor, today}, T.is_agent(actor), customer, balance, frozen, + day, withdrawn, to, old) + case Account.DepositMoney{amount}: + deposit_keeps(T.Context{actor, today}, T.may_act(actor, customer), customer, balance, + frozen, day, withdrawn, amount, old) + case Account.WithdrawMoney{+amount}: + withdraw_keeps(actor, today, T.may_act(actor, customer), frozen, + U32.is_le(amount, balance), + U32.is_le(U32.add(Account.withdrawn_on(U32.is_eq(day, today), withdrawn), amount), + Account.daily_limit()), + customer, balance, day, withdrawn, amount, old, {==}) + case Account.FreezeAccount{}: + freeze_keeps(T.Context{actor, today}, T.may_act(actor, customer), frozen, customer, + balance, day, withdrawn, old) + case Account.CloseAccount{}: + close_keeps(T.Context{actor, today}, T.may_act(actor, customer), U32.is_eq(balance, 0), + customer, balance, frozen, day, withdrawn, old) + case Account.DebitTransfer{transfer, +amount, by}: + debit_keeps(T.Context{actor, today}, T.may_act(by, customer), frozen, + U32.is_le(amount, balance), customer, balance, day, withdrawn, transfer, amount, old) + case Account.CreditTransfer{transfer, amount}: + old + case Account.RefundTransfer{transfer, amount}: + old + case Account.RecordSettlement{settlement, amount}: + old + +# One command keeps the limit. +def step_keeps( + +context: T.Context, +state: Account.AccountState, command: Account.AccountCommand, + old: Within(state) +) -> Within(Account.step(context, state, command)): + match context state: + case T.Context{+actor, +today} Account.Unopened{}: + not_open_keeps(T.Context{actor, today}, True{}, command) + case T.Context{+actor, +today} Account.Closed{}: + %Equal.sym(Account.AccountState, + account_after(T.Context{actor, today}, Account.Closed{}, + Account.decide.not_open(False{}, command)), + Account.Closed{}, closed_stays(T.Context{actor, today}, command)) : Within(_) + {==} + case T.Context{+actor, +today} Account.Open{+customer, +balance, +frozen, +day, +withdrawn}: + open_keeps(actor, today, customer, balance, frozen, day, withdrawn, command, old) + +# Every sequence of commands keeps the limit, by induction on the commands. +def replay_keeps(commands: List, +state: Account.AccountState, old: Within(state)) + -> Within(Account.replay(commands, state)): + match commands: + case Nil{}: + old + case Domain.Sent{+context, +command} <> rest: + replay_keeps(rest, Account.step(context, state, command), + step_keeps(context, state, command, old)) + +def Laws.within_daily_limit(commands): + replay_keeps(commands, Account.initial(), {==}) + +def Laws.a_closed_account_stays_closed(context, command): + match context: + case T.Context{actor, today}: + closed_stays(T.Context{actor, today}, command) + +def Laws.only_an_agent_changes_the_owner(customer, day, state, to): + match state: + case Account.Unopened{}: + {==} + case Account.Closed{}: + {==} + case Account.Open{owner, balance, frozen, at, withdrawn}: + {==} + +# A frozen account refuses a withdrawal, whoever asks. +def frozen_refuses( + -actor: T.Actor, -today: U32, may: Bool, -enough: Bool, -within: Bool, -customer: Nat, + -balance: U32, -day: U32, -withdrawn: U32, -used: U32, -amount: U32 +) -> {account_after(T.Context{actor, today}, + Account.Open{customer, balance, True{}, day, withdrawn}, + Account.withdraw.go(may, True{}, enough, within, balance, used, amount)) + == Account.Open{customer, balance, True{}, day, withdrawn} : Account.AccountState}: + match may: + case False{}: + {==} + case True{}: + {==} + +def Laws.a_frozen_account_refuses_a_withdrawal(context, customer, balance, day, withdrawn, amount): + match context: + case T.Context{+actor, +today}: + frozen_refuses(actor, today, T.may_act(actor, customer), + U32.is_le(amount, balance), + U32.is_le(U32.add(Account.withdrawn_on(U32.is_eq(day, today), withdrawn), amount), + Account.daily_limit()), + customer, balance, day, withdrawn, + Account.withdrawn_on(U32.is_eq(day, today), withdrawn), amount) + +# Transfer +# ======== + +def transfer_after( + +context: T.Context, +state: Transfer.TransferState, decided: Transfer.Decided() +) -> Transfer.TransferState: + Domain.settle(~T.Context, ~Transfer.TransferState, ~Transfer.TransferEvent, + ~Transfer.TransferRejection, ~Transfer.evolve, context, state, decided) + +# A late approval changes nothing, whoever sends it. +def late_stays(+context: T.Context, +state: Transfer.TransferState, agent: Bool) + -> {transfer_after(context, state, Transfer.approve.late(agent)) == state + : Transfer.TransferState}: + match agent: + case True{}: + {==} + case False{}: + {==} + +# A command on a transfer that has ended changes nothing. +def ended_stays(+actor: T.Actor, +day: U32, +state: Transfer.TransferState, + command: Transfer.TransferCommand) + -> {transfer_after(T.Context{actor, day}, state, Transfer.decide.settled(actor, False{}, command)) + == state : Transfer.TransferState}: + match command: + case Transfer.RequestTransfer{source, destination, amount}: + {==} + case Transfer.ApproveTransfer{}: + late_stays(T.Context{actor, day}, state, T.is_agent(actor)) + case Transfer.ExpireTransfer{}: + {==} + case Transfer.CompleteTransfer{}: + {==} + case Transfer.FailTransfer{reason}: + {==} + +def Laws.a_completed_transfer_stays_completed(context, command): + match context: + case T.Context{+actor, +day}: + ended_stays(actor, day, Transfer.Completed{}, command) + +def Laws.a_failed_transfer_stays_failed(context, reason, command): + match context: + case T.Context{+actor, +day}: + ended_stays(actor, day, Transfer.Failed{reason}, command) + +# "The transfer is between two different accounts." +def Between(state: Transfer.TransferState) -> Type: + {Transfer.between_two_accounts(state) == True{} : Bool} + +# A request is recorded only between two different accounts. +def request_keeps( + +context: T.Context, same: Bool, large: Bool, -source: Nat, -destination: Nat, -amount: U32, + -by: T.Actor, checked: {same == Nat.is_eq(source, destination) : Bool} +) -> Between(transfer_after(context, Transfer.New{}, + Transfer.request.go(same, large, Transfer.Details{source, destination, amount, by}))): + match context same large: + case T.Context{actor, day} True{} _: + {==} + case T.Context{actor, day} False{} True{}: + %checked : {Bool.not(_) == True{} : Bool} + {==} + case T.Context{actor, day} False{} False{}: + %checked : {Bool.not(_) == True{} : Bool} + {==} + +def approve_keeps( + +context: T.Context, agent: Bool, -details: Transfer.Details, -by: T.Actor, + old: Between(Transfer.AwaitingApproval{details}) +) -> Between(transfer_after(context, Transfer.AwaitingApproval{details}, + Transfer.approve.go(agent, details, by))): + match context agent: + case T.Context{actor, day} True{}: + old + case T.Context{actor, day} False{}: + old + +def late_keeps(+context: T.Context, +state: Transfer.TransferState, agent: Bool, old: Between(state)) + -> Between(transfer_after(context, state, Transfer.approve.late(agent))): + match agent: + case True{}: + old + case False{}: + old + +# A command on a transfer that is new keeps the rule. +def new_keeps(+actor: T.Actor, +day: U32, command: Transfer.TransferCommand) + -> Between(transfer_after(T.Context{actor, day}, Transfer.New{}, + Transfer.decide.settled(actor, True{}, command))): + match command: + case Transfer.RequestTransfer{+source, +destination, +amount}: + request_keeps(T.Context{actor, day}, Nat.is_eq(source, destination), + U32.is_le(Transfer.approval_threshold(), amount), source, destination, amount, actor, {==}) + case Transfer.ApproveTransfer{}: + late_keeps(T.Context{actor, day}, Transfer.New{}, T.is_agent(actor), {==}) + case Transfer.ExpireTransfer{}: + {==} + case Transfer.CompleteTransfer{}: + {==} + case Transfer.FailTransfer{reason}: + {==} + +def awaiting_keeps( + +actor: T.Actor, +day: U32, +details: Transfer.Details, command: Transfer.TransferCommand, + old: Between(Transfer.AwaitingApproval{details}) +) -> Between(transfer_after(T.Context{actor, day}, Transfer.AwaitingApproval{details}, + Transfer.decide.awaiting(actor, details, command))): + match command: + case Transfer.RequestTransfer{source, destination, amount}: + old + case Transfer.ApproveTransfer{}: + approve_keeps(T.Context{actor, day}, T.is_agent(actor), details, actor, old) + case Transfer.ExpireTransfer{}: + {==} + case Transfer.CompleteTransfer{}: + old + case Transfer.FailTransfer{reason}: + old + +def pending_keeps( + +actor: T.Actor, +day: U32, +details: Transfer.Details, command: Transfer.TransferCommand, + old: Between(Transfer.Pending{details}) +) -> Between(transfer_after(T.Context{actor, day}, Transfer.Pending{details}, + Transfer.decide.pending(actor, command))): + match command: + case Transfer.RequestTransfer{source, destination, amount}: + old + case Transfer.ApproveTransfer{}: + late_keeps(T.Context{actor, day}, Transfer.Pending{details}, T.is_agent(actor), old) + case Transfer.ExpireTransfer{}: + old + case Transfer.CompleteTransfer{}: + {==} + case Transfer.FailTransfer{reason}: + {==} + +# One command keeps a transfer between two accounts. +def transfer_step_keeps( + +context: T.Context, +state: Transfer.TransferState, command: Transfer.TransferCommand, + old: Between(state) +) -> Between(Transfer.step(context, state, command)): + match context state: + case T.Context{+actor, +day} Transfer.New{}: + new_keeps(actor, day, command) + case T.Context{+actor, +day} Transfer.AwaitingApproval{+details}: + awaiting_keeps(actor, day, details, command, old) + case T.Context{+actor, +day} Transfer.Pending{+details}: + pending_keeps(actor, day, details, command, old) + case T.Context{+actor, +day} Transfer.Completed{}: + %Equal.sym(Transfer.TransferState, + transfer_after(T.Context{actor, day}, Transfer.Completed{}, + Transfer.decide.settled(actor, False{}, command)), + Transfer.Completed{}, ended_stays(actor, day, Transfer.Completed{}, command)) : Between(_) + {==} + case T.Context{+actor, +day} Transfer.Failed{+reason}: + %Equal.sym(Transfer.TransferState, + transfer_after(T.Context{actor, day}, Transfer.Failed{reason}, + Transfer.decide.settled(actor, False{}, command)), + Transfer.Failed{reason}, ended_stays(actor, day, Transfer.Failed{reason}, command)) + : Between(_) + {==} + +def transfer_replay_keeps( + commands: List, +state: Transfer.TransferState, old: Between(state) +) -> Between(Transfer.replay(commands, state)): + match commands: + case Nil{}: + old + case Domain.Sent{+context, +command} <> rest: + transfer_replay_keeps(rest, Transfer.step(context, state, command), + transfer_step_keeps(context, state, command, old)) + +def transfer_between(world: Bank.World(), +id: Nat) -> Between(Bank.transfer(world, id)): + transfer_replay_keeps(Bank.transfer_sends(Bank.sent_of(world), id), Transfer.initial(), {==}) + +def Laws.every_transfer_between_two_accounts(moves, id): + transfer_between(Bank.steps(moves, Bank.start()), id) + +# Registration +# ============ + +# A number is itself. +def is_eq_refl(n: Nat) -> {Nat.is_eq(n, n) == True{} : Bool}: + match n: + case 0n: + {==} + case 1n+p: + is_eq_refl(p) + +def Laws.the_name_goes_to_who_registered(id, username): + %Equal.sym(Bool, Nat.is_eq(id, id), True{}, is_eq_refl(id)) : + {(Customer.customer_after(Customer.New{}, + Customer.register.go(_, False{}, False{}, id, username)), + Customer.claim_after(Customer.Free{}, + Customer.register.go(_, False{}, False{}, id, username))) + == (Customer.Registered{username}, Customer.Claimed{id}) + : Customer.CustomerState & Customer.ClaimState} + {==} + +def taken_refuses(may: Bool, registered: Bool, -holder: Nat, -id: Nat, -username: Nat) + -> {Customer.claim_after(Customer.Claimed{holder}, + Customer.register.go(may, registered, True{}, id, username)) + == Customer.Claimed{holder} : Customer.ClaimState}: + match may registered: + case False{} _: + {==} + case True{} True{}: + {==} + case True{} False{}: + {==} + +def Laws.a_claimed_name_stays_with_its_holder(actor, customer, holder, command): + match command: + case Customer.RegisterCustomer{+id, username}: + taken_refuses(T.may_act(actor, id), Customer.is_registered(customer), holder, id, username) + +def registered_refuses(may: Bool, -taken: Bool, -known: Nat, -id: Nat, -username: Nat) + -> {Customer.customer_after(Customer.Registered{known}, + Customer.register.go(may, True{}, taken, id, username)) + == Customer.Registered{known} : Customer.CustomerState}: + match may: + case False{}: + {==} + case True{}: + {==} + +def Laws.a_registered_customer_stays_as_registered(actor, username, claim, command): + match command: + case Customer.RegisterCustomer{+id, name}: + registered_refuses(T.may_act(actor, id), Customer.is_claimed(claim), username, id, name) + +def Laws.an_unapproved_transfer_can_always_expire(context, details): + match context: + case T.Context{actor, day}: + {==} + +# The witness: Sam registers, then deposits. +def Laws.an_account_can_hold_money(): + ([Bank.Register{Stories.sam(), Customer.RegisterCustomer{1n, 7n}}, + Bank.ToAccount{101n, Stories.sam(), Account.DepositMoney{100}}], + {==}) + +def Laws.customers_cannot_credit_an_account(id, actor, transfer, amount): + {==} + +# The bank +# ======== + +# Every account in a world is within its limit: its state is the commands it +# was sent, replayed, and every sequence of commands keeps the limit. +def account_within(world: Bank.World(), +id: Nat) -> Within(Bank.account(world, id)): + replay_keeps(Bank.account_sends(Bank.sent_of(world), id), Account.initial(), {==}) + +def Laws.every_account_within_its_limit(moves, id): + account_within(Bank.steps(moves, Bank.start()), id) + +# Names +# ===== + +def Truth(b: Bool) -> Type: + match b: + case True{}: + Unit + case False{}: + Empty + +# True is not False. +def true_is_not_false(e: {True{} == False{} : Bool}) -> Empty: + %e : Truth(_) + Unit{} + +# Two numbers that compare equal are the same number. +def eq_of_is_eq(a: Nat, b: Nat, e: {True{} == Nat.is_eq(a, b) : Bool}) -> {a == b : Nat}: + match a b: + case 0n 0n: + {==} + case 0n 1n+q: + Empty.absurd({0n == 1n+q : Nat}, true_is_not_false(e)) + case 1n+p 0n: + Empty.absurd({1n+p == 0n : Nat}, true_is_not_false(e)) + case 1n+p 1n+q: + %eq_of_is_eq(p, q, e) : {1n+p == 1n+_ : Nat} + {==} + +# When two keys compare equal, their slots are held alike. +def held_alike( + -older: +List, -of_customer: Bool, +a: Nat, +b: Nat, flag: Bool, + e: {flag == Nat.is_eq(a, b) : Bool} +) -> {Customer.when(flag, Customer.is_held(Customer.slot(older, of_customer, b))) + == Customer.when(flag, Customer.is_held(Customer.slot(older, of_customer, a))) : Bool}: + match flag: + case False{}: + {==} + case True{}: + %eq_of_is_eq(a, b, e) : + {Customer.is_held(Customer.slot(older, of_customer, _)) + == Customer.is_held(Customer.slot(older, of_customer, a)) : Bool} + {==} + +# A slot that is not held holds nothing. +def vacant_holds_nothing(slot: Customer.Slot, -what: Nat, e: {Customer.is_held(slot) == False{} : Bool}) + -> {False{} == Customer.holds(slot, what) : Bool}: + match slot: + case Customer.Vacant{}: + {==} + case Customer.Holds{value}: + Empty.absurd({False{} == Customer.holds(Customer.Holds{value}, what) : Bool}, + true_is_not_false(e)) + +def same_right(a: Bool, b: Bool, ha: {False{} == a : Bool}, h: {Customer.same(a, b) == True{} : Bool}) + -> {False{} == b : Bool}: + match a b: + case True{} _: + Empty.absurd({False{} == b : Bool}, true_is_not_false(Equal.sym(Bool, False{}, True{}, ha))) + case False{} True{}: + Empty.absurd({False{} == True{} : Bool}, + true_is_not_false(Equal.sym(Bool, False{}, True{}, h))) + case False{} False{}: + {==} + +def same_left(a: Bool, b: Bool, hb: {False{} == b : Bool}, h: {Customer.same(a, b) == True{} : Bool}) + -> {False{} == a : Bool}: + match a b: + case _ True{}: + Empty.absurd({False{} == a : Bool}, true_is_not_false(Equal.sym(Bool, False{}, True{}, hb))) + case True{} False{}: + Empty.absurd({False{} == True{} : Bool}, + true_is_not_false(Equal.sym(Bool, False{}, True{}, h))) + case False{} False{}: + {==} + +# One registration keeps the names in agreement. cs is what the customer +# asked about held before, and lu what the name asked about held. +def agree_step( + may: Bool, reg: Bool, taken: Bool, sc: Bool, su: Bool, + +id: Nat, +username: Nat, +c: Nat, +u: Nat, +cs: Customer.Slot, +lu: Customer.Slot, + ih: {Customer.same(Customer.holds(cs, u), Customer.holds(lu, c)) == True{} : Bool}, + hsc: {sc == Nat.is_eq(id, c) : Bool}, + hsu: {su == Nat.is_eq(username, u) : Bool}, + fc: {Customer.when(sc, Customer.is_held(cs)) == Customer.when(sc, reg) : Bool}, + fu: {Customer.when(su, Customer.is_held(lu)) == Customer.when(su, taken) : Bool} +) -> {Customer.same( + Customer.holds(Customer.slot_next( + Customer.is_accepted(Customer.register.go(may, reg, taken, id, username)), + sc, username, cs), u), + Customer.holds(Customer.slot_next( + Customer.is_accepted(Customer.register.go(may, reg, taken, id, username)), + su, id, lu), c)) == True{} : Bool}: + match may reg taken sc su: + case False{} _ _ _ _: + ih + case True{} True{} _ _ _: + ih + case True{} False{} True{} _ _: + ih + case True{} False{} False{} False{} False{}: + ih + case True{} False{} False{} True{} True{}: + %hsu : {Customer.same(_, Nat.is_eq(id, c)) == True{} : Bool} + %hsc : {Customer.same(True{}, _) == True{} : Bool} + {==} + case True{} False{} False{} True{} False{}: + %hsu : {Customer.same(_, Customer.holds(lu, c)) == True{} : Bool} + %same_right(Customer.holds(cs, u), Customer.holds(lu, c), + vacant_holds_nothing(cs, u, fc), ih) + : {Customer.same(False{}, _) == True{} : Bool} + {==} + case True{} False{} False{} False{} True{}: + %hsc : {Customer.same(Customer.holds(cs, u), _) == True{} : Bool} + %same_left(Customer.holds(cs, u), Customer.holds(lu, c), + vacant_holds_nothing(lu, c, fu), ih) + : {Customer.same(_, False{}) == True{} : Bool} + {==} + +# Every list of registrations leaves the names in agreement. +def agree(sent: +List, +c: Nat, +u: Nat) + -> {Customer.names_agree(sent, c, u) == True{} : Bool}: + match sent: + case Nil{}: + {==} + case Customer.Registering{actor, Customer.RegisterCustomer{+id, +username}} <> +older: + agree_step( + T.may_act(actor, id), + Customer.is_held(Customer.slot(older, True{}, id)), + Customer.is_held(Customer.slot(older, False{}, username)), + Nat.is_eq(id, c), Nat.is_eq(username, u), + id, username, c, u, + Customer.slot(older, True{}, c), Customer.slot(older, False{}, u), + agree(older, c, u), {==}, {==}, + held_alike(older, True{}, id, c, Nat.is_eq(id, c), {==}), + held_alike(older, False{}, username, u, Nat.is_eq(username, u), {==})) + +def Laws.names_always_agree(moves, id, name): + agree(Bank.registrations_of(Bank.steps(moves, Bank.start())), id, name) + +# Stories +# ======= +# +# A story is proved by running it. + +def Laws.registering.customer(): + {==} + +def Laws.registering.username(): + {==} + +def Laws.registering.main_account(): + {==} + +def Laws.registering.dashboard(): + {==} + +def Laws.a_taken_username(): + {==} + +def Laws.registering_someone_else(): + {==} + +def Laws.withdrawing.events(): + {==} + +def Laws.withdrawing.summary(): + {==} + +def Laws.withdrawing.statement(): + {==} + +def Laws.an_overdraft(): + {==} + +def Laws.someone_elses_account(): + {==} + +def Laws.the_daily_limit.today(): + {==} + +def Laws.the_daily_limit.tomorrow(): + {==} + +def Laws.freezing_twice(): + {==} + +def Laws.a_risky_withdrawal.call(): + {==} + +def Laws.a_risky_withdrawal.frozen(): + {==} + +def Laws.a_risky_withdrawal.refused(): + {==} + +def Laws.split_withdrawals(): + {==} + +def Laws.closed_while_checked.events(): + {==} + +def Laws.closed_while_checked.summary(): + {==} + +def Laws.a_transfer.source(): + {==} + +def Laws.a_transfer.destination(): + {==} + +def Laws.a_transfer.transfer(): + {==} + +def Laws.a_transfer.saga(): + {==} + +def Laws.a_transfer.status(): + {==} + +def Laws.a_transfer.shown_on_both(): + {==} + +def Laws.someone_elses_money.account(): + {==} + +def Laws.someone_elses_money.transfer(): + {==} + +def Laws.a_large_transfer.waits(): + {==} + +def Laws.a_large_transfer.customers_cannot_approve(): + {==} + +def Laws.a_large_transfer.approved(): + {==} + +def Laws.an_unapproved_transfer_expires(): + {==} + +def Laws.an_unapproved_transfer_expires.too_late(): + {==} + +def Laws.to_a_closed_account.refunded(): + {==} + +def Laws.to_a_closed_account.failed(): + {==} + +def Laws.closed_between_two_steps(): + {==} + +def Laws.requested_three_times(): + {==} + +def Laws.a_settlement_on_a_closed_account(): + {==} + +def Laws.reassigning.customers_cannot(): + {==} + +def Laws.reassigning.dashboards(): + {==} + +def Laws.reassigning.activity(): + {==} + +def Laws.the_ledger_is_private.owner(): + {==} + +def Laws.the_ledger_is_private.another_customer(): + {==} + +def Laws.the_account_card(): + {==} + diff --git a/packages/alchemy-bend/examples/bank/Search.bend b/packages/alchemy-bend/examples/bank/Search.bend new file mode 100644 index 00000000000..e797f959edd --- /dev/null +++ b/packages/alchemy-bend/examples/bank/Search.bend @@ -0,0 +1,191 @@ +# A search for the sequence of moves that breaks a rule. Where a proof says a +# rule holds for ever, this says it holds in every sequence tried, and when it +# does not, it gives the sequence. +# +# bend Search.bend +# +# checks the rules about a settled bank in every sequence of up to four of the +# moves below, and shows the shortest sequence that breaks a rule that is false. + +import Base +import ./Types.bend as T +import ./Account.bend as Account +import ./Transfer.bend as Transfer +import ./Customer.bend as Customer +import ./Bank.bend as Bank +import ./Views.bend as Views +import ./Stories.bend as Stories + +# The moves a sequence is made of: what callers do, a fault, and the clock. +def moves() -> +List: + [Bank.Register{Stories.sam(), Customer.RegisterCustomer{1n, 7n}}, + Bank.Register{Stories.alex(), Customer.RegisterCustomer{2n, 8n}}, + Bank.ToAccount{101n, Stories.sam(), Account.DepositMoney{30000}}, + Bank.ToTransfer{1n, Stories.sam(), Transfer.RequestTransfer{101n, 102n, 100}}, + Bank.ToTransfer{2n, Stories.sam(), Transfer.RequestTransfer{101n, 102n, 20000}}, + Bank.ToTransfer{2n, Stories.support(), Transfer.ApproveTransfer{}}, + Bank.ToAccount{102n, Stories.alex(), Account.CloseAccount{}}, + Bank.Redeliver{3n}, + Bank.Pass{86400}] + +# Rules about a settled bank +# ========================== + +def taken(events: +List) -> U32: + match events: + case Nil{}: + 0 + case Account.TransferDebited{t, amount, after} <> rest: + U32.add(amount, taken(rest)) + case _ <> rest: + taken(rest) + +def given(events: +List) -> U32: + match events: + case Nil{}: + 0 + case Account.TransferCredited{t, amount, after} <> rest: + U32.add(amount, given(rest)) + case Account.TransferRefunded{t, amount, after} <> rest: + U32.add(amount, given(rest)) + case Account.RefundStranded{t, amount} <> rest: + U32.add(amount, given(rest)) + case _ <> rest: + given(rest) + +# RULE: every cent a transfer takes out of an account is paid into another, +# paid back, or recorded as stranded. +def transfers_lose_no_money(+world: Bank.World()) -> Bool: + U32.is_eq( + U32.add(taken(Views.account_events(Bank.log_of(world), 101n)), + taken(Views.account_events(Bank.log_of(world), 102n))), + U32.add(given(Views.account_events(Bank.log_of(world), 101n)), + given(Views.account_events(Bank.log_of(world), 102n)))) + +def is_pending(state: Transfer.TransferState) -> Bool: + match state: + case Transfer.Pending{details}: + True{} + case _: + False{} + +# RULE: a transfer that may run has run: it completed or it failed. +def no_transfer_left_pending(+world: Bank.World()) -> Bool: + Bool.not(is_pending(Bank.transfer(world, 1n)) || is_pending(Bank.transfer(world, 2n))) + +def has_ended(state: Transfer.TransferState) -> Bool: + match state: + case Transfer.Completed{}: + True{} + case Transfer.Failed{reason}: + True{} + case Transfer.New{}: + True{} + case _: + False{} + +def all_ended(+world: Bank.World()) -> Bool: + has_ended(Bank.transfer(world, 1n)) && has_ended(Bank.transfer(world, 2n)) + +# RULE (eventually): once the approval window has closed, every transfer that +# was asked for has ended. +def every_transfer_ends(+world: Bank.World()) -> Bool: + all_ended(Bank.play(world, Bank.Pass{86400})) + +def is_waiting(state: Transfer.TransferState) -> Bool: + match state: + case Transfer.AwaitingApproval{details}: + True{} + case _: + False{} + +# A rule that is false: no transfer ever waits for approval. +def no_transfer_ever_waits(+world: Bank.World()) -> Bool: + Bool.not(is_waiting(Bank.transfer(world, 1n)) || is_waiting(Bank.transfer(world, 2n))) + +def is_completed(state: Transfer.TransferState) -> Bool: + match state: + case Transfer.Completed{}: + True{} + case _: + False{} + +# Another rule that is false: no transfer ever completes. +def no_transfer_ever_completes(+world: Bank.World()) -> Bool: + Bool.not(is_completed(Bank.transfer(world, 1n))) + +# The search +# ========== + +def found(holds: Bool, deeper: Maybe<&2, +List>, +index: Nat, sibling: Maybe<&2, +List>) + -> Maybe<&2, +List>: + match holds deeper: + case False{} _: + Some{[index]} + case True{} Some{path}: + Some{index <> path} + case True{} None{}: + sibling + +# The first sequence of at most `depth` moves after which the rule fails, by +# where each move is in `all`. It tries the moves in `rest`, from `index` on. +def breaks( + ~rule: @+w: Bank.World() -> Bool, depth: Nat, +all: +List, rest: +List, + +index: Nat, +world: Bank.World() +) -> Maybe<&2, +List>: + match depth rest: + case 0n _: + None{} + case 1n+d Nil{}: + None{} + case 1n+d +move <> more: + +below = d + found(rule(Bank.play(world, move)), + breaks(~rule, below, all, all, 0n, Bank.play(world, move)), + index, + breaks(~rule, 1n+below, all, more, 1n+index, world)) + +def shortest.or(here: Maybe<&2, +List>, deeper: Maybe<&2, +List>) + -> Maybe<&2, +List>: + match here: + case Some{path}: + Some{path} + case None{}: + deeper + +# The shortest such sequence: the search runs at each depth up to the limit. +def shortest(~rule: @+w: Bank.World() -> Bool, limit: Nat, +depth: Nat, +all: +List) + -> Maybe<&2, +List>: + match limit: + case 0n: + None{} + case 1n+l: + shortest.or(breaks(~rule, depth, all, all, 0n, Bank.start()), + shortest(~rule, l, 1n+depth, all)) + +def show_path(path: +List) -> String: + match path: + case Nil{}: + "" + case i <> rest: + Nat.show(i) ++ " " ++ show_path(rest) + +def verdict(name: String, result: Maybe<&2, +List>) -> String: + match result: + case None{}: + "holds in every sequence tried: " ++ name + case Some{path}: + "BROKEN by moves " ++ show_path(path) ++ ": " ++ name + +def main() -> IO(Unit): + do IO: + IO.print(verdict("transfers lose no money", + shortest(~transfers_lose_no_money, 4n, 1n, moves()))) + IO.print(verdict("no transfer is left pending", + shortest(~no_transfer_left_pending, 4n, 1n, moves()))) + IO.print(verdict("every transfer ends once the window closes", + shortest(~every_transfer_ends, 4n, 1n, moves()))) + IO.print(verdict("no transfer ever waits for approval", + shortest(~no_transfer_ever_waits, 4n, 1n, moves()))) + IO.print(verdict("no transfer ever completes", + shortest(~no_transfer_ever_completes, 4n, 1n, moves()))) diff --git a/packages/alchemy-bend/examples/bank/Server.bend b/packages/alchemy-bend/examples/bank/Server.bend new file mode 100644 index 00000000000..95d628cae57 --- /dev/null +++ b/packages/alchemy-bend/examples/bank/Server.bend @@ -0,0 +1,875 @@ +# The bank over HTTP, kept in a journal file so it is where it was after a +# restart. +# +# bend Server.bend -o build/bank && ./build/bank +# +# A request's path says who asks and what for: +# +# /c/1/register/7 customer 1 registers under username 7 +# /c/1/account/101/deposit/5000 deposit, withdraw, close, freeze, owner/N +# /c/1/transfer/1/request/101/102/40 ask for a transfer; /a/7/transfer/1/approve +# /c/1/account/101/summary summary, statement, card +# /c/1/customer/1/dashboard /c/1/transfer/1/status +# /pass/86400 time passes, beyond the wall clock +# /app/c/1 customer 1's page; /app/a/7 an agent's +# +# Every request that changes the bank is written to the journal before it is +# applied, and the journal is replayed at the start. + +import Base +import ../../Domain.bend as Domain +import ./Types.bend as T +import ./Account.bend as Account +import ./Transfer.bend as Transfer +import ./Customer.bend as Customer +import ./Bank.bend as Bank +import ./Views.bend as Views +import ./Api.bend as Api + +# Reading a path +# ============== + +type Part is Data: + WC{} + WA{} + WAccount{} + WTransfer{} + WCustomer{} + WRegister{} + WDeposit{} + WWithdraw{} + WFreeze{} + WClose{} + WOwner{} + WRequest{} + WApprove{} + WSummary{} + WStatement{} + WCard{} + WDashboard{} + WStatus{} + WPass{} + WApp{} + WVersion{} + WAnswer{} + WFraud{} + WRefund{} + WOther{} + +# This word, when the text is it; otherwise whatever else it turns out to be. +def word.is(same: Bool, this: Part, otherwise: Part) -> Part: + match same: + case True{}: + this + case False{}: + otherwise + +def word(+s: String) -> Part: + word.is(String.eq(s, "c"), WC{}, + word.is(String.eq(s, "a"), WA{}, + word.is(String.eq(s, "account"), WAccount{}, + word.is(String.eq(s, "transfer"), WTransfer{}, + word.is(String.eq(s, "customer"), WCustomer{}, + word.is(String.eq(s, "register"), WRegister{}, + word.is(String.eq(s, "deposit"), WDeposit{}, + word.is(String.eq(s, "withdraw"), WWithdraw{}, + word.is(String.eq(s, "freeze"), WFreeze{}, + word.is(String.eq(s, "close"), WClose{}, + word.is(String.eq(s, "owner"), WOwner{}, + word.is(String.eq(s, "request"), WRequest{}, + word.is(String.eq(s, "approve"), WApprove{}, + word.is(String.eq(s, "summary"), WSummary{}, + word.is(String.eq(s, "statement"), WStatement{}, + word.is(String.eq(s, "card"), WCard{}, + word.is(String.eq(s, "dashboard"), WDashboard{}, + word.is(String.eq(s, "status"), WStatus{}, + word.is(String.eq(s, "pass"), WPass{}, + word.is(String.eq(s, "app"), WApp{}, + word.is(String.eq(s, "version"), WVersion{}, + word.is(String.eq(s, "answer"), WAnswer{}, + word.is(String.eq(s, "fraud"), WFraud{}, + word.is(String.eq(s, "refund"), WRefund{}, + WOther{})))))))))))))))))))))))) + +# A part of a path: a number, or a word. +type Token is Data: + N{value: Nat} + W{word: Part} + +def token.of(number: Maybe<&2, Nat>, word: Part) -> Token: + match number: + case Some{n}: + N{n} + case None{}: + W{word} + +def token(+s: String) -> Token: + token.of(Nat.read(s), word(s)) + +def tokens.keep(empty: Bool, +part: String, rest: +List) -> +List: + match empty: + case True{}: + rest + case False{}: + token(part) <> rest + +def tokens(parts: List<&2, String>) -> +List: + match parts: + case Nil{}: + [] + case +part <> rest: + tokens.keep(String.is_empty(part), part, tokens(rest)) + +# What a request asks for. +type Asked is Data: + Play{move: Bank.Move} + Summary{actor: T.Actor, account: Nat} + Statement{actor: T.Actor, account: Nat} + Card{actor: T.Actor, account: Nat} + Dashboard{actor: T.Actor, customer: Nat} + Status{transfer: Nat} + Page{} + # How much has been recorded: a page that watches this stays live. + Version{} + Unknown{} + # The same, answered with the asker's page: /app/c/1, /app/c/1/account/101/deposit/5000. + Viewing{actor: T.Actor, who: Nat, asked: Asked} + +def route.for(+actor: T.Actor, +who: Nat, rest: +List) -> Asked: + match rest: + case W{WRegister{}} <> N{username} <> Nil{}: + Play{Bank.Register{actor, Customer.RegisterCustomer{who, username}}} + case W{WAccount{}} <> N{id} <> W{WDeposit{}} <> N{amount} <> Nil{}: + Play{Bank.ToAccount{id, actor, Account.DepositMoney{U32.from_nat(amount)}}} + case W{WAccount{}} <> N{id} <> W{WWithdraw{}} <> N{amount} <> Nil{}: + Play{Bank.ToAccount{id, actor, Account.WithdrawMoney{U32.from_nat(amount)}}} + case W{WAccount{}} <> N{id} <> W{WClose{}} <> Nil{}: + Play{Bank.ToAccount{id, actor, Account.CloseAccount{}}} + case W{WAccount{}} <> N{id} <> W{WFreeze{}} <> Nil{}: + Play{Bank.ToAccount{id, actor, Account.FreezeAccount{}}} + case W{WAccount{}} <> N{id} <> W{WOwner{}} <> N{to} <> Nil{}: + Play{Bank.ToAccount{id, actor, Account.ChangeOwner{to}}} + case W{WAccount{}} <> N{id} <> W{WSummary{}} <> Nil{}: + Summary{actor, id} + case W{WAccount{}} <> N{id} <> W{WStatement{}} <> Nil{}: + Statement{actor, id} + case W{WAccount{}} <> N{id} <> W{WCard{}} <> Nil{}: + Card{actor, id} + case W{WCustomer{}} <> N{id} <> W{WDashboard{}} <> Nil{}: + Dashboard{actor, id} + case W{WTransfer{}} <> N{id} <> W{WRequest{}} <> N{source} <> N{destination} <> N{amount} <> Nil{}: + Play{Bank.ToTransfer{id, actor, + Transfer.RequestTransfer{source, destination, U32.from_nat(amount)}}} + case W{WTransfer{}} <> N{id} <> W{WApprove{}} <> Nil{}: + Play{Bank.ToTransfer{id, actor, Transfer.ApproveTransfer{}}} + case W{WTransfer{}} <> N{id} <> W{WStatus{}} <> Nil{}: + Status{id} + case _: + Unknown{} + +def route(path: +List) -> Asked: + match path: + case Nil{}: + Page{} + case W{WC{}} <> N{+id} <> rest: + route.for(T.ByCustomer{id}, id, rest) + case W{WA{}} <> N{+id} <> rest: + route.for(T.ByAgent{id}, id, rest) + case W{WPass{}} <> N{seconds} <> Nil{}: + Play{Bank.Pass{U32.from_nat(seconds)}} + case W{WVersion{}} <> Nil{}: + Version{} + case W{WApp{}} <> W{WC{}} <> N{+id} <> rest: + Viewing{T.ByCustomer{id}, id, route.for(T.ByCustomer{id}, id, rest)} + case W{WApp{}} <> W{WA{}} <> N{+id} <> rest: + Viewing{T.ByAgent{id}, id, route.for(T.ByAgent{id}, id, rest)} + case _: + Unknown{} + +# What a path asks for. +def asked(path: String) -> Asked: + route(tokens(String.split(path, '/'))) + +# Answering +# ========= + +def show_bool(b: Bool) -> String: + match b: + case True{}: + "true" + case False{}: + "false" + +def show_account_rejection(why: Account.AccountRejection) -> String: + match why: + case Account.AlreadyOpen{}: + "AlreadyOpen" + case Account.NotOpen{}: + "NotOpen" + case Account.NotOwner{}: + "NotOwner" + case Account.NotPermitted{}: + "NotPermitted" + case Account.Frozen{}: + "Frozen" + case Account.InsufficientFunds{balance, requested}: + "InsufficientFunds balance=" ++ U32.show(balance) ++ " requested=" ++ U32.show(requested) + case Account.DailyLimitExceeded{remaining}: + "DailyLimitExceeded remaining=" ++ U32.show(remaining) + case Account.BalanceNotZero{balance}: + "BalanceNotZero balance=" ++ U32.show(balance) + +def show_transfer_rejection(why: Transfer.TransferRejection) -> String: + match why: + case Transfer.AlreadyRequested{}: + "AlreadyRequested" + case Transfer.SameAccount{}: + "SameAccount" + case Transfer.NotPermitted{}: + "NotPermitted" + case Transfer.NotAwaitingApproval{}: + "NotAwaitingApproval" + +def show_registration_rejection(why: Customer.RegistrationRejection) -> String: + match why: + case Customer.AlreadyRegistered{}: + "AlreadyRegistered" + case Customer.NotTheCustomer{}: + "NotTheCustomer" + case Customer.UsernameTaken{}: + "UsernameTaken" + +# A response: whether the request was accepted, and what to say. +type Answer is Data: + Answer{status: String, body: String} + +def ok(body: String) -> Answer: + Answer{"200 OK", body} + +def rejected(why: String) -> Answer: + Answer{"409 Conflict", "{\"rejected\":\"" ++ why ++ "\"}"} + +def forbidden() -> Answer: + Answer{"403 Forbidden", "{\"error\":\"forbidden\"}"} + +def account_answer(decided: Account.Decided()) -> Answer: + match decided: + case Domain.Reject{why}: + rejected(show_account_rejection(why)) + case Domain.Record{events}: + ok("{\"recorded\":" ++ Nat.show(List.length(&2, Account.AccountEvent, events)) ++ "}") + +def transfer_answer(decided: Transfer.Decided()) -> Answer: + match decided: + case Domain.Reject{why}: + rejected(show_transfer_rejection(why)) + case Domain.Record{events}: + ok("{\"recorded\":" ++ Nat.show(List.length(&2, Transfer.TransferEvent, events)) ++ "}") + +def registration_answer(registration: Customer.Registration) -> Answer: + match registration: + case Customer.Refused{why}: + rejected(show_registration_rejection(why)) + case Customer.Accepted{on_customer, on_claim}: + ok("{\"recorded\":2}") + +# What the caller is told about a move, from the bank before it. +def told(+world: Bank.World(), move: Bank.Move) -> Answer: + match move: + case Bank.ToAccount{id, actor, command}: + account_answer(Bank.ask_account(world, id, actor, command)) + case Bank.ToTransfer{id, actor, command}: + transfer_answer(Bank.ask_transfer(world, id, actor, command)) + case Bank.Register{actor, command}: + registration_answer(Bank.ask_register(world, actor, command)) + case _: + ok("{}") + +def show_summary(read: Views.Read) -> Answer: + match read: + case Views.Forbidden{}: + forbidden() + case Views.Allowed{Views.Summary{opened, customer, balance, frozen, closed}}: + ok("{\"opened\":" ++ show_bool(opened) ++ ",\"customer\":" ++ Nat.show(customer) + ++ ",\"balance\":" ++ U32.show(balance) ++ ",\"frozen\":" ++ show_bool(frozen) + ++ ",\"closed\":" ++ show_bool(closed) ++ "}") + +def show_kind(kind: Views.LineKind) -> String: + match kind: + case Views.Deposit{}: + "deposit" + case Views.Withdrawal{}: + "withdrawal" + case Views.TransferIn{}: + "transfer-in" + case Views.TransferOut{}: + "transfer-out" + case Views.RefundIn{}: + "refund" + case Views.Settlement{}: + "settlement" + +def show_lines(lines: +List) -> String: + match lines: + case Nil{}: + "" + case Views.Line{kind, amount, balance} <> rest: + "{\"kind\":\"" ++ show_kind(kind) ++ "\",\"amount\":" ++ U32.show(amount) + ++ ",\"balance\":" ++ U32.show(balance) ++ "}\n" ++ show_lines(rest) + +def show_statement(read: Views.Read<+List>) -> Answer: + match read: + case Views.Forbidden{}: + forbidden() + case Views.Allowed{lines}: + ok(show_lines(lines)) + +def show_cards(cards: +List) -> String: + match cards: + case Nil{}: + "" + case Views.Card{customer, balance, frozen} <> rest: + "{\"customer\":" ++ Nat.show(customer) ++ ",\"balance\":" ++ U32.show(balance) + ++ ",\"frozen\":" ++ show_bool(frozen) ++ "}\n" ++ show_cards(rest) + +def guard_cards(may: Bool, cards: +List) -> Answer: + match may: + case True{}: + ok(show_cards(cards)) + case False{}: + forbidden() + +def show_holdings(holdings: +List) -> String: + match holdings: + case Nil{}: + "" + case Views.Holding{account, balance} <> rest: + "{\"account\":" ++ Nat.show(account) ++ ",\"balance\":" ++ U32.show(balance) ++ "}\n" + ++ show_holdings(rest) + +def guard_holdings(may: Bool, holdings: +List) -> Answer: + match may: + case True{}: + ok(show_holdings(holdings)) + case False{}: + forbidden() + +def show_progress(progress: Views.Progress) -> String: + match progress: + case Views.NotRequested{}: + "not-requested" + case Views.AwaitingApproval{}: + "awaiting-approval" + case Views.Pending{}: + "pending" + case Views.InFlight{}: + "in-flight" + case Views.Completed{}: + "completed" + case Views.Failed{reason}: + "failed" + +def page() -> String: + "Bank

Bank

" + ++ "

As customer account " + ++ " amount

" + ++ "

" + ++ "" + ++ "" + ++ "" + ++ "

" + ++ "

Answer

Summary

"
+    ++ "

Statement

"
+
+# Pages
+# =====
+#
+# A page is a function of the bank and of who is looking, through the same
+# guarded reads the server answers; each link on it sends a command.
+
+def money.cents(cents: U32) -> String:
+  U32.show(cents)
+
+def link(href: String, label: String) -> String:
+  "" ++ label ++ " "
+
+def line_rows(lines: +List) -> String:
+  match lines:
+    case Nil{}:
+      ""
+    case Views.Line{kind, amount, balance} <> rest:
+      "" ++ show_kind(kind) ++ "" ++ U32.show(amount) ++ ""
+        ++ U32.show(balance) ++ "" ++ line_rows(rest)
+
+def direction(incoming: Bool) -> String:
+  match incoming:
+    case True{}:
+      "in"
+    case False{}:
+      "out"
+
+def moved_rows(moved: +List, +world: Bank.World()) -> String:
+  match moved:
+    case Nil{}:
+      ""
+    case Views.Moved{+transfer, amount, incoming} <> rest:
+      "" ++ Nat.show(transfer) ++ "" ++ direction(incoming) ++ ""
+        ++ U32.show(amount) ++ "" ++ show_progress(Views.transfer_status(world, transfer))
+        ++ "" ++ moved_rows(rest, world)
+
+def account_part.shown(read: Views.Read, +base: String, +world: Bank.World(), +account: Nat)
+  -> String:
+  match read:
+    case Views.Forbidden{}:
+      "

You may not see this account.

" + case Views.Allowed{Views.Summary{opened, customer, balance, frozen, closed}}: + "

Account " ++ Nat.show(account) ++ "

Balance " ++ U32.show(balance) + ++ " cents, frozen " ++ show_bool(frozen) ++ ", closed " ++ show_bool(closed) ++ "

" + ++ link(base ++ "/account/" ++ Nat.show(account) ++ "/deposit/10000", "Deposit 10000") + ++ link(base ++ "/account/" ++ Nat.show(account) ++ "/withdraw/2500", "Withdraw 2500") + ++ link(base ++ "/transfer/" ++ U32.show(Bank.now_of(world)) ++ "/request/" + ++ Nat.show(account) ++ "/102/4000", "Send 4000 to account 102") + ++ link(base ++ "/transfer/" ++ U32.show(U32.add(Bank.now_of(world), 1)) ++ "/request/" + ++ Nat.show(account) ++ "/102/20000", "Send 20000 to account 102") + ++ "

" + ++ line_rows(Views.statement(Bank.log_of(world), account)) ++ "
StatementAmountBalance
" + ++ "" + ++ moved_rows(Views.moved(Bank.log_of(world), account), world) ++ "
TransferDirectionAmountStatus
" + +def account_part(+actor: T.Actor, +base: String, +world: Bank.World(), +account: Nat) -> String: + account_part.shown(Views.read_summary(actor, Bank.log_of(world), account), base, world, account) + +def waiting.row(waits: Bool, +id: Nat, +base: String) -> String: + match waits: + case True{}: + "

Transfer " ++ Nat.show(id) ++ " waits for approval. " + ++ link(base ++ "/transfer/" ++ Nat.show(id) ++ "/approve", "Approve") ++ "

" + case False{}: + "" + +def is_waiting(state: Transfer.TransferState) -> Bool: + match state: + case Transfer.AwaitingApproval{details}: + True{} + case _: + False{} + +# The transfers that wait for approval, each with a link to approve it. +def waiting(log: +List, +world: Bank.World(), +base: String) -> String: + match log: + case Nil{}: + "" + case Bank.FromTransfer{+id, Transfer.TransferRequested{details, needs}} <> rest: + waiting.row(is_waiting(Bank.transfer(world, id)), id, base) ++ waiting(rest, world, base) + case _ <> rest: + waiting(rest, world, base) + +def view.body(actor: T.Actor, +who: Nat, +base: String, +world: Bank.World()) -> String: + match actor: + case T.ByCustomer{id}: + "

" ++ link(base ++ "/register/" ++ Nat.show(who), "Register") ++ link(base, "Refresh") + ++ link("/app/a/7", "Look as a support agent") ++ "

" + ++ account_part(T.ByCustomer{id}, base, world, Bank.main_account(who)) + case T.ByAgent{+id}: + "

" ++ link(base, "Refresh") ++ link("/app/c/1", "Look as customer 1") + ++ link("/app/c/2", "Look as customer 2") ++ "

" + ++ waiting(Bank.log_of(world), world, base) + ++ account_part(T.ByAgent{id}, base, world, 101n) + ++ account_part(T.ByAgent{id}, base, world, 102n) + case T.BySystem{id}: + "" + +def base_of(actor: T.Actor, who: Nat) -> String: + match actor: + case T.ByAgent{id}: + "/app/a/" ++ Nat.show(who) + case _: + "/app/c/" ++ Nat.show(who) + +# The page for whoever is looking, with what the last request answered. +def view(+actor: T.Actor, +who: Nat, note: String, +world: Bank.World()) -> String: + "Bank

Bank

" ++ note ++ "

" + ++ view.body(actor, who, base_of(actor, who), world) + ++ "" + +# Whether the Api offers the move to this actor: customers get the customer +# Api, and agents get both. +def offered.to(actor: T.Actor, customer: Bool, support: Bool) -> Bool: + match actor: + case T.ByCustomer{id}: + customer + case T.ByAgent{id}: + customer || support + case T.BySystem{id}: + False{} + +def offered(+move: Bank.Move) -> Bool: + match move: + case Bank.ToAccount{id, actor, command}: + offered.to(actor, Api.customer_api(move), Api.support_api(move)) + case Bank.ToTransfer{id, actor, command}: + offered.to(actor, Api.customer_api(move), Api.support_api(move)) + case Bank.Register{actor, command}: + True{} + case Bank.Pass{seconds}: + True{} + case _: + False{} + +# Outside systems +# =============== +# +# The server calls an outside system for each call the bank is waiting on, and +# writes what it answered to the journal ("answer/fraud/95"), so a replay +# never asks again. + +# The call the bank has waited on longest, if it waits on one. +type Waiting is Data: + NoCall{} + AskFraud{account: Nat, total: U32} + AskRefund{settlement: Nat, amount: U32} + +def call_waiting.first(calls: +List) -> Waiting: + match calls: + case Bank.FraudScore{account, total} <> rest: + AskFraud{account, total} + case Bank.Refund{settlement, amount} <> rest: + AskRefund{settlement, amount} + case Nil{}: + NoCall{} + +def call_waiting(world: Bank.World()) -> Waiting: + call_waiting.first(Bank.calls_of(world)) + +def stand_in.risk(risky: Bool) -> Nat: + match risky: + case True{}: + 95n + case False{}: + 10n + +# The stand-in for the fraud system: a day's outflow of 900.00 or more is risky. +def stand_in_risk(total: U32) -> Nat: + stand_in.risk(U32.is_le(90000, total)) + +# An answer from outside, as a journal line says it. +def answer_move(tokens: +List) -> Maybe<&2, Bank.Move>: + match tokens: + case W{WAnswer{}} <> W{WFraud{}} <> N{risk} <> Nil{}: + Some{Bank.AnswerFraud{risk}} + case W{WAnswer{}} <> W{WRefund{}} <> Nil{}: + Some{Bank.AnswerRefund{}} + case _: + None{} + +# What a request leaves and answers: the bank after it, whether it is to be +# written to the journal, and the response. +type Handled is Data: + Handled{world: Bank.World(), journal: Bool, answer: Answer} + +def handle.play(+world: Bank.World(), +move: Bank.Move, may: Bool) -> Handled: + match may: + case True{}: + Handled{Bank.play(world, move), True{}, told(world, move)} + case False{}: + Handled{world, False{}, forbidden()} + +# The page, after whatever was asked for on it. +def handle.viewing(+actor: T.Actor, +who: Nat, handled: Handled) -> Handled: + match handled: + case Handled{+world, journal, Answer{status, body}}: + Handled{world, journal, Answer{"200 OK", view(actor, who, body, world)}} + +def handle(+world: Bank.World(), what: Asked) -> Handled: + match what: + case Play{+move}: + handle.play(world, move, offered(move)) + case Summary{actor, account}: + Handled{world, False{}, show_summary(Views.read_summary(actor, Bank.log_of(world), account))} + case Statement{actor, account}: + Handled{world, False{}, + show_statement(Views.account_ledger(actor, Bank.log_of(world), account))} + case Card{actor, +account}: + Handled{world, False{}, + guard_cards(Views.owned_by(actor, Views.summary(Bank.log_of(world), account)), + Views.cards(Bank.log_of(world), account))} + case Dashboard{actor, +customer}: + Handled{world, False{}, + guard_holdings(T.may_act(actor, customer), + Views.dashboard([Bank.main_account(customer)], Bank.log_of(world), customer))} + case Status{transfer}: + Handled{world, False{}, + ok("{\"status\":\"" ++ show_progress(Views.transfer_status(world, transfer)) ++ "\"}")} + case Page{}: + Handled{world, False{}, Answer{"200 OK", page()}} + case Version{}: + Handled{world, False{}, + ok(Nat.show(List.length(&2, Bank.Emitted, Bank.log_of(world))))} + case Unknown{}: + Handled{world, False{}, Answer{"404 Not Found", "{\"error\":\"no such route\"}"}} + case Viewing{actor, who, Unknown{}}: + Handled{world, False{}, Answer{"200 OK", view(actor, who, "", world)}} + case Viewing{actor, who, inner}: + handle.viewing(actor, who, handle(world, inner)) + +def replay.one(handled: Handled) -> Bank.World(): + match handled: + case Handled{world, journal, answer}: + world + +def apply_line.go(+world: Bank.World(), +line: String, answer: Maybe<&2, Bank.Move>) + -> Bank.World(): + match answer: + case Some{move}: + Bank.play(world, move) + case None{}: + replay.one(handle(world, asked(line))) + +# The bank after one journal line: a request, or an answer from outside. +def apply_line(+world: Bank.World(), +line: String) -> Bank.World(): + apply_line.go(world, line, answer_move(tokens(String.split(line, '/')))) + +# The bank a journal leaves: its lines, replayed in order. +def replay(lines: List<&2, String>, +world: Bank.World()) -> Bank.World(): + match lines: + case Nil{}: + world + case +line <> rest: + replay(rest, apply_line(world, line)) + +# Serving +# ======= + +# The wall clock, in seconds since 1970. Base has none, so this is an effect +# of the server's own. +def Clock.unix() -> IO(U32): + import "./clock.c" + import "./clock.js" + +# The bank once the wall clock is taken into account: whether time moved, the +# journal line that says so, and the bank after it. +type Ticked is Data: + Ticked{world: Bank.World(), moved: Bool, line: String} + +def tick.go(moved: Bool, +world: Bank.World(), +by: U32) -> Ticked: + match moved: + case True{}: + Ticked{Bank.play(world, Bank.Pass{by}), True{}, "/pass/" ++ U32.show(by)} + case False{}: + Ticked{world, False{}, ""} + +def tick(+world: Bank.World(), +now: U32) -> Ticked: + tick.go(U32.is_lt(Bank.now_of(world), now), world, U32.sub(now, Bank.now_of(world))) + +def response(answer: Answer) -> String: + match answer: + case Answer{status, body}: + "HTTP/1.1 " ++ status ++ "\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n" ++ body + +def second(parts: List<&2, String>) -> String: + match parts: + case first <> path <> rest: + path + case _: + "/" + +# The path of a request, from its first line: "GET /path HTTP/1.1". +def path_of(request: String) -> String: + second(String.split(request, ' ')) + +def journal_written(m: File & Result<&1, &1, U32 & String, Unit>) -> IO(Unit): + (f, r) = m + File.close(f) + +def journal_append(path: String, line: String) -> IO(Unit): + do IO: + f : File <- IO.try(File, File.open(path, "a")) + w : File & Result<&1, &1, U32 & String, Unit> <- File.write(f, line ++ "\n") + journal_written(w) + +# Writes a request that changes the bank to the journal. +def keep(wrote: Bool, journal: String, path: String) -> IO(Unit): + match wrote: + case True{}: + journal_append(journal, path) + case False{}: + IO.pure(Unit, Unit{}) + +def sent(m: Socket & Result<&1, &1, (U32 & String) & List<&2, U32>, Unit>) -> IO(Unit): + (s, r) = m + Socket.close(s) + +def risk_of(ran: Result<&1, &1, U32 & String, U32 & (String & String)>, otherwise: Nat) -> Nat: + match ran: + case Done{(status, (out, err))}: + Maybe.default(&2, Nat, Nat.read(String.trim(out)), otherwise) + case Fail{e}: + otherwise + +# FraudCheck.score: asks the service at FRAUD_URL for a risk out of 100, with +# curl. With no FRAUD_URL, a stand-in answers. +def fraud_score(set: Result<&1, &1, U32 & String, String>, account: Nat, +total: U32) -> IO(Nat): + match set: + case Fail{e}: + IO.pure(Nat, stand_in_risk(total)) + case Done{url}: + do IO: + ran : Result<&1, &1, U32 & String, U32 & (String & String)> <- Process.run("curl", + ["-fsS", "--max-time", "10", + url ++ "?account=" ++ Nat.show(account) ++ "&amount=" ++ U32.show(total)], + "", 65536, 15000) + return risk_of(ran, stand_in_risk(total)) + +def refunded(ran: Result<&1, &1, U32 & String, U32 & (String & String)>) -> Unit: + Unit{} + +# Payments.refund: asks the service at PAYMENTS_URL to refund, with curl. +def refund(set: Result<&1, &1, U32 & String, String>, settlement: Nat, amount: U32) -> IO(Unit): + match set: + case Fail{e}: + IO.pure(Unit, Unit{}) + case Done{url}: + do IO: + ran : Result<&1, &1, U32 & String, U32 & (String & String)> <- Process.run("curl", + ["-fsS", "--max-time", "10", + url ++ "?settlement=" ++ Nat.show(settlement) ++ "&amount=" ++ U32.show(amount)], + "", 65536, 15000) + return refunded(ran) + +# Calls the outside systems the bank is waiting on, until none is left. Each +# answer is written to the journal before the bank takes it. +def call_outside(fuel: Nat, +journal: String, +world: Bank.World(), next: Waiting) + -> IO(Bank.World()): + match fuel next: + case 0n _: + IO.pure(Bank.World(), world) + case 1n+p NoCall{}: + IO.pure(Bank.World(), world) + case 1n+p AskFraud{account, total}: + do IO: + set : Result<&1, &1, U32 & String, String> <- IO.get_env("FRAUD_URL") + +risk : Nat <- fraud_score(set, account, total) + journal_append(journal, "answer/fraud/" ++ Nat.show(risk)) + call_outside(p, journal, Bank.play(world, Bank.AnswerFraud{risk}), + call_waiting(Bank.play(world, Bank.AnswerFraud{risk}))) + case 1n+p AskRefund{settlement, amount}: + do IO: + set : Result<&1, &1, U32 & String, String> <- IO.get_env("PAYMENTS_URL") + refund(set, settlement, amount) + journal_append(journal, "answer/refund") + call_outside(p, journal, Bank.play(world, Bank.AnswerRefund{}), + call_waiting(Bank.play(world, Bank.AnswerRefund{}))) + +def finish(s: Socket, +journal: String, path: String, handled: Handled) -> IO(Bank.World()): + match handled: + case Handled{+world, wrote, answer}: + do IO: + keep(wrote, journal, path) + after : Bank.World() <- call_outside(16n, journal, world, call_waiting(world)) + m : Socket & Result<&1, &1, (U32 & String) & List<&2, U32>, Unit> <- TCP.send(s, response(answer)) + sent(m) + return after + +def respond(s: Socket, +journal: String, +path: String, ticked: Ticked) -> IO(Bank.World()): + match ticked: + case Ticked{+world, moved, line}: + do IO: + keep(moved, journal, line) + finish(s, journal, path, handle(world, asked(path))) + +def unread(s: Socket, world: Bank.World()) -> IO(Bank.World()): + do IO: + Socket.close(s) + return world + +def reply( + m: Socket & Result<&1, &1, U32 & String, Maybe<&1, String>>, +world: Bank.World(), journal: String, + now: U32 +) -> IO(Bank.World()): + (s, r) = m + match r: + case Done{Some{request}}: + respond(s, journal, path_of(request), tick(world, now)) + case Done{None{}}: + unread(s, world) + case Fail{e}: + unread(s, world) + +def talk(s: Socket, +world: Bank.World(), journal: String) -> IO(Bank.World()): + do IO: + read : Socket & Result<&1, &1, U32 & String, Maybe<&1, String>> <- TCP.recv(s, 8192) + now : U32 <- Clock.unix() + reply(read, world, journal, now) + +# Handles one connection, then goes on with the listener and the bank it left. +def conn( + m: Listener & Result<&1, &1, U32 & String, Socket>, +world: Bank.World(), journal: String, + go_on: Listener -> @+w: Bank.World() -> IO(Unit) +) -> IO(Unit): + (l, r) = m + do IO: + s : Socket <- IO.pass(Socket, r) + w : Bank.World() <- talk(s, world, journal) + go_on(l, w) + +# One request at a time, each from the bank the last one left. +def serve(fuel: Nat, l: Listener, +world: Bank.World(), +journal: String) -> IO(Unit): + match fuel: + case 0n: + Listener.close(l) + case 1n+p: + do IO: + m : Listener & Result<&1, &1, U32 & String, Socket> <- TCP.accept(l) + conn(m, world, journal, l2 => +w2 => serve(p, l2, w2, journal)) + +def load.done(m: File & Result<&1, &1, U32 & String, String>) -> IO(Bank.World()): + (f, r) = m + match r: + case Done{text}: + do IO: + File.close(f) + return replay(String.lines(text), Bank.start()) + case Fail{e}: + do IO: + File.close(f) + return Bank.start() + +def load.read(opened: Result<&1, &1, U32 & String, File>) -> IO(Bank.World()): + match opened: + case Fail{e}: + IO.pure(Bank.World(), Bank.start()) + case Done{f}: + do IO: + m : File & Result<&1, &1, U32 & String, String> <- File.read(f, 16777216) + load.done(m) + +# The bank the journal leaves, or a new one when there is no journal. +def load(journal: String) -> IO(Bank.World()): + do IO: + opened : Result<&1, &1, U32 & String, File> <- File.open(journal, "r") + load.read(opened) + +# Where to listen: BANK_HOST, or this machine only. +def host_of(set: Result<&1, &1, U32 & String, String>) -> String: + match set: + case Done{host}: + host + case Fail{e}: + "127.0.0.1" + +def main() -> IO(Unit): + do IO: + world : Bank.World() <- load("bank.journal") + set : Result<&1, &1, U32 & String, String> <- IO.get_env("BANK_HOST") + l : Listener <- IO.try(Listener, TCP.listen(host_of(set), 8788)) + IO.print("Bank: serving on port 8788, kept in bank.journal") + serve(4294967295n, l, world, "bank.journal") diff --git a/packages/alchemy-bend/examples/bank/Stories.bend b/packages/alchemy-bend/examples/bank/Stories.bend new file mode 100644 index 00000000000..ace6c961bbd --- /dev/null +++ b/packages/alchemy-bend/examples/bank/Stories.bend @@ -0,0 +1,127 @@ +# Stories: examples of what the bank does. Each is the world after a sequence +# of moves; the laws in LAWS.bend say what the bank looks like in it. + +import Base +import ./Types.bend as T +import ./Account.bend as Account +import ./Transfer.bend as Transfer +import ./Customer.bend as Customer +import ./Bank.bend as Bank + +def sam() -> T.Actor: + T.ByCustomer{1n} + +def alex() -> T.Actor: + T.ByCustomer{2n} + +def support() -> T.Actor: + T.ByAgent{7n} + +# Account 1 is Sam's, with this much in it. +def sams_account(amount: U32) -> Bank.World(): + Bank.run([ + Bank.ToAccount{1n, sam(), Account.OpenAccount{1n}}, + Bank.ToAccount{1n, sam(), Account.DepositMoney{amount}} + ], Bank.start()) + +# Account 1 is Sam's, with this much in it, and account 2 is Alex's. +def two_accounts(amount: U32) -> Bank.World(): + Bank.run([Bank.ToAccount{2n, alex(), Account.OpenAccount{2n}}], sams_account(amount)) + +def registering() -> Bank.World(): + Bank.run([Bank.Register{sam(), Customer.RegisterCustomer{1n, 7n}}], Bank.start()) + +def withdrawing() -> Bank.World(): + Bank.run([Bank.ToAccount{1n, sam(), Account.WithdrawMoney{30}}], sams_account(100)) + +# Two withdrawals cross the review threshold; the fraud system finds no risk. +def two_withdrawals() -> Bank.World(): + Bank.run([ + Bank.ToAccount{1n, sam(), Account.WithdrawMoney{40000}}, + Bank.ToAccount{1n, sam(), Account.WithdrawMoney{40000}}, + Bank.AnswerFraud{10n} + ], sams_account(300000)) + +def the_next_day() -> Bank.World(): + Bank.run([ + Bank.Pass{86400}, + Bank.ToAccount{1n, sam(), Account.WithdrawMoney{30000}} + ], two_withdrawals()) + +def frozen_by_support() -> Bank.World(): + Bank.run([ + Bank.ToAccount{1n, support(), Account.FreezeAccount{}}, + Bank.ToAccount{1n, support(), Account.FreezeAccount{}} + ], sams_account(100)) + +def a_risky_withdrawal() -> Bank.World(): + Bank.run([Bank.ToAccount{1n, sam(), Account.WithdrawMoney{60000}}], sams_account(90000)) + +def found_risky() -> Bank.World(): + Bank.run([Bank.AnswerFraud{95n}], a_risky_withdrawal()) + +def split_withdrawals() -> Bank.World(): + Bank.run([ + Bank.ToAccount{1n, sam(), Account.WithdrawMoney{30000}}, + Bank.ToAccount{1n, sam(), Account.WithdrawMoney{30000}} + ], sams_account(90000)) + +# The account is closed while the fraud check is pending, and found risky after. +def closed_while_checked() -> Bank.World(): + Bank.run([ + Bank.ToAccount{1n, sam(), Account.WithdrawMoney{60000}}, + Bank.ToAccount{1n, sam(), Account.CloseAccount{}}, + Bank.AnswerFraud{95n} + ], sams_account(60000)) + +def a_transfer() -> Bank.World(): + Bank.run([Bank.ToTransfer{1n, sam(), Transfer.RequestTransfer{1n, 2n, 40}}], two_accounts(100)) + +def someone_elses_money() -> Bank.World(): + Bank.run([Bank.ToTransfer{1n, alex(), Transfer.RequestTransfer{1n, 2n, 40}}], two_accounts(100)) + +def a_large_transfer() -> Bank.World(): + Bank.run([Bank.ToTransfer{1n, sam(), Transfer.RequestTransfer{1n, 2n, 20000}}], + two_accounts(50000)) + +def approved() -> Bank.World(): + Bank.run([ + Bank.ToTransfer{1n, support(), Transfer.ApproveTransfer{}}, + Bank.Pass{86400} + ], a_large_transfer()) + +def expired() -> Bank.World(): + Bank.run([Bank.Pass{86400}], a_large_transfer()) + +# Alex's account is closed before Sam's transfer to it. +def to_a_closed_account() -> Bank.World(): + Bank.run([ + Bank.ToAccount{2n, alex(), Account.CloseAccount{}}, + Bank.ToTransfer{1n, sam(), Transfer.RequestTransfer{1n, 2n, 40}} + ], two_accounts(100)) + +def a_settlement_on_a_closed_account() -> Bank.World(): + Bank.run([ + Bank.ToAccount{2n, alex(), Account.CloseAccount{}}, + Bank.ToAccount{2n, Bank.system(), Account.RecordSettlement{9n, 500}} + ], two_accounts(100)) + +def reassigned() -> Bank.World(): + Bank.run([Bank.ToAccount{1n, support(), Account.ChangeOwner{2n}}], sams_account(100)) + +# One step at a time: Alex closes their account after Sam's transfer was +# debited and before it is credited, so the saga refunds it. +def closed_between_two_steps() -> Bank.World(): + Bank.steps([ + Bank.ToTransfer{1n, sam(), Transfer.RequestTransfer{1n, 2n, 40}}, + Bank.Deliver{0n}, + Bank.Advance{0n}, + Bank.ToAccount{2n, alex(), Account.CloseAccount{}}, + Bank.Advance{0n}, + Bank.Advance{0n}, + Bank.Advance{0n} + ], two_accounts(100)) + +# A fault: the request for a transfer reaches the policies three times. +def requested_three_times() -> Bank.World(): + Bank.run([Bank.Redeliver{3n}, Bank.Redeliver{3n}], a_transfer()) diff --git a/packages/alchemy-bend/examples/bank/Transfer.bend b/packages/alchemy-bend/examples/bank/Transfer.bend new file mode 100644 index 00000000000..926529ea83f --- /dev/null +++ b/packages/alchemy-bend/examples/bank/Transfer.bend @@ -0,0 +1,176 @@ +# A transfer between two accounts. Large transfers wait for approval until +# their window closes; approval and expiry are commands on this one instance, +# so exactly one of them wins. + +import Base +import ../../Domain.bend as Domain +import ./Types.bend as T + +# What a transfer moves, and for whom. +type Details is Data: + Details{source: Nat, destination: Nat, amount: U32, requested_by: T.Actor} + +# Why a transfer failed. +type Reason is Data: + NotApprovedInTime{} + SourceNotOpen{} + NotYourAccount{} + SourceFrozen{} + InsufficientFunds{} + DestinationNotOpen{} + Refused{} + +type TransferState is Data: + New{} + AwaitingApproval{details: Details} + Pending{details: Details} + Completed{} + Failed{reason: Reason} + +type TransferCommand is Data: + RequestTransfer{source: Nat, destination: Nat, amount: U32} + # A support agent approves a large transfer before its window closes. + ApproveTransfer{} + # The approval window closed. It reports a fact, so it is never rejected. + ExpireTransfer{} + # Reports an outcome, so it is never rejected. + CompleteTransfer{} + FailTransfer{reason: Reason} + +type TransferEvent is Data: + TransferRequested{details: Details, needs_approval: Bool} + TransferApproved{details: Details, approved_by: T.Actor} + TransferCompleted{} + TransferFailed{reason: Reason} + +type TransferRejection is Data: + AlreadyRequested{} + SameAccount{} + NotPermitted{} + NotAwaitingApproval{} + +def Decided() -> Data: + Domain.Decided + +# Transfers of at least this many cents wait for a support agent's approval. +def approval_threshold() -> U32: + 10000 + +def initial() -> TransferState: + New{} + +def request.go(same: Bool, large: Bool, details: Details) -> Decided(): + match same: + case True{}: + Domain.Reject{SameAccount{}} + case False{}: + Domain.Record{[TransferRequested{details, large}]} + +def approve.go(agent: Bool, details: Details, by: T.Actor) -> Decided(): + match agent: + case True{}: + Domain.Record{[TransferApproved{details, by}]} + case False{}: + Domain.Reject{NotPermitted{}} + +# An approval of a transfer that is not waiting for one. +def approve.late(agent: Bool) -> Decided(): + match agent: + case True{}: + Domain.Reject{NotAwaitingApproval{}} + case False{}: + Domain.Reject{NotPermitted{}} + +# A command on a transfer that is neither waiting for approval nor pending. +def decide.settled(+actor: T.Actor, is_new: Bool, command: TransferCommand) -> Decided(): + match is_new command: + case True{} RequestTransfer{+source, +destination, +amount}: + request.go(Nat.is_eq(source, destination), U32.is_le(approval_threshold(), amount), + Details{source, destination, amount, actor}) + case False{} RequestTransfer{source, destination, amount}: + Domain.Reject{AlreadyRequested{}} + case _ ApproveTransfer{}: + approve.late(T.is_agent(actor)) + case _ _: + Domain.Record{[]} + +def decide.awaiting(+actor: T.Actor, details: Details, command: TransferCommand) -> Decided(): + match command: + case RequestTransfer{source, destination, amount}: + Domain.Reject{AlreadyRequested{}} + case ApproveTransfer{}: + approve.go(T.is_agent(actor), details, actor) + case ExpireTransfer{}: + Domain.Record{[TransferFailed{NotApprovedInTime{}}]} + case _: + Domain.Record{[]} + +def decide.pending(+actor: T.Actor, command: TransferCommand) -> Decided(): + match command: + case RequestTransfer{source, destination, amount}: + Domain.Reject{AlreadyRequested{}} + case ApproveTransfer{}: + approve.late(T.is_agent(actor)) + case ExpireTransfer{}: + Domain.Record{[]} + case CompleteTransfer{}: + Domain.Record{[TransferCompleted{}]} + case FailTransfer{reason}: + Domain.Record{[TransferFailed{reason}]} + +def decide(context: T.Context, state: TransferState, command: TransferCommand) -> Decided(): + match context state: + case T.Context{actor, day} New{}: + decide.settled(actor, True{}, command) + case T.Context{actor, day} AwaitingApproval{details}: + decide.awaiting(actor, details, command) + case T.Context{actor, day} Pending{details}: + decide.pending(actor, command) + case T.Context{actor, day} Completed{}: + decide.settled(actor, False{}, command) + case T.Context{actor, day} Failed{reason}: + decide.settled(actor, False{}, command) + +def requested(needs_approval: Bool, details: Details) -> TransferState: + match needs_approval: + case True{}: + AwaitingApproval{details} + case False{}: + Pending{details} + +def evolve(context: T.Context, state: TransferState, event: TransferEvent) -> TransferState: + match event: + case TransferRequested{details, needs_approval}: + requested(needs_approval, details) + case TransferApproved{details, approved_by}: + Pending{details} + case TransferCompleted{}: + Completed{} + case TransferFailed{reason}: + Failed{reason} + +def Sent() -> Data: + Domain.Sent + +def step(+context: T.Context, +state: TransferState, command: TransferCommand) -> TransferState: + Domain.step(~T.Context, ~TransferState, ~TransferCommand, ~TransferEvent, ~TransferRejection, + ~decide, ~evolve, context, state, command) + +def replay(commands: List, +state: TransferState) -> TransferState: + Domain.replay(~T.Context, ~TransferState, ~TransferCommand, ~TransferEvent, ~TransferRejection, + ~decide, ~evolve, commands, state) + +def distinct(details: Details) -> Bool: + match details: + case Details{source, destination, amount, requested_by}: + Bool.not(Nat.is_eq(source, destination)) + +# RULE: a transfer moves between two different accounts. +def between_two_accounts(state: TransferState) -> Bool: + match state: + case AwaitingApproval{details}: + distinct(details) + case Pending{details}: + distinct(details) + case _: + True{} diff --git a/packages/alchemy-bend/examples/bank/Types.bend b/packages/alchemy-bend/examples/bank/Types.bend new file mode 100644 index 00000000000..18043287113 --- /dev/null +++ b/packages/alchemy-bend/examples/bank/Types.bend @@ -0,0 +1,38 @@ +# What the whole bank shares. Ids are numbers. Money is whole cents and time is +# whole seconds, both 32-bit: a sum past 4,294,967,295 wraps. + +import Base + +# Who is acting. +type Actor is Data: + ByCustomer{id: Nat} + ByAgent{id: Nat} + BySystem{id: Nat} + +# What a decision is made with: who asks, and on what day. +type Context is Data: + Context{actor: Actor, day: U32} + +def is_agent(actor: Actor) -> Bool: + match actor: + case ByAgent{id}: + True{} + case _: + False{} + +# Customers act on what is theirs; agents and the system on anything. +def may_act(actor: Actor, owner: Nat) -> Bool: + match actor: + case ByCustomer{id}: + Nat.is_eq(id, owner) + case _: + True{} + +def day_of(context: Context) -> U32: + match context: + case Context{actor, day}: + day + +# The day a moment falls on. +def day(now: U32) -> U32: + U32.div(now, 86400) diff --git a/packages/alchemy-bend/examples/bank/Views.bend b/packages/alchemy-bend/examples/bank/Views.bend new file mode 100644 index 00000000000..8e596592956 --- /dev/null +++ b/packages/alchemy-bend/examples/bank/Views.bend @@ -0,0 +1,365 @@ +# What is read from the bank. Each read is a function of the log of recorded +# events, so it can never disagree with what was recorded. + +import Base +import ./Types.bend as T +import ./Account.bend as Account +import ./Transfer.bend as Transfer +import ./Customer.bend as Customer +import ./Bank.bend as Bank + +# Customers read what is theirs; agents read anything. Nobody owns what +# nobody opened. +def must_own(actor: T.Actor, opened: Bool, owner: Nat) -> Bool: + match actor opened: + case T.ByAgent{id} _: + True{} + case _ False{}: + True{} + case T.ByCustomer{id} True{}: + Nat.is_eq(id, owner) + case T.BySystem{id} True{}: + False{} + +# What a guarded read answers. +type Read<-A: Data> is Data: + Forbidden{} + Allowed{value: A} + +# Streams of events +# ================= + +def account_events.keep(same: Bool, event: Account.AccountEvent, rest: +List) + -> +List: + match same: + case True{}: + event <> rest + case False{}: + rest + +# The events one account recorded, in order. +def account_events(log: +List, +id: Nat) -> +List: + match log: + case Nil{}: + [] + case Bank.FromAccount{on, event, day, seq} <> rest: + account_events.keep(Nat.is_eq(on, id), event, account_events(rest, id)) + case _ <> rest: + account_events(rest, id) + +def transfer_events.keep( + same: Bool, event: Transfer.TransferEvent, rest: +List +) -> +List: + match same: + case True{}: + event <> rest + case False{}: + rest + +# The events one transfer recorded, in order. +def transfer_events(log: +List, +id: Nat) -> +List: + match log: + case Nil{}: + [] + case Bank.FromTransfer{on, event} <> rest: + transfer_events.keep(Nat.is_eq(on, id), event, transfer_events(rest, id)) + case _ <> rest: + transfer_events(rest, id) + +# AccountSummary +# ============== + +# An account at a glance. +type Summary is Data: + Summary{opened: Bool, customer: Nat, balance: U32, frozen: Bool, closed: Bool} + +def no_summary() -> Summary: + Summary{False{}, 0n, 0, False{}, False{}} + +def summarize(summary: Summary, event: Account.AccountEvent) -> Summary: + match summary event: + case Summary{opened, customer, balance, frozen, closed} Account.AccountOpened{to}: + Summary{True{}, to, balance, frozen, closed} + case Summary{opened, customer, balance, frozen, closed} Account.OwnerChanged{previous, to}: + Summary{opened, to, balance, frozen, closed} + case Summary{opened, customer, balance, frozen, closed} Account.MoneyDeposited{amount, after}: + Summary{opened, customer, after, frozen, closed} + case Summary{opened, customer, balance, frozen, closed} Account.MoneyWithdrawn{amount, after}: + Summary{opened, customer, after, frozen, closed} + case Summary{opened, customer, balance, frozen, closed} Account.TransferDebited{t, amount, after}: + Summary{opened, customer, after, frozen, closed} + case Summary{opened, customer, balance, frozen, closed} Account.TransferCredited{t, amount, after}: + Summary{opened, customer, after, frozen, closed} + case Summary{opened, customer, balance, frozen, closed} Account.TransferRefunded{t, amount, after}: + Summary{opened, customer, after, frozen, closed} + case Summary{opened, customer, balance, frozen, closed} Account.SettlementReceived{s, amount, after}: + Summary{opened, customer, after, frozen, closed} + case Summary{opened, customer, balance, frozen, closed} Account.AccountFrozen{}: + Summary{opened, customer, balance, True{}, closed} + case Summary{opened, customer, balance, frozen, closed} Account.AccountClosed{}: + Summary{opened, customer, balance, frozen, True{}} + case s _: + s + +def summary_in(events: +List, summary: Summary) -> Summary: + match events: + case Nil{}: + summary + case event <> rest: + summary_in(rest, summarize(summary, event)) + +# An account's summary. +def summary(log: +List, id: Nat) -> Summary: + summary_in(account_events(log, id), no_summary()) + +def guard_summary(may: Bool, summary: Summary) -> Read: + match may: + case True{}: + Allowed{summary} + case False{}: + Forbidden{} + +def owned_by(actor: T.Actor, summary: Summary) -> Bool: + match summary: + case Summary{opened, customer, balance, frozen, closed}: + must_own(actor, opened, customer) + +# An account's summary, for its owner and agents. +def read_summary(actor: T.Actor, +log: +List, +id: Nat) -> Read: + guard_summary(owned_by(actor, summary(log, id)), summary(log, id)) + +# Statement +# ========= + +type LineKind is Data: + Deposit{} + Withdrawal{} + TransferIn{} + TransferOut{} + RefundIn{} + Settlement{} + +type Line is Data: + Line{kind: LineKind, amount: U32, balance: U32} + +# An account's money events as statement lines. +def lines(events: +List) -> +List: + match events: + case Nil{}: + [] + case Account.MoneyDeposited{amount, after} <> rest: + Line{Deposit{}, amount, after} <> lines(rest) + case Account.MoneyWithdrawn{amount, after} <> rest: + Line{Withdrawal{}, amount, after} <> lines(rest) + case Account.TransferCredited{t, amount, after} <> rest: + Line{TransferIn{}, amount, after} <> lines(rest) + case Account.TransferDebited{t, amount, after} <> rest: + Line{TransferOut{}, amount, after} <> lines(rest) + case Account.TransferRefunded{t, amount, after} <> rest: + Line{RefundIn{}, amount, after} <> lines(rest) + case Account.SettlementReceived{s, amount, after} <> rest: + Line{Settlement{}, amount, after} <> lines(rest) + case _ <> rest: + lines(rest) + +def statement(log: +List, id: Nat) -> +List: + lines(account_events(log, id)) + +# AccountLedger: one account's ledger, for its owner and agents. The Ledger +# projection gives it every money event the accounts record. +def guard_lines(may: Bool, rows: +List) -> Read<+List>: + match may: + case True{}: + Allowed{rows} + case False{}: + Forbidden{} + +def account_ledger(actor: T.Actor, +log: +List, +id: Nat) -> Read<+List>: + guard_lines(owned_by(actor, summary(log, id)), statement(log, id)) + +# AccountActivity +# =============== + +# What support needs to see about an account. +def activity(events: +List) -> +List: + match events: + case Nil{}: + [] + case Account.AccountFrozen{} <> rest: + Account.AccountFrozen{} <> activity(rest) + case Account.AccountClosed{} <> rest: + Account.AccountClosed{} <> activity(rest) + case Account.OwnerChanged{previous, to} <> rest: + Account.OwnerChanged{previous, to} <> activity(rest) + case Account.RefundStranded{t, amount} <> rest: + Account.RefundStranded{t, amount} <> activity(rest) + case Account.SettlementOnClosedAccount{s, amount} <> rest: + Account.SettlementOnClosedAccount{s, amount} <> activity(rest) + case _ <> rest: + activity(rest) + +def guard_events(may: Bool, events: +List) + -> Read<+List>: + match may: + case True{}: + Allowed{events} + case False{}: + Forbidden{} + +# Agents only. +def read_activity(actor: T.Actor, log: +List, id: Nat) + -> Read<+List>: + guard_events(T.is_agent(actor), activity(account_events(log, id))) + +# AccountCard +# =========== + +# A card for an account: a log per account that clients follow. The +# AccountCards projection appends one on every change to the summary. +type Card is Data: + Card{customer: Nat, balance: U32, frozen: Bool} + +def changes_the_card(event: Account.AccountEvent) -> Bool: + match event: + case Account.MoneyDeposited{amount, after}: + True{} + case Account.MoneyWithdrawn{amount, after}: + True{} + case Account.TransferDebited{t, amount, after}: + True{} + case Account.TransferCredited{t, amount, after}: + True{} + case Account.TransferRefunded{t, amount, after}: + True{} + case Account.SettlementReceived{s, amount, after}: + True{} + case Account.AccountFrozen{}: + True{} + case _: + False{} + +def card_of(summary: Summary) -> Card: + match summary: + case Summary{opened, customer, balance, frozen, closed}: + Card{customer, balance, frozen} + +def cards.keep(changed: Bool, card: Card, rest: +List) -> +List: + match changed: + case True{}: + card <> rest + case False{}: + rest + +def cards_in(events: +List, +summary: Summary) -> +List: + match events: + case Nil{}: + [] + case +event <> rest: + cards.keep(changes_the_card(event), card_of(summarize(summary, event)), + cards_in(rest, summarize(summary, event))) + +def cards(log: +List, id: Nat) -> +List: + cards_in(account_events(log, id), no_summary()) + +# CustomerDashboard +# ================= + +# One of a customer's accounts, and its balance. +type Holding is Data: + Holding{account: Nat, balance: U32} + +def holdings.keep(mine: Bool, account: Nat, balance: U32, rest: +List) -> +List: + match mine: + case True{}: + Holding{account, balance} <> rest + case False{}: + rest + +def holding_of(+customer: Nat, +account: Nat, summary: Summary, rest: +List) + -> +List: + match summary: + case Summary{opened, owner, balance, frozen, closed}: + holdings.keep(opened && Nat.is_eq(owner, customer) && Bool.not(closed), account, balance, + rest) + +# A customer's open accounts among these, with their balances. An ownership +# change moves an account between dashboards, because the summary follows it. +def dashboard(accounts: List, +log: +List, +customer: Nat) -> +List: + match accounts: + case Nil{}: + [] + case +account <> rest: + holding_of(customer, account, summary(log, account), dashboard(rest, log, customer)) + +# TransferStatus +# ============== + +type Progress is Data: + NotRequested{} + AwaitingApproval{} + Pending{} + InFlight{} + Completed{} + Failed{reason: Transfer.Reason} + +def progress.debited(debited: Bool, waiting: Progress) -> Progress: + match debited: + case True{}: + InFlight{} + case False{}: + waiting + +def progress_of(state: Transfer.TransferState, debited: Bool) -> Progress: + match state: + case Transfer.New{}: + NotRequested{} + case Transfer.AwaitingApproval{details}: + AwaitingApproval{} + case Transfer.Pending{details}: + progress.debited(debited, Pending{}) + case Transfer.Completed{}: + Completed{} + case Transfer.Failed{reason}: + Failed{reason} + +def was_debited(log: +List, +transfer: Nat) -> Bool: + match log: + case Nil{}: + False{} + case Bank.FromAccount{on, Account.TransferDebited{t, amount, after}, day, seq} <> rest: + Nat.is_eq(t, transfer) || was_debited(rest, transfer) + case _ <> rest: + was_debited(rest, transfer) + +# Where a transfer stands, from the transfer's events and the accounts'. +def transfer_status(+world: Bank.World(), +transfer: Nat) -> Progress: + progress_of(Bank.transfer(world, transfer), was_debited(Bank.log_of(world), transfer)) + +# AccountTransfers +# ================ + +type Moved is Data: + Moved{transfer: Nat, amount: U32, incoming: Bool} + +def moved.one(out: Bool, into: Bool, +transfer: Nat, +amount: U32, rest: +List) + -> +List: + match out into: + case True{} True{}: + Moved{transfer, amount, False{}} <> Moved{transfer, amount, True{}} <> rest + case True{} False{}: + Moved{transfer, amount, False{}} <> rest + case False{} True{}: + Moved{transfer, amount, True{}} <> rest + case False{} False{}: + rest + +# The transfers in and out of an account: one transfer shows on both accounts. +def moved(log: +List, +account: Nat) -> +List: + match log: + case Nil{}: + [] + case Bank.FromTransfer{id, Transfer.TransferRequested{Transfer.Details{source, destination, amount, by}, needs}} <> rest: + moved.one(Nat.is_eq(source, account), Nat.is_eq(destination, account), id, amount, + moved(rest, account)) + case _ <> rest: + moved(rest, account) diff --git a/packages/alchemy-bend/examples/bank/clock.c b/packages/alchemy-bend/examples/bank/clock.c new file mode 100644 index 00000000000..97a8f3c6aa0 --- /dev/null +++ b/packages/alchemy-bend/examples/bank/clock.c @@ -0,0 +1,10 @@ +// Clock.unix: seconds since 1970, from the host's wall clock. +#include + +Term clock_unix_run(Env e, Term* f, IoWork* w) { + return (Term)(u32)time(NULL); +} + +static void __attribute__((constructor)) clock_unix_use(void) { + io_eff(CID(Clock.unix), clock_unix_run); +} diff --git a/packages/alchemy-bend/examples/bank/clock.js b/packages/alchemy-bend/examples/bank/clock.js new file mode 100644 index 00000000000..859f57301a6 --- /dev/null +++ b/packages/alchemy-bend/examples/bank/clock.js @@ -0,0 +1,6 @@ +// Clock.unix: seconds since 1970, from the host's wall clock. +function clock_unix() { + return Math.floor(Date.now() / 1000) >>> 0; +} + +io_eff(CID(Clock.unix), clock_unix); diff --git a/packages/alchemy-bend/examples/bank/durable-object/worker.mjs b/packages/alchemy-bend/examples/bank/durable-object/worker.mjs new file mode 100644 index 00000000000..8017080d2e3 --- /dev/null +++ b/packages/alchemy-bend/examples/bank/durable-object/worker.mjs @@ -0,0 +1,82 @@ +// The proved bank on a Cloudflare Durable Object. +// +// `bend Server.bend -o durable-object/Server.mjs` writes the module this +// imports: the bank's pure functions, compiled from Bend. The object keeps the +// journal in its storage, one entry per request that changed the bank, and +// replays it when it wakes. So the bank is where it was, with every saga where +// it stood, and one object is one writer. +import Bank from "./Server.mjs"; + +const list = (items) => items.reduceRight((tail, head) => ({ $: "Con", head, tail }), { $: "Nil" }); +const key = (n) => "journal:" + String(n).padStart(12, "0"); + +export class BankObject { + constructor(state, env) { + this.state = state; + this.env = env; + this.world = undefined; + this.entries = 0; + } + + async load() { + if (this.world !== undefined) return; + const stored = await this.state.storage.list({ prefix: "journal:" }); + const lines = [...stored.values()]; + this.entries = lines.length; + this.world = Bank.replay(list(lines), Bank["Bank:start"]()); + } + + // Writes the entries to storage, then takes the world they lead to. + async commit(lines, world) { + if (lines.length > 0) { + const writes = {}; + for (const line of lines) writes[key(this.entries++)] = line; + await this.state.storage.put(writes); + } + this.world = world; + } + + // FraudCheck.score and Payments.refund: the services at FRAUD_URL and + // PAYMENTS_URL, or stand-ins when they are not set. + async answer(call) { + if (call.$ === "AskFraud") { + const url = this.env.FRAUD_URL; + const risk = url + ? parseInt(await (await fetch(`${url}?account=${call.account}&amount=${call.total}`)).text(), 10) + : Bank.stand_in_risk(call.total); + return "answer/fraud/" + risk; + } + const url = this.env.PAYMENTS_URL; + if (url) await fetch(`${url}?settlement=${call.settlement}&amount=${call.amount}`); + return "answer/refund"; + } + + async fetch(request) { + await this.load(); + const path = new URL(request.url).pathname; + const lines = []; + const ticked = Bank.tick(this.world, Math.floor(Date.now() / 1000)); + if (ticked.moved) lines.push(ticked.line); + const handled = Bank.handle(ticked.world, Bank.asked(path)); + if (handled.journal) lines.push(path); + // Call the outside systems the bank is waiting on. Each answer is a + // journal line, so a replay never asks again. + let world = handled.world; + for (let call = Bank.call_waiting(world); call.$ !== "NoCall"; call = Bank.call_waiting(world)) { + const line = await this.answer(call); + lines.push(line); + world = Bank.apply_line(world, line); + } + await this.commit(lines, world); + return new Response(handled.answer.body, { + status: parseInt(handled.answer.status, 10), + headers: { "content-type": "text/html; charset=utf-8" }, + }); + } +} + +export default { + fetch(request, env) { + return env.BANK.get(env.BANK.idFromName("bank")).fetch(request); + }, +}; diff --git a/packages/alchemy-bend/examples/bank/durable-object/wrangler.toml b/packages/alchemy-bend/examples/bank/durable-object/wrangler.toml new file mode 100644 index 00000000000..b3392c39a00 --- /dev/null +++ b/packages/alchemy-bend/examples/bank/durable-object/wrangler.toml @@ -0,0 +1,11 @@ +name = "alchemy-bend-bank" +main = "worker.mjs" +compatibility_date = "2026-10-01" + +[[durable_objects.bindings]] +name = "BANK" +class_name = "BankObject" + +[[migrations]] +tag = "v1" +new_sqlite_classes = ["BankObject"] diff --git a/packages/alchemy-bend/examples/bank/host.mjs b/packages/alchemy-bend/examples/bank/host.mjs new file mode 100644 index 00000000000..16b9bbcfeb3 --- /dev/null +++ b/packages/alchemy-bend/examples/bank/host.mjs @@ -0,0 +1,26 @@ +// A host driving the proved bank: `bend Bank.bend -o build/Bank.mjs` writes the +// module this imports. Constructors cross as { $: "Name", ...fields }, and a +// number is a Nat. +import Bank from "./build/Bank.mjs"; + +const sam = { $: "ByCustomer", id: 1 }; +const alex = { $: "ByCustomer", id: 2 }; + +const moves = [ + { $: "Register", actor: sam, command: { $: "RegisterCustomer", customer: 1, username: 7 } }, + { $: "Register", actor: alex, command: { $: "RegisterCustomer", customer: 2, username: 8 } }, + { $: "ToAccount", id: 101, actor: sam, command: { $: "DepositMoney", amount: 100 } }, + { + $: "ToTransfer", + id: 1, + actor: sam, + command: { $: "RequestTransfer", source: 101, destination: 102, amount: 40 }, + }, +]; + +let world = Bank.start(); +for (const move of moves) world = Bank.play(world, move); + +console.log("Sam's account: ", JSON.stringify(Bank.account(world, 101))); +console.log("Alex's account:", JSON.stringify(Bank.account(world, 102))); +console.log("The transfer: ", JSON.stringify(Bank.transfer(world, 1))); diff --git a/packages/alchemy-lean/.dockerignore b/packages/alchemy-lean/.dockerignore new file mode 100644 index 00000000000..4996668e912 --- /dev/null +++ b/packages/alchemy-lean/.dockerignore @@ -0,0 +1,2 @@ +.lake +*.journal diff --git a/packages/alchemy-lean/.gitignore b/packages/alchemy-lean/.gitignore new file mode 100644 index 00000000000..5f6922565db --- /dev/null +++ b/packages/alchemy-lean/.gitignore @@ -0,0 +1,2 @@ +/.lake +*.journal diff --git a/packages/alchemy-lean/Alchemy.lean b/packages/alchemy-lean/Alchemy.lean new file mode 100644 index 00000000000..8989ab88414 --- /dev/null +++ b/packages/alchemy-lean/Alchemy.lean @@ -0,0 +1,45 @@ +import Alchemy.Aggregate +import Alchemy.Codec +import Alchemy.Signature +import Alchemy.Program +import Alchemy.View +import Alchemy.Model +import Alchemy.History +import Alchemy.Caused +import Alchemy.Engine +import Alchemy.Stored +import Alchemy.Refines +import Alchemy.Reads +import Alchemy.Rest +import Alchemy.Compose +import Alchemy.Behaviour +import Alchemy.Syntax +import Alchemy.Story +import Alchemy.Check +import Alchemy.Api +import Alchemy.Host +import Alchemy.Html +import Alchemy.Cloud.Access +import Alchemy.Cloud.Run +import Alchemy.Cloud.Effect +import Alchemy.Cloud.Layer +import Alchemy.Cloud.Graph +import Alchemy.Cloud.Sim +import Alchemy.Cloud.Tactics +import Alchemy.Cloud.AWS +import Alchemy.Cloud.Hosted +import Alchemy.Cloud.Tell +import Alchemy.Cloud.Laws +import Alchemy.Cloud.AWSLaws +import Alchemy.Cloud.HostedLaws +import Alchemy.Cloud.AWSJournal +import Alchemy.Cloud.Host +import Alchemy.Cloud.Cloudflare +import Alchemy.Cloud.CloudflareControl +import Alchemy.Cloud.Api +import Alchemy.Cloud.Provider +import Alchemy.Cloud.Engine +import Alchemy.Cloud.Cli +import Alchemy.Cloud.AWSControl +import Alchemy.Cloud.SQSQueue +import Alchemy.Ranking diff --git a/packages/alchemy-lean/Alchemy/Aggregate.lean b/packages/alchemy-lean/Alchemy/Aggregate.lean new file mode 100644 index 00000000000..51d800233b9 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Aggregate.lean @@ -0,0 +1,132 @@ +/-! +An aggregate: a thing whose rules hold in one transaction. `decide` answers a +command with the events it records or a rejection, and `evolve` applies one +event to the state. +-/ +namespace Alchemy + +/-- A moment, in whatever unit the model counts in. -/ +abbrev Time := Nat + +/-- What a decision is made with: who asks, and when. -/ +structure Context (Actor : Type) where + actor : Actor + now : Time + +structure Aggregate where + name : String + Id : Type + State : Type + Command : Type + Event : Type + Rejection : Type + /-- Who a command is sent by. -/ + Actor : Type + /-- The state of an instance nothing was recorded on. -/ + initial : State + /-- The instance a command is sent to. -/ + keyOf : Command → Id + decide : Context Actor → State → Command → Except Rejection (List Event) + /-- Applies one event, recorded at the given time. -/ + evolve : State → Event → Time → State + /-- What an accepted command answers its caller. -/ + Reply : Type := Unit + /-- The reply, from the state the command left. -/ + reply : State → Command → Reply := by exact fun _ _ => () + [decEqId : DecidableEq Id] + [decEqState : DecidableEq State] + [decEqEvent : DecidableEq Event] + [decEqRejection : DecidableEq Rejection] + [decEqReply : DecidableEq Reply] + +namespace Aggregate + +attribute [instance] Aggregate.decEqId Aggregate.decEqState Aggregate.decEqEvent + Aggregate.decEqRejection Aggregate.decEqReply + +variable (a : Aggregate) + +/-- The state after every event, in order, all recorded at one time. -/ +def apply (s : a.State) (es : List a.Event) (time : Time) : a.State := + es.foldl (fun s e => a.evolve s e time) s + +/-- The state of an instance these events were recorded on, in order: the "given" of a scenario. -/ +def after (es : List a.Event) : a.State := a.apply a.initial es 0 + +/-- The state after one command: unchanged when the command is rejected. -/ +def step (ctx : Context a.Actor) (s : a.State) (c : a.Command) : a.State := + match a.decide ctx s c with + | .ok es => a.apply s es ctx.now + | .error _ => s + +/-- A command with who sends it and when. -/ +abbrev Sent := Context a.Actor × a.Command + +/-- The state after every command, in order. -/ +def replay (s : a.State) (cs : List a.Sent) : a.State := + cs.foldl (fun s c => a.step c.1 s c.2) s + +/-- A rule no accepted command breaks. -/ +def Keeps (P : a.State → Prop) : Prop := + ∀ ctx s c es, P s → a.decide ctx s c = .ok es → P (a.apply s es ctx.now) + +/-- A rule no recorded event breaks, whoever records it: a command or a decision. -/ +def Evolves (P : a.State → Prop) : Prop := + ∀ s e time, P s → P (a.evolve s e time) + +/-- A rule about what a command may do to the state. -/ +def Transition (R : Context a.Actor → a.State → a.Command → a.State → Prop) : Prop := + ∀ ctx s c es, a.decide ctx s c = .ok es → R ctx s c (a.apply s es ctx.now) + +theorem Evolves.apply {a : Aggregate} {P : a.State → Prop} (kept : a.Evolves P) + (es : List a.Event) (time : Time) : ∀ s, P s → P (a.apply s es time) := by + induction es with + | nil => intro s h; exact h + | cons e es ih => intro s h; exact ih _ (kept s e time h) + +theorem Evolves.keeps {a : Aggregate} {P : a.State → Prop} (kept : a.Evolves P) : a.Keeps P := + fun ctx s _ es h _ => kept.apply es ctx.now s h + +theorem Keeps.step {a : Aggregate} {P : a.State → Prop} (kept : a.Keeps P) + (ctx : Context a.Actor) (s : a.State) (c : a.Command) (h : P s) : P (a.step ctx s c) := by + unfold Aggregate.step + split + · next es eq => exact kept ctx s c es h eq + · exact h + +theorem Keeps.replay {a : Aggregate} {P : a.State → Prop} (kept : a.Keeps P) + (cs : List a.Sent) : ∀ s, P s → P (a.replay s cs) := by + induction cs with + | nil => intro s h; exact h + | cons c cs ih => intro s h; exact ih _ (kept.step c.1 s c.2 h) + +/-- +A command is idempotent: sent twice in a row, it leaves what it leaves sent +once. A caller who is not sure the first one arrived can send it again. +-/ +def IdempotentAt (c : a.Command) : Prop := + ∀ ctx s, a.step ctx (a.step ctx s c) c = a.step ctx s c + +/-- Every command is idempotent. -/ +def Idempotent : Prop := ∀ c, a.IdempotentAt c + +/-- Two commands commute: either order leaves the same state. -/ +def Commute (c d : a.Command) : Prop := + ∀ ctx s, a.step ctx (a.step ctx s c) d = a.step ctx (a.step ctx s d) c + +/-- A rule every state of an aggregate satisfies, with its proof. -/ +structure Invariant (a : Aggregate) where + name : String + holds : a.State → Prop + /-- It holds before anything is recorded. -/ + initially : holds a.initial + /-- No accepted command breaks it. -/ + kept : a.Keeps holds + +/-- An invariant holds after any sequence of commands. -/ +theorem Invariant.always {a : Aggregate} (rule : Invariant a) (cs : List a.Sent) : + rule.holds (a.replay a.initial cs) := + rule.kept.replay cs a.initial rule.initially + +end Aggregate +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Api.lean b/packages/alchemy-lean/Alchemy/Api.lean new file mode 100644 index 00000000000..7f5eb199a6f --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Api.lean @@ -0,0 +1,23 @@ +import Alchemy.Engine + +/-! +An Api: what one audience may send and read. Who is asking is the actor each +command and read is given, so a session is an argument, not a setting. +-/ +namespace Alchemy + +structure Api (m : Model) where + name : String + /-- The commands this audience may send. -/ + accepts : Send m.signature.aggregates → Bool + decisions : List (Decision m.signature.aggregates) := [] + views : List (View m.signature.aggregates) := [] + streams : List (Stream m.signature.aggregates) := [] + queries : List (Query m.signature.aggregates) := [] + +/-- Sends a command through an Api: `none` when the Api does not offer it. -/ +def Api.send {m : Model} (api : Api m) (w : World m.signature) (s : Send m.signature.aggregates) + (fuel : Nat := 1000) : Option (World m.signature) := + if api.accepts s then some (m.play fuel w (.send s)) else none + +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Attr.lean b/packages/alchemy-lean/Alchemy/Attr.lean new file mode 100644 index 00000000000..acf309a828a --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Attr.lean @@ -0,0 +1,12 @@ +import Lean + +/-! +The definitions a behaviour proof steps through: the engine's, and each +model's own. +-/ + +/-- Unfolded when a behaviour theorem is proved by running the model with its variables left as they are. -/ +register_simp_attr behaviour + +/-- Facts a rule about a stack is checked with: what the stack built, and how grants cover one another. -/ +register_simp_attr stack_facts diff --git a/packages/alchemy-lean/Alchemy/Behaviour.lean b/packages/alchemy-lean/Alchemy/Behaviour.lean new file mode 100644 index 00000000000..6c0ee61995f --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Behaviour.lean @@ -0,0 +1,113 @@ +import Alchemy.Attr +import Alchemy.Engine +import Alchemy.Compose + +/-! +# Behaviour, proved by running + +A behaviour theorem says: after these moves, this is true. It is proved by +running the model with its ids and amounts left as variables, one step at a +time. The lemmas here are the steps. +-/ + +namespace Alchemy + +namespace Model + +variable (m : Model) + +/-- One more step of settling: take a step if there is one. -/ +theorem settle_succ (fuel : Nat) (w : World m.signature) : + m.settle (fuel + 1) w = (m.stepOnce w).elim w (m.settle fuel) := by + show (match m.stepOnce w with + | none => w + | some w' => m.settle fuel w') = _ + cases m.stepOnce w <;> rfl + +theorem settle_zero (w : World m.signature) : m.settle 0 w = w := rfl + +theorem fireDue_zero (fuel : Nat) (w : World m.signature) : m.fireDue fuel 0 w = w := rfl + +theorem fireDue_succ (fuel count : Nat) (w : World m.signature) : + m.fireDue fuel (count + 1) w = + match m.nextDue w.now w.schedule with + | none => w + | some (before, x, after) => + m.fireDue fuel count (m.settle fuel ({ w with schedule := before ++ after }.dispatch x.2)) := + rfl + +end Model + +theorem Program.pure_eq {σ : Signature} {α : Type} (a : α) : + (Pure.pure a : Program σ α) = Program.pure a := rfl + +theorem Program.bind_eq {σ : Signature} {α β : Type} (x : Program σ α) (f : α → Program σ β) : + (Bind.bind x f : Program σ β) = Program.bind x f := rfl + +namespace Link + +variable {a b : Model} (link : Link a b) + +theorem settle_succ (calls : Nat) (w : link.Worlds) : + link.settle (calls + 1) w = (link.answerNext w).elim w (link.settle calls) := by + show (match link.answerNext w with + | none => w + | some w' => link.settle calls w') = _ + cases link.answerNext w <;> rfl + +theorem settle_zero (w : link.Worlds) : link.settle 0 w = w := rfl + +end Link + +attribute [behaviour] + Model.run Model.play Model.settle_succ Model.settle_zero Model.stepOnce Model.tryFibers + Model.advance Model.react Model.waiting Model.answer Model.answerGo Model.pass + Model.fireDue_zero Model.fireDue_succ Model.nextDue + World.dispatch World.decide World.lift World.start World.finish + Recorded.dispatch Recorded.decide Recorded.records Recorded.outcome Recorded.record Recorded.start + States.set update Aggregate.apply Aggregate.after + Policy.on Program.request Program.tell Program.step Program.ask Program.undoWith + Program.startSaga Program.signalSaga Program.awaitSignal Program.later Program.bind + Program.pure_eq Program.bind_eq Option.elim + Link.run Link.play Link.settle_succ Link.settle_zero Link.answerNext Link.fuel + Model.AtRest World.Settled + +/-- +Proves a behaviour theorem by running the model, with its variables left as +they are. Each `if` on the way is decided by arithmetic from the hypotheses, so +`amount ≥ 50000` settles a test for `amount ≥ 10000`. More definitions to unfold +go in the list. +-/ +syntax "behaviour" (" [" Lean.Parser.Tactic.simpLemma,* "]")? : tactic + +theorem Behaviour.then_branch {α : Sort _} {c : Prop} [Decidable c] {a b : α} (h : c) : + (if c then a else b) = a := by simp [h] + +theorem Behaviour.else_branch {α : Sort _} {c : Prop} [Decidable c] {a b : α} (h : ¬c) : + (if c then a else b) = b := by simp [h] + +macro_rules + | `(tactic| behaviour) => + `(tactic| ( + try dsimp only + try simp (config := { failIfUnchanged := false }) + [behaviour, Alchemy.Program.pure_eq, Alchemy.Program.bind_eq, *] + repeat' (first + | done + | (simp (disch := omega) + [behaviour, Alchemy.Program.pure_eq, Alchemy.Program.bind_eq, + Alchemy.Behaviour.then_branch, Alchemy.Behaviour.else_branch, *] + try simp [behaviour, Alchemy.Program.pure_eq, Alchemy.Program.bind_eq, *])))) + | `(tactic| behaviour [$lemmas,*]) => + `(tactic| ( + try dsimp only + try simp (config := { failIfUnchanged := false }) + [behaviour, Alchemy.Program.pure_eq, Alchemy.Program.bind_eq, $lemmas,*, *] + repeat' (first + | done + | (simp (disch := omega) + [behaviour, Alchemy.Program.pure_eq, Alchemy.Program.bind_eq, + Alchemy.Behaviour.then_branch, Alchemy.Behaviour.else_branch, $lemmas,*, *] + try simp [behaviour, Alchemy.Program.pure_eq, Alchemy.Program.bind_eq, $lemmas,*, *])))) + +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Caused.lean b/packages/alchemy-lean/Alchemy/Caused.lean new file mode 100644 index 00000000000..09a62173574 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Caused.lean @@ -0,0 +1,487 @@ +import Alchemy.Model +import Alchemy.Attr + +/-! +# Commands only a reaction sends + +Some commands are not for callers: a shipment is scheduled because an order was +paid, not because somebody asked. `Model.caused` proves a rule that depends on +that. A command is justified by what is recorded; every reaction sends only +justified commands; callers are offered only commands that keep the rule +anyway. Then the rule holds in every world the model can reach. +-/ +namespace Alchemy + +variable {σ : Signature} {α : Type} + +/-- Every command a program may send, schedule or register to undo, whatever it is answered. -/ +inductive Program.Only (ok : Send σ.aggregates → Prop) : Program σ α → Prop where + | pure (a) : Only ok (.pure a) + | fail (failure) : Only ok (.fail failure) + | send (s k) : ok s → (∀ r, Only ok (k r)) → Only ok (.send s k) + | call (c k) : (∀ r, Only ok (k r)) → Only ok (.call c k) + | await (k) : (∀ r, Only ok (k r)) → Only ok (.await k) + | compensate (u k) : (∀ failure, ok (u failure)) → Only ok k → Only ok (.compensate u k) + | start (saga input k) : Only ok k → Only ok (.start saga input k) + | signal (saga signal k) : Only ok k → Only ok (.signal saga signal k) + | schedule (after s k) : ok s → Only ok k → Only ok (.schedule after s k) + +theorem Program.Only.mono {ok ok' : Send σ.aggregates → Prop} (wider : ∀ s, ok s → ok' s) + {p : Program σ α} (only : p.Only ok) : p.Only ok' := by + induction only with + | pure a => exact .pure a + | fail failure => exact .fail failure + | send s k h _ ih => exact .send s k (wider s h) ih + | call c k _ ih => exact .call c k ih + | await k _ ih => exact .await k ih + | compensate u k h _ ih => exact .compensate u k (fun failure => wider _ (h failure)) ih + | start saga input k _ ih => exact .start saga input k ih + | signal saga signal k _ ih => exact .signal saga signal k ih + | schedule after s k h _ ih => exact .schedule after s k (wider s h) ih + +namespace Program.Only + +variable {ok : Send σ.aggregates → Prop} {β : Type} + +/-- One step after another sends only what each may. -/ +theorem bind {p : Program σ α} {f : α → Program σ β} (first : p.Only ok) + (rest : ∀ a, (f a).Only ok) : (p.bind f).Only ok := by + induction first with + | pure a => exact rest a + | fail failure => exact .fail failure + | send s k h _ ih => exact .send s _ h ih + | call c k _ ih => exact .call c _ ih + | await k _ ih => exact .await _ ih + | compensate u k h _ ih => exact .compensate u _ h ih + | start saga input k _ ih => exact .start saga input _ ih + | signal saga signal k _ ih => exact .signal saga signal _ ih + | schedule after s k h _ ih => exact .schedule after s _ h ih + +theorem bind' {p : Program σ α} {f : α → Program σ β} (first : p.Only ok) + (rest : ∀ a, (f a).Only ok) : (p >>= f).Only ok := bind first rest + +theorem pure' (a : α) : (Pure.pure a : Program σ α).Only ok := .pure a + +theorem tell {s : Send σ.aggregates} (h : ok s) : (Program.tell s).Only ok := + .send s _ h fun _ => .pure () + +theorem ask {s : Send σ.aggregates} (h : ok s) : (Program.ask s).Only ok := + .send s _ h fun r => .pure r + +theorem step {s : Send σ.aggregates} {explain} (h : ok s) : (Program.step s explain).Only ok := + .send s _ h fun r => by cases r <;> first | exact .pure () | exact .fail _ + +theorem request (c : σ.Call) : (Program.request c).Only ok := .call c _ fun r => .pure r + +theorem awaitSignal : (Program.awaitSignal : Program σ σ.Signal).Only ok := .await _ fun r => .pure r + +theorem undoWith {undo : σ.Failure → Send σ.aggregates} (h : ∀ failure, ok (undo failure)) : + (Program.undoWith undo).Only ok := .compensate undo _ h (.pure ()) + +theorem startSaga (saga : σ.Saga) (input : σ.SagaInput) : (Program.startSaga saga input).Only ok := + .start saga input _ (.pure ()) + +theorem signalSaga (saga : σ.Saga) (signal : σ.Signal) : (Program.signalSaga saga signal).Only ok := + .signal saga signal _ (.pure ()) + +theorem later {after : Time} {s : Send σ.aggregates} (h : ok s) : (Program.later after s).Only ok := + .schedule after s _ h (.pure ()) + +end Program.Only + +namespace Model + +variable (m : Model) + +/-- What `caused` asks: a rule, what justifies a command, and that reactions send only justified ones. -/ +structure Caused (rule : Recorded m.signature.aggregates → Prop) + (justified : Recorded m.signature.aggregates → Send m.signature.aggregates → Prop) : Prop where + initially : rule (.start m.signature.aggregates) + /-- What justifies a command still does once more is recorded. -/ + lasting : ∀ r now s s', justified r s' → justified (r.dispatch now s) s' + /-- A command callers are offered keeps the rule. -/ + offered : ∀ r now s, m.offered s → rule r → rule (r.dispatch now s) + /-- A justified command keeps the rule. -/ + kept : ∀ r now s, justified r s → rule r → rule (r.dispatch now s) + /-- A policy reacting to a recorded event sends only justified commands. -/ + policies : ∀ p ∈ m.policies, ∀ r history e, e ∈ r.log → (p.react history e).Only (justified r) + /-- So does every saga. -/ + sagas : ∀ r saga input, (m.saga saga input).Only (justified r) + +/-- Everything that could still send a command is justified in sending it. -/ +structure Caused.Holds {m : Model} (justified : Recorded m.signature.aggregates → + Send m.signature.aggregates → Prop) (w : World m.signature) : Prop where + inbox : ∀ e ∈ w.inbox, e ∈ w.log + programs : ∀ f ∈ w.fibers, f.program.Only (justified w.toRecorded) + undos : ∀ f ∈ w.fibers, ∀ u ∈ f.undo, ∀ failure, justified w.toRecorded (u failure) + schedule : ∀ x ∈ w.schedule, justified w.toRecorded x.2 + +end Model + +namespace Recorded + +variable {g : Aggregates} + +/-- A command only adds to the log. -/ +theorem log_dispatch (r : Recorded g) (now : Time) (s : Send g) : + ∃ more, (r.dispatch now s).log = r.log ++ more := by + rcases r.dispatch_cases now s with same | ⟨es, _, recorded⟩ + · exact ⟨[], by rw [same, List.append_nil]⟩ + · rw [recorded]; exact r.log_subset_record _ _ _ _ + +end Recorded + +namespace Model + +variable {m : Model} {rule : Recorded m.signature.aggregates → Prop} + {justified : Recorded m.signature.aggregates → Send m.signature.aggregates → Prop} + +/-- Sending a command keeps everything justified: its new events wait, and what was justified still is. -/ +theorem Caused.Holds.dispatch (caused : m.Caused rule justified) {w : World m.signature} + (holds : Caused.Holds justified w) (s : Send m.signature.aggregates) : + Caused.Holds justified (w.dispatch s) := by + obtain ⟨more, grew⟩ := w.toRecorded.log_dispatch w.now s + have log : (w.dispatch s).log = w.log ++ more := grew + have inbox : (w.dispatch s).inbox = w.inbox ++ more := by + show w.inbox ++ (w.toRecorded.dispatch w.now s).log.drop w.log.length = _ + rw [grew, List.drop_left] + refine ⟨?_, ?_, ?_, ?_⟩ + · intro e mem + rw [inbox] at mem + rw [log] + rcases List.mem_append.mp mem with old | new + · exact List.mem_append_left _ (holds.inbox e old) + · exact List.mem_append_right _ new + · intro f mem + exact (holds.programs f mem).mono fun s' => caused.lasting _ _ s s' + · intro f mem u inUndo failure + exact caused.lasting _ _ s _ (holds.undos f mem u inUndo failure) + · intro x mem + exact caused.lasting _ _ s _ (holds.schedule x mem) + +/-- A change that records nothing, and leaves only justified programs, keeps everything justified. -/ +theorem Caused.Holds.change {w w' : World m.signature} (holds : Caused.Holds justified w) + (recorded : w'.toRecorded = w.toRecorded) (inbox : ∀ e ∈ w'.inbox, e ∈ w.inbox) + (programs : ∀ f ∈ w'.fibers, f.program.Only (justified w.toRecorded)) + (undos : ∀ f ∈ w'.fibers, ∀ u ∈ f.undo, ∀ failure, justified w.toRecorded (u failure)) + (schedule : ∀ x ∈ w'.schedule, justified w.toRecorded x.2) : Caused.Holds justified w' := + ⟨fun e mem => by rw [show w'.log = w.log from congrArg Recorded.log recorded]; exact holds.inbox e (inbox e mem), + by rw [recorded]; exact programs, by rw [recorded]; exact undos, by rw [recorded]; exact schedule⟩ + +/-- A fiber's own next step: the rule is kept, and whatever replaces the fiber is justified. -/ +theorem Caused.advance (caused : m.Caused rule justified) {w w' : World m.signature} + {f : Fiber m.signature} {fs : List (Fiber m.signature)} (adv : m.advance w f = some (w', fs)) + (ruled : rule w.toRecorded) (holds : Caused.Holds justified w) (mem : f ∈ w.fibers) : + rule w'.toRecorded ∧ Caused.Holds justified w' ∧ w'.fibers = w.fibers ∧ + ∀ x ∈ fs, x.program.Only (justified w'.toRecorded) ∧ + ∀ u ∈ x.undo, ∀ failure, justified w'.toRecorded (u failure) := by + have only := holds.programs f mem + have undos := holds.undos f mem + have finished : ∀ status, rule (w.finish f.owner status).toRecorded ∧ + Caused.Holds justified (w.finish f.owner status) ∧ (w.finish f.owner status).fibers = w.fibers := by + intro status + unfold World.finish + cases f.owner with + | none => exact ⟨ruled, holds, rfl⟩ + | some saga => exact ⟨ruled, holds.change rfl (fun _ h => h) holds.programs holds.undos holds.schedule, rfl⟩ + unfold Model.advance at adv + split at adv + · cases adv + obtain ⟨a, b, c⟩ := finished .completed + exact ⟨a, b, c, by intro x h; cases h⟩ + · next failure program => + split at adv + · cases adv + obtain ⟨a, b, c⟩ := finished (.failed failure) + exact ⟨a, b, c, by intro x h; cases h⟩ + · next u rest undo => + cases adv + have just := undos u (by rw [undo]; exact List.mem_cons_self) failure + refine ⟨caused.kept _ _ _ just ruled, holds.dispatch caused _, rfl, ?_⟩ + intro x h + cases List.mem_singleton.mp h + exact ⟨only.mono fun s' => caused.lasting _ _ _ s', fun u' inRest failure' => + caused.lasting _ _ _ _ (undos u' (by rw [undo]; exact List.mem_cons_of_mem _ inRest) failure')⟩ + · next s k program => + cases adv + rw [program] at only + cases only with + | send _ _ just rest => + refine ⟨caused.kept _ _ _ just ruled, holds.dispatch caused _, rfl, ?_⟩ + intro x h + cases List.mem_singleton.mp h + exact ⟨(rest _).mono fun s' => caused.lasting _ _ _ s', fun u inUndo failure => + caused.lasting _ _ _ _ (undos u inUndo failure)⟩ + · cases adv + · next k program => + rw [program] at only + cases only with + | await _ rest => + split at adv + · cases adv + · split at adv + · cases adv + · cases adv + refine ⟨ruled, holds.change rfl (fun _ h => h) holds.programs holds.undos holds.schedule, + rfl, ?_⟩ + intro x h + cases List.mem_singleton.mp h + exact ⟨rest _, undos⟩ + · next u k program => + cases adv + rw [program] at only + cases only with + | compensate _ _ just rest => + refine ⟨ruled, holds, rfl, ?_⟩ + intro x h + cases List.mem_singleton.mp h + refine ⟨rest, fun u' inUndo failure => ?_⟩ + rcases List.mem_cons.mp inUndo with rfl | old + · exact just failure + · exact undos u' old failure + · next saga input k program => + rw [program] at only + cases only with + | start _ _ _ rest => + split at adv + · cases adv + refine ⟨ruled, holds.change rfl (fun _ h => h) holds.programs holds.undos holds.schedule, + rfl, ?_⟩ + intro x h + rcases List.mem_cons.mp h with rfl | h + · exact ⟨rest, undos⟩ + · cases List.mem_singleton.mp h + exact ⟨caused.sagas _ saga input, by intro u h; cases h⟩ + · cases adv + refine ⟨ruled, holds, rfl, ?_⟩ + intro x h + cases List.mem_singleton.mp h + exact ⟨rest, undos⟩ + · next saga signal k program => + cases adv + rw [program] at only + cases only with + | signal _ _ _ rest => + refine ⟨ruled, holds.change rfl (fun _ h => h) holds.programs holds.undos holds.schedule, + rfl, ?_⟩ + intro x h + cases List.mem_singleton.mp h + exact ⟨rest, undos⟩ + · next after s k program => + cases adv + rw [program] at only + cases only with + | schedule _ _ _ just rest => + refine ⟨ruled, holds.change rfl (fun _ h => h) holds.programs holds.undos ?_, rfl, ?_⟩ + · intro x h + rcases List.mem_append.mp h with old | new + · exact holds.schedule x old + · cases List.mem_singleton.mp new + exact just + · intro x h + cases List.mem_singleton.mp h + exact ⟨rest, undos⟩ + +/-- +A rule that callers' commands keep, and that justified commands keep, holds in +every world the model can reach, when reactions send only justified commands. +-/ +theorem caused (m : Model) {rule : Recorded m.signature.aggregates → Prop} + {justified : Recorded m.signature.aggregates → Send m.signature.aggregates → Prop} + (noDecisions : m.decisions = []) (caused : m.Caused rule justified) : + ∀ w, m.Reachable w → rule w.toRecorded := by + suffices ∀ w, m.Reachable w → rule w.toRecorded ∧ Caused.Holds justified w from + fun w reach => (this w reach).1 + intro w reach + induction reach with + | start => + refine ⟨caused.initially, ⟨?_, ?_, ?_, ?_⟩⟩ <;> intro x h <;> cases h + | @step w _ _ step ih => + obtain ⟨ruled, holds⟩ := ih + have reacted : ∀ (v : World m.signature) (e : Emitted m.signature.aggregates), + Caused.Holds justified v → e ∈ v.log → Caused.Holds justified (m.react v e) := by + intro v e held inLog + refine held.change rfl (fun _ h => h) ?_ ?_ held.schedule + · intro f h + rcases List.mem_append.mp h with old | new + · exact held.programs f old + · obtain ⟨p, inPolicies, rfl⟩ := List.mem_map.mp new + exact caused.policies p inPolicies _ _ e inLog + · intro f h + rcases List.mem_append.mp h with old | new + · exact held.undos f old + · obtain ⟨p, _, rfl⟩ := List.mem_map.mp new + intro u h; cases h + cases step with + | send s offered => exact ⟨caused.offered _ _ s offered ruled, holds.dispatch caused s⟩ + | decide d actor c mem => rw [noDecisions] at mem; cases mem + | deliver e before after split => + have inLog : e ∈ w.log := holds.inbox e (by rw [split]; simp) + refine ⟨ruled, reacted { w with inbox := before ++ after } e ?_ inLog⟩ + refine holds.change rfl ?_ holds.programs holds.undos holds.schedule + intro x h + rw [split] + rcases List.mem_append.mp h with l | r + · exact List.mem_append_left _ l + · exact List.mem_append_right _ (List.mem_cons_of_mem _ r) + | redeliver e mem => exact ⟨ruled, reacted w e holds mem⟩ + | advance f before after w' fs split adv => + have mem : f ∈ w.fibers := by rw [split]; simp + obtain ⟨ruled', holds', fibers, replaced⟩ := caused.advance adv ruled holds mem + have old : ∀ x, x ∈ before ∨ x ∈ after → x ∈ w'.fibers := by + intro x h + rw [fibers, split] + rcases h with l | r + · exact List.mem_append_left _ l + · exact List.mem_append_right _ (List.mem_cons_of_mem _ r) + refine ⟨ruled', holds'.change rfl (fun _ h => h) ?_ ?_ holds'.schedule⟩ + · intro x h + rcases List.mem_append.mp h with h | r + · rcases List.mem_append.mp h with l | new + · exact holds'.programs x (old x (.inl l)) + · exact (replaced x new).1 + · exact holds'.programs x (old x (.inr r)) + · intro x h + rcases List.mem_append.mp h with h | r + · rcases List.mem_append.mp h with l | new + · exact holds'.undos x (old x (.inl l)) + · exact (replaced x new).2 + · exact holds'.undos x (old x (.inr r)) + | answer f before after c k reply split program => + have mem : f ∈ w.fibers := by rw [split]; simp + have only := holds.programs f mem + rw [program] at only + cases only with + | call _ _ rest => + have old : ∀ x, x ∈ before ∨ x ∈ after → x ∈ w.fibers := by + intro x h + rw [split] + rcases h with l | r + · exact List.mem_append_left _ l + · exact List.mem_append_right _ (List.mem_cons_of_mem _ r) + refine ⟨ruled, holds.change rfl (fun _ h => h) ?_ ?_ holds.schedule⟩ + · intro x h + rcases List.mem_append.mp h with l | r + · exact holds.programs x (old x (.inl l)) + · rcases List.mem_cons.mp r with rfl | r + · exact rest reply + · exact holds.programs x (old x (.inr r)) + · intro x h + rcases List.mem_append.mp h with l | r + · exact holds.undos x (old x (.inl l)) + · rcases List.mem_cons.mp r with rfl | r + · exact holds.undos f mem + · exact holds.undos x (old x (.inr r)) + | tick time later => + exact ⟨ruled, holds.change rfl (fun _ h => h) holds.programs holds.undos holds.schedule⟩ + | fire due s before after split isDue => + have just : justified w.toRecorded s := holds.schedule (due, s) (by rw [split]; simp) + have rest : Caused.Holds justified { w with schedule := before ++ after } := by + refine holds.change rfl (fun _ h => h) holds.programs holds.undos ?_ + intro x h + refine holds.schedule x ?_ + rw [split] + rcases List.mem_append.mp h with l | r + · exact List.mem_append_left _ l + · exact List.mem_append_right _ (List.mem_cons_of_mem _ r) + exact ⟨caused.kept _ _ s just ruled, rest.dispatch caused s⟩ + +/-! ## An event that needs another, across aggregates -/ + +/-- Every `effect` in these events has its `cause` among them. -/ +def Backed {g : Aggregates} (effect : Emitted g → Prop) (cause : Emitted g → Emitted g → Prop) + (log : List (Emitted g)) : Prop := + ∀ e ∈ log, effect e → ∃ c ∈ log, cause e c + +/-- A command may be sent: anything it could record that is an `effect` has its `cause` recorded. -/ +def Due {g : Aggregates} (effect : Emitted g → Prop) (cause : Emitted g → Emitted g → Prop) + (log : List (Emitted g)) (s : Send g) : Prop := + ∀ x seq time, effect ⟨s.to, (g.of s.to).keyOf s.command, x, seq, time⟩ → + ∃ c ∈ log, cause ⟨s.to, (g.of s.to).keyOf s.command, x, seq, time⟩ c + +/-- +"Nothing ships unless it was paid." Callers are offered no command that records +an `effect`, and every policy and saga sends a command that could record one +only when its `cause` is recorded. Then in every world the model can reach, +every `effect` recorded has its `cause` recorded. +-/ +theorem backed (m : Model) (noDecisions : m.decisions = []) + {effect : Emitted m.signature.aggregates → Prop} + {cause : Emitted m.signature.aggregates → Emitted m.signature.aggregates → Prop} + (offered : ∀ s, m.offered s → ∀ x seq time, + ¬effect ⟨s.to, (m.signature.aggregates.of s.to).keyOf s.command, x, seq, time⟩) + (policies : ∀ p ∈ m.policies, ∀ log history e, e ∈ log → + (p.react history e).Only (Due effect cause log)) + (sagas : ∀ log saga input, (m.saga saga input).Only (Due effect cause log)) + (w : World m.signature) (reach : m.Reachable w) : Backed effect cause w.log := by + have step : ∀ (r : Recorded m.signature.aggregates) now s, Due effect cause r.log s → + Backed effect cause r.log → Backed effect cause (r.dispatch now s).log := by + intro r now s due backed + rcases r.dispatch_cases now s with same | ⟨es, _, recorded⟩ + · rw [same]; exact backed + · rw [recorded] + obtain ⟨more, grew⟩ := r.log_subset_record now s.to + ((m.signature.aggregates.of s.to).keyOf s.command) es + intro e mem isEffect + rcases Recorded.mem_record_log mem with old | ⟨x, _, seq, rfl⟩ + · obtain ⟨c, inLog, is⟩ := backed e old isEffect + exact ⟨c, by rw [grew]; exact List.mem_append_left _ inLog, is⟩ + · obtain ⟨c, inLog, is⟩ := due x seq now isEffect + exact ⟨c, by rw [grew]; exact List.mem_append_left _ inLog, is⟩ + refine m.caused (rule := fun r => Backed effect cause r.log) + (justified := fun r s => Due effect cause r.log s) noDecisions + { initially := by intro e h; cases h + lasting := ?_ + offered := fun r now s isOffered backed => + step r now s (fun x seq time isEffect => absurd isEffect (offered s isOffered x seq time)) backed + kept := fun r now s due backed => step r now s due backed + policies := fun p mem r history e inLog => policies p mem r.log history e inLog + sagas := fun r saga input => sagas r.log saga input } w reach + intro r now s s' due x seq time isEffect + obtain ⟨more, grew⟩ := r.log_dispatch now s + obtain ⟨c, inLog, is⟩ := due x seq time isEffect + exact ⟨c, by rw [grew]; exact List.mem_append_left _ inLog, is⟩ + +end Model + +/-- Walks a program, branch by branch, leaving one goal for each command it sends. -/ +macro "only_sends" : tactic => `(tactic| ( + try simp only [Alchemy.Policy.on, ↓reduceDIte, behaviour] + repeat' (first + | exact Alchemy.Program.Only.pure _ + | exact Alchemy.Program.Only.fail _ + | refine Alchemy.Program.Only.call _ _ ?_ + | refine Alchemy.Program.Only.send _ _ ?_ ?_ + | refine Alchemy.Program.Only.await _ ?_ + | refine Alchemy.Program.Only.compensate _ _ ?_ ?_ + | refine Alchemy.Program.Only.start _ _ _ ?_ + | refine Alchemy.Program.Only.signal _ _ _ ?_ + | refine Alchemy.Program.Only.schedule _ _ _ ?_ ?_ + | intro _ + | split))) + +/-- +`caused_by reach` proves that every `effect` recorded has its `cause` recorded, +in a world the model reaches: `Model.Backed effect cause w.log`. It checks that +callers are offered no command that records an effect, then walks each policy's +reaction to each event, and each saga. A command that could record an effect is +allowed where the event being reacted to is its cause. +-/ +macro "caused_by " reach:term : tactic => `(tactic| ( + refine Alchemy.Model.backed _ rfl ?_ ?_ ?_ _ $reach + · rintro ⟨to, actor, command⟩ isOffered x seq time + cases to <;> first | exact id | exact isOffered.elim + · intro p mem log history e inLog + simp only [List.mem_cons, List.not_mem_nil, or_false] at mem + obtain ⟨n, id, event, seq, time⟩ := e + repeat' (first | (rcases mem with h | mem; subst h) | subst mem) + all_goals (cases n <;> cases event <;> only_sends) + all_goals first + | exact ⟨_, inLog, rfl⟩ + | (rename_i h; exact False.elim h) + · intro log saga input + only_sends + all_goals first + | (rename_i h; exact False.elim h))) + +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Check.lean b/packages/alchemy-lean/Alchemy/Check.lean new file mode 100644 index 00000000000..d092665181a --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Check.lean @@ -0,0 +1,37 @@ +import Alchemy.Engine + +/-! +A search for the sequence of moves that breaks a rule. Where a proof says a +rule holds for ever, this says it holds in every sequence tried, and when it +does not, it gives the sequence. +-/ +namespace Alchemy +namespace Model + +variable (m : Model) + +/-- The first sequence of at most `depth` moves after which `rule` fails, by where each move is in `moves`. -/ +def breaks (moves : List (Move m)) (rule : World m.signature → Bool) (fuel : Nat := 1000) : + Nat → World m.signature → Option (List Nat) + | 0, w => if rule w then none else some [] + | depth + 1, w => + if rule w then + (moves.zipIdx).findSome? fun (move, i) => + (breaks moves rule fuel depth (m.play fuel w move)).map (i :: ·) + else some [] + +/-- The shortest sequence of at most `depth` moves that breaks `rule`, if there is one. -/ +def counterexample (moves : List (Move m)) (depth : Nat) (rule : World m.signature → Bool) : + Option (List Nat) := + (List.range (depth + 1)).findSome? fun d => m.breaks moves rule 1000 d (World.start m.signature) + +/-- A rule holds after every sequence of at most `depth` of the moves, once the model has settled. -/ +def checked (moves : List (Move m)) (depth : Nat) (rule : World m.signature → Bool) : Bool := + (m.breaks moves rule 1000 depth (World.start m.signature)).isNone + +/-- Some sequence of at most `depth` of the moves gets to a world where `goal` holds. -/ +def sometimes (moves : List (Move m)) (depth : Nat) (goal : World m.signature → Bool) : Bool := + (m.breaks moves (fun w => !goal w) 1000 depth (World.start m.signature)).isSome + +end Model +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Cloud/AWS.lean b/packages/alchemy-lean/Alchemy/Cloud/AWS.lean new file mode 100644 index 00000000000..c3ba5d4b35f --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/AWS.lean @@ -0,0 +1,417 @@ +import Alchemy.Attr +import Alchemy.Cloud.Host + +/-! +# A small AWS + +Buckets, queues and functions: their access, their calls, and what each call +does in memory. Enough to show the graph; not a provider. +-/ + +namespace Alchemy.AWS +open Alchemy.Cloud + +abbrev Path := List String + +inductive Kind where + | bucket + | queue + | function +deriving DecidableEq, Repr + +/-! ## Access -/ + +inductive BucketOp where + /-- Read objects whose key is under a prefix. -/ + | get (under : Path) + /-- Write objects whose key is under a prefix. -/ + | put (under : Path) + | list +deriving DecidableEq, Repr + +inductive QueueOp where + | send + | receive +deriving DecidableEq, Repr + +inductive FunctionOp where + | invoke +deriving DecidableEq, Repr + +abbrev Op : Kind → Type + | .bucket => BucketOp + | .queue => QueueOp + | .function => FunctionOp + +instance : (k : Kind) → DecidableEq (Op k) + | .bucket => inferInstanceAs (DecidableEq BucketOp) + | .queue => inferInstanceAs (DecidableEq QueueOp) + | .function => inferInstanceAs (DecidableEq FunctionOp) + +/-- A grant on a prefix covers every key under it. -/ +@[stack_facts] def BucketOp.covers : BucketOp → BucketOp → Bool + | .get under, .get key => under.isPrefixOf key + | .put under, .put key => under.isPrefixOf key + | _, _ => false + +instance : Kinds Kind where + Op := Op + covers {k} := match k with + | .bucket => BucketOp.covers + | _ => fun _ _ => false + +/-! ## Configuration, calls and events -/ + +structure BucketProps where + versioned : Bool := false +deriving DecidableEq, Repr + +structure QueueProps where + /-- First in, first out. Fixed when the queue is created. -/ + fifo : Bool := false + /-- Seconds a received message stays hidden. -/ + visibilityTimeout : Nat := 30 +deriving DecidableEq, Repr + +structure FunctionProps where + url : Bool := false + memory : Nat := 512 +deriving DecidableEq, Repr + +abbrev Props : Kind → Type + | .bucket => BucketProps + | .queue => QueueProps + | .function => FunctionProps + +/-- A bucket has no object of this key. -/ +structure S3.NoSuchKey where + bucket : String + key : Path +deriving DecidableEq, Repr + +inductive BucketCall where + | getObject (key : Path) + | putObject (key : Path) (body : String) + | listObjects + +inductive QueueCall where + | sendMessage (body : String) + | receiveMessage + +abbrev Call : Kind → Type + | .bucket => BucketCall + | .queue => QueueCall + | .function => Empty + +abbrev BucketCall.Reply : BucketCall → Type + | .getObject _ => Except S3.NoSuchKey String + | .putObject .. => Unit + | .listObjects => List Path + +abbrev QueueCall.Reply : QueueCall → Type + | .sendMessage _ => Unit + | .receiveMessage => Option String + +abbrev Reply : {k : Kind} → Call k → Type + | .bucket, c => BucketCall.Reply c + | .queue, c => QueueCall.Reply c + +def needs : {k : Kind} → Call k → Op k + | .bucket, .getObject key => .get key + | .bucket, .putObject key _ => .put key + | .bucket, .listObjects => .list + | .queue, .sendMessage _ => .send + | .queue, .receiveMessage => .receive + +inductive BucketEvent where + | objectCreated (key : Path) + +/-- A queue tells its consumers that a message arrived. -/ +inductive QueueEvent where + | messageSent + +abbrev Event : Kind → Type + | .bucket => BucketEvent + | .queue => QueueEvent + | _ => Empty + +inductive Method where + | get + | post +deriving DecidableEq, Repr + +structure Request where + method : Method := .get + path : Path := [] + body : String := "" +deriving DecidableEq, Repr + +structure Response where + status : Nat + body : String := "" +deriving DecidableEq, Repr + +instance : Cloud Kind where + Props := Props + Call := Call + Reply := Reply + needs := needs + Event := Event + Request := fun + | .function => Request + | _ => Empty + Response := fun + | .function => Response + | _ => Empty + +/-! ## The handles a program holds -/ + +abbrev Bucket := Ref Kind.bucket +abbrev Queue := Ref Kind.queue +abbrev Function := Ref Kind.function + +namespace S3 + +def Bucket (id : String) (props : BucketProps := {}) : Construct Kind AWS.Bucket := + resource Kind.bucket id props + +/-- Read the objects of a bucket under a prefix. With no prefix, all of them. -/ +abbrev Get (bucket : AWS.Bucket) (under : Path := []) : Access Kind := .on bucket (BucketOp.get under) + +/-- Write the objects of a bucket under a prefix. With no prefix, all of them. -/ +abbrev Put (bucket : AWS.Bucket) (under : Path := []) : Access Kind := .on bucket (BucketOp.put under) + +abbrev List (bucket : AWS.Bucket) : Access Kind := .on bucket BucketOp.list + +variable {R : Service Kind} {ε : Type} + +/-- How reading an object can fail. -/ +inductive GetObjectError where + | noSuchKey (error : NoSuchKey) +deriving DecidableEq, Repr + +/-- Reads the objects of a bucket under a prefix. -/ +structure GetObject.Client (bucket : AWS.Bucket) (under : Path) (access : Access Kind) where + call : String → Run access GetObjectError String + +/-- Writes the objects of a bucket under a prefix. -/ +structure PutObject.Client (bucket : AWS.Bucket) (under : Path) (access : Access Kind) where + call : String → String → Run access Never Unit + +/-- Lists the keys of a bucket. -/ +structure ListObjects.Client (bucket : AWS.Bucket) (access : Access Kind) where + call : Run access Never (_root_.List Path) + +/-- Read the objects of a bucket under a prefix: a step that gives the client. -/ +def GetObject (bucket : AWS.Bucket) (under : Path := []) {m : Type → Type} {access : Access Kind} + [Gives m (GetObject.Client bucket under) access] : m (GetObject.Client bucket under access) := + Layer.Gives.give + +/-- `GetObject` on the bucket itself. Grants read access to the prefix. -/ +def GetObjectLive (bucket : AWS.Bucket) (under : Path := []) : + Layer Nothing (GetObject.Client bucket under) where + needs := Get bucket under + build le _ := + { call := fun name => do + let found ← Run.performUnder bucket (BucketCall.getObject (under ++ [name])) + (BucketOp.get under) ⟨le⟩ (by simp [Cloud.needs, AWS.needs, Kinds.covers, BucketOp.covers]) + match found with + | .ok body => return body + | .error missing => throw (.noSuchKey missing) } + + +/-- Write the objects of a bucket under a prefix: a step that gives the client. -/ +def PutObject (bucket : AWS.Bucket) (under : Path := []) {m : Type → Type} {access : Access Kind} + [Gives m (PutObject.Client bucket under) access] : m (PutObject.Client bucket under access) := + Layer.Gives.give + +/-- `PutObject` on the bucket itself. Grants write access to the prefix. -/ +def PutObjectLive (bucket : AWS.Bucket) (under : Path := []) : + Layer Nothing (PutObject.Client bucket under) where + needs := Put bucket under + build le _ := + { call := fun name body => + Run.performUnder bucket (BucketCall.putObject (under ++ [name]) body) (BucketOp.put under) + ⟨le⟩ (by simp [Cloud.needs, AWS.needs, Kinds.covers, BucketOp.covers]) } + + +/-- List the keys of a bucket: a step that gives the client. -/ +def ListObjects (bucket : AWS.Bucket) {m : Type → Type} {access : Access Kind} + [Gives m (ListObjects.Client bucket) access] : m (ListObjects.Client bucket access) := + Layer.Gives.give + +/-- `ListObjects` on the bucket itself. Grants listing its keys. -/ +def ListObjectsLive (bucket : AWS.Bucket) : Layer Nothing (ListObjects.Client bucket) where + needs := List bucket + build le _ := { call := Run.perform bucket BucketCall.listObjects ⟨le⟩ } + + +/-- Read `under/name`. -/ +def getObjectE (bucket : AWS.Bucket) (under : Path) (name : String) + [Uses R (GetObject.Client bucket under)] [Raises ε GetObjectError] : Effect R ε String := + use (GetObject.Client bucket under) (·.call name) + +/-- Write `under/name`. -/ +def putObjectE (bucket : AWS.Bucket) (under : Path) (name : String) (body : String) + [Uses R (PutObject.Client bucket under)] : Effect R ε Unit := + use (PutObject.Client bucket under) (·.call name body) + +def listObjects (bucket : AWS.Bucket) [Uses R (ListObjects.Client bucket)] : + Effect R ε (_root_.List Path) := + use (ListObjects.Client bucket) (·.call) + +/-- Run this whenever an object is created in the bucket. -/ +def onObjectCreated {ε : Type} [Repr ε] (bucket : AWS.Bucket) + (handle : Path → Effect R ε Unit) : Listener R where + kind := .bucket + source := bucket + Error := ε + describe := reprStr + handle := fun + | .objectCreated key => handle key + +end S3 + +namespace SQS + +def Queue (id : String) (props : QueueProps := {}) : Construct Kind AWS.Queue := + resource Kind.queue id props + +abbrev Send (queue : AWS.Queue) : Access Kind := .on queue QueueOp.send +abbrev Receive (queue : AWS.Queue) : Access Kind := .on queue QueueOp.receive + +variable {R : Service Kind} {ε : Type} + +/-- Sends messages to a queue. -/ +structure SendMessage.Client (queue : AWS.Queue) (access : Access Kind) where + call : String → Run access Never Unit + +/-- Takes messages off a queue. -/ +structure ReceiveMessage.Client (queue : AWS.Queue) (access : Access Kind) where + call : Run access Never (Option String) + +/-- Put messages on a queue: a step that gives the client. -/ +def SendMessage (queue : AWS.Queue) {m : Type → Type} {access : Access Kind} + [Gives m (SendMessage.Client queue) access] : m (SendMessage.Client queue access) := + Layer.Gives.give + +/-- `SendMessage` on the queue itself. Grants sending to it. -/ +def SendMessageLive (queue : AWS.Queue) : Layer Nothing (SendMessage.Client queue) where + needs := Send queue + build le _ := { call := fun body => Run.perform queue (QueueCall.sendMessage body) ⟨le⟩ } + + +/-- Take messages off a queue: a step that gives the client. -/ +def ReceiveMessage (queue : AWS.Queue) {m : Type → Type} {access : Access Kind} + [Gives m (ReceiveMessage.Client queue) access] : m (ReceiveMessage.Client queue access) := + Layer.Gives.give + +/-- `ReceiveMessage` on the queue itself. Grants receiving from it. -/ +def ReceiveMessageLive (queue : AWS.Queue) : Layer Nothing (ReceiveMessage.Client queue) where + needs := Receive queue + build le _ := { call := Run.perform queue QueueCall.receiveMessage ⟨le⟩ } + + +def sendMessageE (queue : AWS.Queue) (body : String) [Uses R (SendMessage.Client queue)] : + Effect R ε Unit := + use (SendMessage.Client queue) (·.call body) + +def receiveMessage (queue : AWS.Queue) [Uses R (ReceiveMessage.Client queue)] : + Effect R ε (Option String) := + use (ReceiveMessage.Client queue) (·.call) + +/-- +Consume a queue: run this for each message. A step of a function's block, so +the function is registered as the queue's consumer when the stack is built. It +grants receiving from the queue, which is what takes the message off it. +-/ +def consume {role : Access Kind} {ε : Type} [Repr ε] (queue : AWS.Queue) + (handle : String → Run role ε Unit) [granted : Has role (Receive queue)] : Host role Unit := + Host.listen { + kind := .queue + source := queue + handle := fun (_ : QueueEvent) => do + match ← (((ReceiveMessageLive queue).build granted.le ⟨⟩).call).mapError (fun e => nomatch e) with + | some message => (handle message).mapError reprStr + | none => pure () } + +end SQS + +namespace Lambda + +/-- +A function. Its block binds what it uses and ends with how it answers a +request. Its role is the grants its bindings asked for. +-/ +def Function (id : String) (props : FunctionProps) + (body : {role : Access Kind} → Host role (Request → Run role Never Response)) : + Construct Kind AWS.Function := + hostOf Kind.function id props body + +/-- A function given its services by layers: its body ends with `serve`. -/ +def FunctionWith (id : String) (props : FunctionProps := {}) + (body : Construct Kind (Serve Kind.function)) : Construct Kind AWS.Function := + host Kind.function id props body + +end Lambda + +/-- A test's expectation: the function answers exactly this. -/ +def responds (expected : Response) : Cloud.Response Kind.function → Bool := + fun (got : Response) => got == expected + +/-! ## In memory -/ + +structure Memory where + objects : List (String × Path × String) := [] + messages : List (String × String) := [] +deriving DecidableEq, Repr + +namespace Memory + +def object (m : Memory) (bucket : AWS.Bucket) (key : Path) : Option String := + (m.objects.find? fun (id, k, _) => id == bucket.id && k == key).map (·.2.2) + +def queued (m : Memory) (queue : AWS.Queue) : List String := + (m.messages.filter (·.1 == queue.id)).map (·.2) + +/-- The keys of a bucket. -/ +def keys (m : Memory) (bucket : AWS.Bucket) : List Path := + (m.objects.filter (·.1 == bucket.id)).map (·.2.1) + +/-- Write an object, replacing whatever was at its key. -/ +def put (m : Memory) (bucket : AWS.Bucket) (key : Path) (body : String) : Memory := + { m with + objects := (m.objects.filter fun (id, k, _) => !(id == bucket.id && k == key)) + ++ [(bucket.id, key, body)] } + +/-- Put a message at the back of a queue. -/ +def send (m : Memory) (queue : AWS.Queue) (body : String) : Memory := + { m with messages := m.messages ++ [(queue.id, body)] } + +/-- Take the message at the front of a queue off it. -/ +def receive (m : Memory) (queue : AWS.Queue) : Memory := + match m.messages.find? (·.1 == queue.id) with + | none => m + | some message => { m with messages := m.messages.erase message } + +end Memory + +def simulate : {k : Kind} → Ref k → (c : Call k) → Memory → Reply c × Memory × List (Cloud.Emitted Kind) + | .bucket, bucket, .getObject key, m => + (match m.object bucket key with + | some body => .ok body + | none => .error { bucket := bucket.id, key }, m, []) + | .bucket, bucket, .putObject key body, m => + ((), m.put bucket key body, [(⟨.bucket, bucket, .objectCreated key⟩ : Cloud.Emitted Kind)]) + | .bucket, bucket, .listObjects, m => (m.keys bucket, m, []) + | .queue, queue, .sendMessage body, m => + ((), m.send queue body, [(⟨.queue, queue, .messageSent⟩ : Cloud.Emitted Kind)]) + | .queue, queue, .receiveMessage, m => ((m.queued queue).head?, m.receive queue, []) + +/-- AWS, in memory. -/ +abbrev InMemory : Sim Kind where + State := Memory + init := {} + call := simulate + +end Alchemy.AWS diff --git a/packages/alchemy-lean/Alchemy/Cloud/AWSControl.lean b/packages/alchemy-lean/Alchemy/Cloud/AWSControl.lean new file mode 100644 index 00000000000..00b27186126 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/AWSControl.lean @@ -0,0 +1,442 @@ +import Alchemy.Cloud.AWS +import Alchemy.Cloud.Engine +import Alchemy.Cloud.Cli + +/-! +# The AWS control plane, in small + +The operations that create, change and remove buckets, queues and functions, +each with the errors it can return; a model of what they do; and the providers +that drive them, with proofs. + +In a real SDK this file's `Api` is generated from the service's own description. +-/ + +namespace Alchemy.AWS.Control +open Alchemy.Cloud +open Distilled (Api Eff Model) + +/-! ## The API -/ + +inductive Op where + | createBucket | headBucket | putBucketVersioning | getBucketVersioning | deleteBucket + | createQueue | getQueueAttributes | setQueueAttributes | deleteQueue + | createFunction | getFunctionConfiguration | updateFunctionConfiguration | deleteFunction +deriving DecidableEq, Repr + +inductive CreateBucketError where + /-- You already have this bucket. -/ + | bucketAlreadyOwnedByYou + /-- Somebody else has this name. -/ + | bucketAlreadyExists +deriving DecidableEq, Repr + +inductive HeadBucketError where + | notFound +deriving DecidableEq, Repr + +inductive BucketError where + | noSuchBucket +deriving DecidableEq, Repr + +inductive DeleteBucketError where + | noSuchBucket + | bucketNotEmpty +deriving DecidableEq, Repr + +inductive CreateQueueError where + /-- A queue with this name exists with other attributes. -/ + | queueNameExists +deriving DecidableEq, Repr + +inductive QueueError where + | queueDoesNotExist +deriving DecidableEq, Repr + +inductive CreateFunctionError where + | resourceConflict +deriving DecidableEq, Repr + +inductive FunctionError where + | resourceNotFound +deriving DecidableEq, Repr + +abbrev Input : Op → Type + | .createBucket | .headBucket | .getBucketVersioning | .deleteBucket => Slot + | .putBucketVersioning => Slot × Bool + | .createQueue => Slot × QueueProps + | .setQueueAttributes => Slot × Nat + | .getQueueAttributes | .deleteQueue => Slot + | .createFunction | .updateFunctionConfiguration => Slot × FunctionProps + | .getFunctionConfiguration | .deleteFunction => Slot + +abbrev Output : Op → Type + | .getBucketVersioning => Bool + | .getQueueAttributes => QueueProps + | .getFunctionConfiguration => FunctionProps + | _ => Unit + +abbrev Error : Op → Type + | .createBucket => CreateBucketError + | .headBucket => HeadBucketError + | .putBucketVersioning | .getBucketVersioning => BucketError + | .deleteBucket => DeleteBucketError + | .createQueue => CreateQueueError + | .getQueueAttributes | .setQueueAttributes | .deleteQueue => QueueError + | .createFunction => CreateFunctionError + | .getFunctionConfiguration | .updateFunctionConfiguration | .deleteFunction => FunctionError + +/-- The control plane: every operation, with its input, output and errors. -/ +abbrev Api : Distilled.Api where + Op := Op + In := Input + Out := Output + Err := Error + +/-! ## What the service does -/ + +structure BucketState where + versioned : Bool := false + /-- How many objects it holds. A bucket that holds any cannot be deleted. -/ + objects : Nat := 0 + +/-- An AWS account, as far as these operations can tell. -/ +structure Account where + buckets : Slot → Option BucketState := fun _ => none + /-- Bucket names somebody else has. -/ + taken : Slot → Bool := fun _ => false + queues : Slot → Option QueueProps := fun _ => none + functions : Slot → Option FunctionProps := fun _ => none + +def put {α : Type} (map : Slot → Option α) (name : Slot) (value : Option α) : Slot → Option α := + fun n => if n = name then value else map n + +@[simp] theorem put_self {α : Type} (map : Slot → Option α) (name : Slot) (value : Option α) : + put map name value name = value := by simp [put] + +theorem put_of_ne {α : Type} (map : Slot → Option α) {name other : Slot} (value : Option α) + (ne : other ≠ name) : put map name value other = map other := by simp [put, ne] + +def step : (op : Op) → Input op → Account → Except (Error op) (Output op) × Account + | .createBucket, name, a => + if a.taken name then (.error .bucketAlreadyExists, a) + else match a.buckets name with + | some _ => (.error .bucketAlreadyOwnedByYou, a) + | none => (.ok (), { a with buckets := put a.buckets name (some {}) }) + | .headBucket, name, a => + match a.buckets name with + | some _ => (.ok (), a) + | none => (.error .notFound, a) + | .putBucketVersioning, (name, versioned), a => + match a.buckets name with + | some bucket => (.ok (), { a with buckets := put a.buckets name (some { bucket with versioned }) }) + | none => (.error .noSuchBucket, a) + | .getBucketVersioning, name, a => + match a.buckets name with + | some bucket => (.ok bucket.versioned, a) + | none => (.error .noSuchBucket, a) + | .deleteBucket, name, a => + match a.buckets name with + | none => (.error .noSuchBucket, a) + | some bucket => + if bucket.objects = 0 then (.ok (), { a with buckets := put a.buckets name none }) + else (.error .bucketNotEmpty, a) + | .createQueue, (name, props), a => + match a.queues name with + | none => (.ok (), { a with queues := put a.queues name (some props) }) + | some existing => if existing = props then (.ok (), a) else (.error .queueNameExists, a) + | .getQueueAttributes, name, a => + match a.queues name with + | some queue => (.ok queue, a) + | none => (.error .queueDoesNotExist, a) + | .setQueueAttributes, (name, visibilityTimeout), a => + match a.queues name with + | some queue => + (.ok (), { a with queues := put a.queues name (some { queue with visibilityTimeout }) }) + | none => (.error .queueDoesNotExist, a) + | .deleteQueue, name, a => + match a.queues name with + | some _ => (.ok (), { a with queues := put a.queues name none }) + | none => (.error .queueDoesNotExist, a) + | .createFunction, (name, props), a => + match a.functions name with + | none => (.ok (), { a with functions := put a.functions name (some props) }) + | some _ => (.error .resourceConflict, a) + | .getFunctionConfiguration, name, a => + match a.functions name with + | some function => (.ok function, a) + | none => (.error .resourceNotFound, a) + | .updateFunctionConfiguration, (name, props), a => + match a.functions name with + | some _ => (.ok (), { a with functions := put a.functions name (some props) }) + | none => (.error .resourceNotFound, a) + | .deleteFunction, name, a => + match a.functions name with + | some _ => (.ok (), { a with functions := put a.functions name none }) + | none => (.error .resourceNotFound, a) + +/-- AWS, as these providers need to understand it. -/ +def Service : Model Api where + State := Account + step := step + +/-! ## The providers -/ + +abbrev Calls (α : Type) := Eff Api Failure α + +def call (op : Op) (input : Input op) : Calls (Except (Error op) (Output op)) := + Eff.ask (api := Api) op input + +/-- A bucket. Versioning can be changed in place. -/ +def BucketProvider : Provider Api BucketProps Slot where + diff old new := if old = new then .noop else .update + reconcile name props := do + -- observe, and create it if it is missing; losing a race to our own create is fine + match ← call .headBucket name with + | .ok () => pure () + | .error .notFound => + match ← call .createBucket name with + | .ok () | .error .bucketAlreadyOwnedByYou => pure () + | .error .bucketAlreadyExists => throw "the bucket name is taken by another account" + -- sync + match ← call .putBucketVersioning (name, props.versioned) with + | .ok () => return name + | .error .noSuchBucket => throw "the bucket disappeared while it was being configured" + delete name := do + match ← call .deleteBucket name with + | .ok () | .error .noSuchBucket => return + | .error .bucketNotEmpty => throw "the bucket still holds objects" + +/-- A queue. Whether it is first-in-first-out is fixed at creation. -/ +def QueueProvider : Provider Api QueueProps Slot where + diff old new := + if old = new then .noop else if old.fifo = new.fifo then .update else .replace + reconcile name props := do + match ← call .getQueueAttributes name with + | .error .queueDoesNotExist => + match ← call .createQueue (name, props) with + | .ok () => return name + | .error .queueNameExists => throw "a queue with this name was created with other attributes" + | .ok current => + if current.fifo ≠ props.fifo then + throw "a queue cannot change whether it is first-in-first-out" + else + match ← call .setQueueAttributes (name, props.visibilityTimeout) with + | .ok () => return name + | .error .queueDoesNotExist => throw "the queue disappeared while it was being configured" + delete name := do + match ← call .deleteQueue name with + | .ok () | .error .queueDoesNotExist => return + +/-- A function. Everything about it can be changed in place. -/ +def FunctionProvider : Provider Api FunctionProps Slot where + diff old new := if old = new then .noop else .update + reconcile name props := do + match ← call .getFunctionConfiguration name with + | .error .resourceNotFound => + match ← call .createFunction (name, props) with + | .ok () => return name + | .error .resourceConflict => throw "the function was created by something else meanwhile" + | .ok _ => + match ← call .updateFunctionConfiguration (name, props) with + | .ok () => return name + | .error .resourceNotFound => throw "the function disappeared while it was being configured" + delete name := do + match ← call .deleteFunction name with + | .ok () | .error .resourceNotFound => return + +/-- A provider for every kind. -/ +def providers : Providers Kind Api where + Attrs := fun _ => Slot + provider := fun + | .bucket => BucketProvider + | .queue => QueueProvider + | .function => FunctionProvider + +/-! ## The providers are lawful -/ + +set_option linter.unusedSimpArgs false + +/-- Whether a physical resource exists in the account. -/ +def present : Physical Kind → Account → Bool + | ⟨.bucket, id, generation⟩, a => (a.buckets ⟨id, generation⟩).isSome + | ⟨.queue, id, generation⟩, a => (a.queues ⟨id, generation⟩).isSome + | ⟨.function, id, generation⟩, a => (a.functions ⟨id, generation⟩).isSome + +/-- Unfolds a provider's code running against the model, down to lookups in the account. -/ +macro "run_provider" : tactic => + `(tactic| simp only [providers, BucketProvider, QueueProvider, FunctionProvider, call, Eff.ask, + Bind.bind, Eff.bind, Eff.run, Service, step, Pure.pure, throw, present, Physical.slot] at *) + +/-- A bucket reconcile that succeeds leaves the bucket there, with the versioning asked for. -/ +theorem bucket_reconciled (name : Slot) (props : BucketProps) (a a' : Account) (attrs : Slot) + (ok : (BucketProvider.reconcile name props).run Service a = (.ok attrs, a')) : + ∃ bucket, a'.buckets name = some bucket ∧ bucket.versioned = props.versioned := by + run_provider + cases bucket : a.buckets name <;> cases taken : a.taken name <;> + simp [Eff.run, step, bucket, taken, put] at ok <;> (obtain ⟨_, rfl⟩ := ok) <;> simp [put] + +/-- However a bucket reconcile ends, it touches no other bucket, no queue and no function. -/ +theorem bucket_reconcile_frame (name : Slot) (props : BucketProps) (a : Account) : + let a' := ((BucketProvider.reconcile name props).run Service a).2 + (∀ other, other ≠ name → a'.buckets other = a.buckets other) ∧ + a'.queues = a.queues ∧ a'.functions = a.functions := by + run_provider + cases bucket : a.buckets name <;> cases taken : a.taken name <;> + simp [Eff.run, step, bucket, taken, put] <;> grind + +/-- A bucket delete that succeeds leaves the bucket gone, whether it was there or not. -/ +theorem bucket_deleted (name : Slot) (a a' : Account) + (ok : (BucketProvider.delete name).run Service a = (.ok (), a')) : a'.buckets name = none := by + run_provider + cases bucket : a.buckets name with + | none => simp [Eff.run, bucket] at ok; rw [← ok]; exact bucket + | some held => + by_cases empty : held.objects = 0 <;> simp [Eff.run, bucket, empty] at ok + rw [← ok]; simp + +theorem bucket_delete_frame (name : Slot) (a : Account) : + let a' := ((BucketProvider.delete name).run Service a).2 + (∀ other, other ≠ name → a'.buckets other = a.buckets other) ∧ + a'.queues = a.queues ∧ a'.functions = a.functions := by + run_provider + cases bucket : a.buckets name with + | none => simp [Eff.run, bucket] + | some held => + by_cases empty : held.objects = 0 <;> simp [Eff.run, bucket, empty] + intro other ne; simp [put, ne] + +/-- A queue reconcile that succeeds leaves the queue there, configured as asked. -/ +theorem queue_reconciled (name : Slot) (props : QueueProps) (a a' : Account) (attrs : Slot) + (ok : (QueueProvider.reconcile name props).run Service a = (.ok attrs, a')) : + a'.queues name = some props := by + run_provider + cases queue : a.queues name <;> simp [Eff.run, step, queue] at ok + · rw [← ok.2]; simp + · split at ok <;> simp [Eff.run, step, queue] at ok + rw [← ok.2] + simp + cases props; cases ‹QueueProps›; simp_all + +theorem queue_reconcile_frame (name : Slot) (props : QueueProps) (a : Account) : + let a' := ((QueueProvider.reconcile name props).run Service a).2 + (∀ other, other ≠ name → a'.queues other = a.queues other) ∧ + a'.buckets = a.buckets ∧ a'.functions = a.functions := by + run_provider + cases queue : a.queues name <;> simp [Eff.run, step, queue, put] + · grind + · split <;> simp [Eff.run, step, queue, put] <;> grind + +theorem queue_deleted (name : Slot) (a a' : Account) + (ok : (QueueProvider.delete name).run Service a = (.ok (), a')) : a'.queues name = none := by + run_provider + cases queue : a.queues name <;> simp [Eff.run, step, queue] at ok <;> rw [← ok] <;> simp [queue] + +theorem queue_delete_frame (name : Slot) (a : Account) : + let a' := ((QueueProvider.delete name).run Service a).2 + (∀ other, other ≠ name → a'.queues other = a.queues other) ∧ + a'.buckets = a.buckets ∧ a'.functions = a.functions := by + run_provider + cases queue : a.queues name <;> simp [Eff.run, step, queue, put] <;> grind + +/-- A function reconcile that succeeds leaves the function there, configured as asked. -/ +theorem function_reconciled (name : Slot) (props : FunctionProps) (a a' : Account) (attrs : Slot) + (ok : (FunctionProvider.reconcile name props).run Service a = (.ok attrs, a')) : + a'.functions name = some props := by + run_provider + cases function : a.functions name <;> simp [Eff.run, step, function] at ok <;> + rw [← ok.2] <;> simp + +theorem function_reconcile_frame (name : Slot) (props : FunctionProps) (a : Account) : + let a' := ((FunctionProvider.reconcile name props).run Service a).2 + (∀ other, other ≠ name → a'.functions other = a.functions other) ∧ + a'.buckets = a.buckets ∧ a'.queues = a.queues := by + run_provider + cases function : a.functions name <;> simp [Eff.run, step, function, put] <;> grind + +theorem function_deleted (name : Slot) (a a' : Account) + (ok : (FunctionProvider.delete name).run Service a = (.ok (), a')) : + a'.functions name = none := by + run_provider + cases function : a.functions name <;> simp [Eff.run, step, function] at ok <;> + rw [← ok] <;> simp [function] + +theorem function_delete_frame (name : Slot) (a : Account) : + let a' := ((FunctionProvider.delete name).run Service a).2 + (∀ other, other ≠ name → a'.functions other = a.functions other) ∧ + a'.buckets = a.buckets ∧ a'.queues = a.queues := by + run_provider + cases function : a.functions name <;> simp [Eff.run, step, function, put] <;> grind + +/-- These providers meet what the engine relies on, against this model of AWS. -/ +def lawful : Lawful providers Service where + present := present + diff_self := by + intro k props + cases k <;> simp [providers, BucketProvider, QueueProvider, FunctionProvider] + reconcile_ok := by + intro k slot props s attrs s' ok + cases k + · obtain ⟨_, here, _⟩ := bucket_reconciled slot props s s' attrs ok + simp [present, here] + · simp [present, queue_reconciled slot props s s' attrs ok] + · simp [present, function_reconciled slot props s s' attrs ok] + reconcile_frame := by + intro k slot props s y ne + cases k + · obtain ⟨buckets, queues, functions⟩ := bucket_reconcile_frame slot props s + obtain ⟨_ | _ | _, id, generation⟩ := y <;> simp only [present, providers, queues, functions] + rw [buckets]; intro same; cases same; exact ne rfl + · obtain ⟨queues, buckets, functions⟩ := queue_reconcile_frame slot props s + obtain ⟨_ | _ | _, id, generation⟩ := y <;> simp only [present, providers, buckets, functions] + rw [queues]; intro same; cases same; exact ne rfl + · obtain ⟨functions, buckets, queues⟩ := function_reconcile_frame slot props s + obtain ⟨_ | _ | _, id, generation⟩ := y <;> simp only [present, providers, buckets, queues] + rw [functions]; intro same; cases same; exact ne rfl + delete_ok := by + intro k slot s s' ok + cases k + · simp [present, bucket_deleted slot s s' ok] + · simp [present, queue_deleted slot s s' ok] + · simp [present, function_deleted slot s s' ok] + delete_frame := by + intro k slot s y ne + cases k + · obtain ⟨buckets, queues, functions⟩ := bucket_delete_frame slot s + obtain ⟨_ | _ | _, id, generation⟩ := y <;> simp only [present, providers, queues, functions] + rw [buckets]; intro same; cases same; exact ne rfl + · obtain ⟨queues, buckets, functions⟩ := queue_delete_frame slot s + obtain ⟨_ | _ | _, id, generation⟩ := y <;> simp only [present, providers, buckets, functions] + rw [queues]; intro same; cases same; exact ne rfl + · obtain ⟨functions, buckets, queues⟩ := function_delete_frame slot s + obtain ⟨_ | _ | _, id, generation⟩ := y <;> simp only [present, providers, buckets, queues] + rw [functions]; intro same; cases same; exact ne rfl + +end Alchemy.AWS.Control + +namespace Alchemy.AWS +open Alchemy.Cloud + +/-- A grant, in words. -/ +def describeGrant : Attempt Kind → String + | ⟨.bucket, bucket, .get under⟩ => s!"read {bucket.id}/{"/".intercalate under}" + | ⟨.bucket, bucket, .put under⟩ => s!"write {bucket.id}/{"/".intercalate under}" + | ⟨.bucket, bucket, .list⟩ => s!"list {bucket.id}" + | ⟨.queue, queue, .send⟩ => s!"send to {queue.id}" + | ⟨.queue, queue, .receive⟩ => s!"receive from {queue.id}" + | ⟨.function, function, .invoke⟩ => s!"invoke {function.id}" + +/-- A resource's settings, by name. -/ +def describeSettings : (k : Kind) → Cloud.Props k → List (String × String) + | .bucket, (props : BucketProps) => [("versioned", toString props.versioned)] + | .queue, (props : QueueProps) => + [("fifo", toString props.fifo), ("visibilityTimeout", toString props.visibilityTimeout)] + | .function, (props : FunctionProps) => + [("url", toString props.url), ("memory", toString props.memory)] + +/-- Run a stack from the command line, against an empty model of an AWS account. -/ +def cli {Out : Type} (stack : Stack Kind Out) (args : List String) : IO UInt32 := + stack.cli Control.providers (⟨.empty, {}⟩ : Cloud.World Kind Control.Service) describeGrant + describeSettings args + +end Alchemy.AWS diff --git a/packages/alchemy-lean/Alchemy/Cloud/AWSJournal.lean b/packages/alchemy-lean/Alchemy/Cloud/AWSJournal.lean new file mode 100644 index 00000000000..5b9ffd490dd --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/AWSJournal.lean @@ -0,0 +1,442 @@ +import Std.Data.String.ToNat +import Alchemy.Cloud.AWSLaws +import Alchemy.Cloud.HostedLaws +import Alchemy.Cloud.Tactics +import Alchemy.Cloud.Infer + +/-! +# A journal in S3 + +Where a hosted model keeps its history on AWS. +-/ + +namespace Alchemy.AWS.S3 +open Alchemy.Cloud + +/-- A line as the text of an object: a mark for which kind it is, then its text. -/ +def encodeLine : Cloud.Journal.Line → String + | .input text => String.ofList ('>' :: text.toList) + | .answer text => String.ofList ('<' :: text.toList) + | .decided text => String.ofList ('!' :: text.toList) + +def decodeLine (body : String) : Option Cloud.Journal.Line := + match body.toList with + | '>' :: text => some (.input (String.ofList text)) + | '<' :: text => some (.answer (String.ofList text)) + | '!' :: text => some (.decided (String.ofList text)) + | _ => none + +theorem decode_encode (line : Cloud.Journal.Line) : decodeLine (encodeLine line) = some line := by + cases line <;> simp [encodeLine, decodeLine, String.ofList_toList] + +variable {access : Access Kind} {bucket : AWS.Bucket} {under : Path} + +/-- The lines of a journal, from one on: stops at the first that is missing. -/ +def readFrom (reader : GetObject.Client bucket (under ++ ["lines"]) access) : + Nat → Nat → Run access Never (_root_.List Cloud.Journal.Line) + | _, 0 => pure [] + | first, count + 1 => do + match ← (reader.call (toString first)).result with + | .ok body => + match decodeLine body with + | some line => return line :: (← readFrom reader (first + 1) count) + | none => readFrom reader (first + 1) count + | .error _ => pure [] + +/-- How many lines a journal holds, from what its counter reads. -/ +def countFrom (counter : GetObject.Client bucket under access) : Run access Never Nat := do + match ← (counter.call "count").result with + | .ok text => return text.toNat?.getD 0 + | .error _ => return 0 + +/-- +A journal from four bindings: a counter under a prefix, and one object a line +under `lines/`. A line is written before the counter moves, so a line is never +counted before it is there. +-/ +def journalOf (counter : GetObject.Client bucket under access) + (setCounter : PutObject.Client bucket under access) + (reader : GetObject.Client bucket (under ++ ["lines"]) access) + (writer : PutObject.Client bucket (under ++ ["lines"]) access) : Cloud.Journal access where + read := do readFrom reader 0 (← countFrom counter) + append := fun line => do + let count ← countFrom counter + writer.call (toString count) (encodeLine line) + setCounter.call "count" (toString (count + 1)) + +/-- +A journal kept in a bucket. Grants reading and writing its counter, and +reading and writing its lines. +-/ +def JournalLive (bucket : AWS.Bucket) (under : Path := ["journal"]) : Layer Nothing (Journal (K := Kind)) := + .from (GetObjectLive bucket under ++ PutObjectLive bucket under + ++ GetObjectLive bucket (under ++ ["lines"]) ++ PutObjectLive bucket (under ++ ["lines"])) do + return journalOf (← GetObject bucket under) (← PutObject bucket under) + (← GetObject bucket (under ++ ["lines"])) (← PutObject bucket (under ++ ["lines"])) + +/-! ## The journal's law, from the laws of the bindings it is built on -/ + +/-- How many lines the model of S3 holds for a journal. -/ +def count (bucket : AWS.Bucket) (under : Path) (m : Memory) : Nat := + match m.object bucket (under ++ ["count"]) with + | some text => text.toNat?.getD 0 + | none => 0 + +/-- The lines the model of S3 holds for a journal, read the way the journal reads them. -/ +def linesFrom (bucket : AWS.Bucket) (under : Path) (m : Memory) : + Nat → Nat → _root_.List Cloud.Journal.Line + | _, 0 => [] + | first, count + 1 => + match m.object bucket (under ++ ["lines"] ++ [toString first]) with + | some body => + match decodeLine body with + | some line => line :: linesFrom bucket under m (first + 1) count + | none => linesFrom bucket under m (first + 1) count + | none => [] + +def lines (bucket : AWS.Bucket) (under : Path) (m : Memory) : _root_.List Cloud.Journal.Line := + linesFrom bucket under m 0 (count bucket under m) + +/-- A journal is sound when every line its counter counts is there. -/ +def Sound (bucket : AWS.Bucket) (under : Path) (m : Memory) : Prop := + ∃ held : _root_.List Cloud.Journal.Line, held.length = count bucket under m ∧ + ∀ i (h : i < held.length), + m.object bucket (under ++ ["lines"] ++ [toString i]) = some (encodeLine held[i]) + +theorem countFrom_eval {counter : GetObject.Client bucket under access} + (lawful : GetObject.Lawful counter) (m : Memory) : + (countFrom counter).eval InMemory m = (.ok (count bucket under m), m) := by + show Run.eval InMemory (Run.bind _ _) m = _ + rw [Run.eval_bind, Run.eval_result, lawful.get] + simp only [count] + cases m.object bucket (under ++ ["count"]) <;> rfl + +theorem readFrom_eval {reader : GetObject.Client bucket (under ++ ["lines"]) access} + (lawful : GetObject.Lawful reader) (m : Memory) : + ∀ count first, (readFrom reader first count).eval InMemory m + = (.ok (linesFrom bucket under m first count), m) := by + intro count + induction count with + | zero => intro first; rfl + | succ count ih => + intro first + show Run.eval InMemory (Run.bind _ _) m = _ + rw [Run.eval_bind, Run.eval_result, lawful.get] + cases found : m.object bucket (under ++ ["lines"] ++ [toString first]) with + | none => simp only [linesFrom, found]; rfl + | some body => + cases decoded : decodeLine body with + | none => + simp only [linesFrom, found, decoded] + exact ih _ + | some line => + simp only [linesFrom, found, decoded] + show Run.eval InMemory (Run.bind _ _) m = _ + rw [Run.eval_bind, ih] + rfl + +/-- What a sound journal reads is the lines it holds. -/ +theorem linesFrom_held (m : Memory) (rest : _root_.List Cloud.Journal.Line) : + ∀ first, (∀ i (h : i < rest.length), + m.object bucket (under ++ ["lines"] ++ [toString (first + i)]) = some (encodeLine rest[i])) → + linesFrom bucket under m first rest.length = rest := by + induction rest with + | nil => intro _ _; rfl + | cons line rest ih => + intro first held + have head := held 0 (by simp) + simp only [Nat.add_zero, List.getElem_cons_zero] at head + simp only [List.length_cons, linesFrom, head, decode_encode] + congr 1 + apply ih + intro i h + have := held (i + 1) (by simpa using h) + simpa [Nat.add_assoc, Nat.add_comm 1 i] using this + +theorem lineKey_ne_countKey (under : Path) (name : String) : + ¬(under ++ ["lines"] ++ [name] = under ++ ["count"]) := by + intro same + have := congrArg _root_.List.length same + simp at this + +theorem lineKey_inj (under : Path) (i j : Nat) + (same : under ++ ["lines"] ++ [toString i] = under ++ ["lines"] ++ [toString j]) : i = j := by + have := List.append_cancel_left same + simpa [Nat.toString_eq_repr, Nat.repr_inj] using this + +/-- +The journal keeps its law, given only that the four bindings it is built on +keep theirs. +-/ +theorem journalOf_lawful {counter : GetObject.Client bucket under access} + {setCounter : PutObject.Client bucket under access} + {reader : GetObject.Client bucket (under ++ ["lines"]) access} + {writer : PutObject.Client bucket (under ++ ["lines"]) access} + (counts : GetObject.Lawful counter) (setsCount : PutObject.Lawful setCounter) + (reads : GetObject.Lawful reader) (writes : PutObject.Lawful writer) : + (journalOf counter setCounter reader writer).Lawful InMemory (lines bucket under) + (Sound bucket under) where + read m := by + show Run.eval InMemory (Run.bind _ _) m = _ + rw [Run.eval_bind, countFrom_eval counts] + exact readFrom_eval reads m _ _ + append m line sound := by + obtain ⟨held, length, present⟩ := sound + have evaluated : ((journalOf counter setCounter reader writer).append line).eval InMemory m + = (.ok (), (m.put bucket (under ++ ["lines"] ++ [toString (count bucket under m)]) + (encodeLine line)).put bucket (under ++ ["count"]) + (toString (count bucket under m + 1))) := by + show Run.eval InMemory (Run.bind _ _) m = _ + rw [Run.eval_bind, countFrom_eval counts] + show Run.eval InMemory (Run.bind _ _) m = _ + rw [Run.eval_bind, writes.put] + exact setsCount.put _ _ _ + rw [evaluated] + have counted : count bucket under ((m.put bucket (under ++ ["lines"] ++ + [toString (count bucket under m)]) (encodeLine line)).put bucket (under ++ ["count"]) + (toString (count bucket under m + 1))) = (held ++ [line]).length := by + simp [count, Memory.object_put_self, Nat.toString_eq_repr, Nat.toNat?_repr, length] + have stored : ∀ i (h : i < (held ++ [line]).length), + ((m.put bucket (under ++ ["lines"] ++ [toString (count bucket under m)]) + (encodeLine line)).put bucket (under ++ ["count"]) + (toString (count bucket under m + 1))).object bucket + (under ++ ["lines"] ++ [toString i]) = some (encodeLine (held ++ [line])[i]) := by + intro i h + rw [Memory.object_put_other _ _ _ _ _ _ (fun same => lineKey_ne_countKey under _ same.2)] + by_cases last : i = held.length + · subst last + have here : (m.put bucket (under ++ ["lines"] ++ [toString (count bucket under m)]) + (encodeLine line)).object bucket (under ++ ["lines"] ++ [toString held.length]) + = some (encodeLine line) := by + rw [length]; exact Memory.object_put_self _ _ _ _ + rw [here] + simp + · have earlier : i < held.length := by + simp only [List.length_append, List.length_cons, List.length_nil] at h + omega + rw [Memory.object_put_other _ _ _ _ _ _ (fun same => by + have := lineKey_inj under _ _ same.2 + omega)] + rw [present i earlier] + simp [List.getElem_append_left earlier] + refine ⟨rfl, ?_, held ++ [line], counted.symm, stored⟩ + have before : lines bucket under m = held := by + unfold lines + rw [← length] + exact linesFrom_held m held 0 (by simpa using present) + rw [before] + show linesFrom bucket under _ 0 (count bucket under _) = _ + rw [counted] + exact linesFrom_held _ (held ++ [line]) 0 (by simpa using stored) + +/-- The journal on S3 keeps the journal's law. -/ +theorem JournalLive.lawful (bucket : AWS.Bucket) (under : Path) {access : Access Kind} + (le : (JournalLive bucket under).needs ≤ access) : + ((JournalLive bucket under).build le ⟨⟩).Lawful InMemory (lines bucket under) + (Sound bucket under) := by + have part : ∀ {need : Access Kind}, (∀ t, need.permits t = true → + (JournalLive bucket under).needs.permits t = true) → need ≤ access := + fun within t h => le t (within t h) + apply journalOf_lawful + · exact GetObjectLive.lawful _ _ (part fun t h => by simp [JournalLive, Layer.from, h]) + · exact PutObjectLive.lawful _ _ (part fun t h => by simp [JournalLive, Layer.from, h]) + · exact GetObjectLive.lawful _ _ (part fun t h => by simp [JournalLive, Layer.from, h]) + · exact PutObjectLive.lawful _ _ (part fun t h => by simp [JournalLive, Layer.from, h]) + +theorem linesFrom_same {m m' : Memory} + (same : ∀ key, m'.object bucket key = m.object bucket key) : + ∀ count first, linesFrom bucket under m' first count = linesFrom bucket under m first count := by + intro count + induction count with + | zero => intro _; rfl + | succ count ih => intro first; simp only [linesFrom, same, ih] + +/-- Whatever leaves a bucket's objects alone leaves a journal in it alone, and sound. -/ +theorem untouched {m m' : Memory} (same : ∀ key, m'.object bucket key = m.object bucket key) : + lines bucket under m' = lines bucket under m ∧ (Sound bucket under m → Sound bucket under m') := by + have counted : count bucket under m' = count bucket under m := by simp only [count, same] + refine ⟨by simp only [lines, counted, linesFrom_same same], ?_⟩ + rintro ⟨held, length, present⟩ + exact ⟨held, by rw [counted]; exact length, fun i h => by rw [same]; exact present i h⟩ + +/-- +Code that leaves a bucket's objects alone leaves a journal in it alone, and +sound. This is what an outside call has to show to be used beside a journal. +-/ +theorem quiet {access : Access Kind} {ε α : Type} (run : Run access ε α) (m : Memory) + (objects : ∀ key, (run.eval InMemory m).2.object bucket key = m.object bucket key) + (sound : Sound bucket under m) : + lines bucket under (run.eval InMemory m).2 = lines bucket under m ∧ + Sound bucket under (run.eval InMemory m).2 := + ⟨(untouched objects).1, (untouched objects).2 sound⟩ + +end Alchemy.AWS.S3 + +namespace Alchemy.AWS +open Alchemy.Cloud + +/-! ## Requests, in a test -/ + +/-- A request on its way to a function, in a test. -/ +structure Asked where + function : AWS.Function + request : Request + +def pathOf (path : String) : Path := (path.splitOn "/").filter (· ≠ "") + +/-- `get api "/orders/o-1"` -/ +def get (function : AWS.Function) (path : String) : Asked := + ⟨function, { method := .get, path := pathOf path }⟩ + +/-- `post api "/orders/o-1" body`: the body is sent as JSON. -/ +def post {α : Type} [Text α] (function : AWS.Function) (path : String) (body : α) : Asked := + ⟨function, { method := .post, path := pathOf path, body := Text.write body }⟩ + +/-- `get api "/revenue" ⇒ (200, "40")`: the request, and the status and body it must get. -/ +def Asked.answers (asked : Asked) (expected : Nat × String) : Graph.Step Kind InMemory := + .request asked.function asked.request (responds { status := expected.1, body := expected.2 }) + +@[inherit_doc] infix:50 " ⇒ " => Asked.answers + +end Alchemy.AWS + +/-! ## What can be done to a resource, in words -/ + +namespace Alchemy.AWS +open Alchemy.Cloud + +namespace S3 + +/-- Writing a bucket's objects under a prefix. With no prefix, any of them. -/ +abbrev writing (bucket : AWS.Bucket) (under : Path := []) : Doing Kind := + ⟨Path, fun rest => ⟨.bucket, bucket, BucketOp.put (under ++ rest)⟩⟩ + +/-- Reading a bucket's objects under a prefix. With no prefix, any of them. -/ +abbrev reading (bucket : AWS.Bucket) (under : Path := []) : Doing Kind := + ⟨Path, fun rest => ⟨.bucket, bucket, BucketOp.get (under ++ rest)⟩⟩ + +/-- Listing a bucket's keys. -/ +abbrev listing (bucket : AWS.Bucket) : Doing Kind := + ⟨Unit, fun _ => ⟨.bucket, bucket, BucketOp.list⟩⟩ + +end S3 + +namespace SQS + +/-- Putting messages on a queue. -/ +abbrev sending (queue : AWS.Queue) : Doing Kind := + ⟨Unit, fun _ => ⟨.queue, queue, QueueOp.send⟩⟩ + +/-- Taking messages off a queue. -/ +abbrev receiving (queue : AWS.Queue) : Doing Kind := + ⟨Unit, fun _ => ⟨.queue, queue, QueueOp.receive⟩⟩ + +end SQS + +namespace Lambda + +/-- Invoking a function. -/ +abbrev invoking (function : AWS.Function) : Doing Kind := + ⟨Unit, fun _ => ⟨.function, function, FunctionOp.invoke⟩⟩ + +end Lambda + +end Alchemy.AWS + +/-! ## Operations called directly: the call is what asks for the grant -/ + +namespace Alchemy.AWS +open Alchemy.Cloud + +namespace S3 + +/-- Write `under/name`. -/ +def putObject {role : Access Kind} (bucket : AWS.Bucket) (under : Path) (name body : String) + [granted : Has role (Put bucket under)] : Run role Never Unit := + ((PutObjectLive bucket under).build granted.le ⟨⟩).call name body + +/-- Read `under/name`. -/ +def getObject {role : Access Kind} (bucket : AWS.Bucket) (under : Path) (name : String) + [granted : Has role (Get bucket under)] : Run role GetObjectError String := + ((GetObjectLive bucket under).build granted.le ⟨⟩).call name + +/-- Writing an object does what the model says. -/ +theorem putObject_eval {role : Access Kind} (bucket : AWS.Bucket) (under : Path) (name body : String) + [granted : Has role (Put bucket under)] (m : Memory) : + (putObject (role := role) bucket under name body).eval InMemory m + = (.ok (), m.put bucket (under ++ [name]) body) := + (PutObjectLive.lawful bucket under granted.le).put m name body + +/-- Reading an object answers what the model holds, and changes nothing. -/ +theorem getObject_eval {role : Access Kind} (bucket : AWS.Bucket) (under : Path) (name : String) + [granted : Has role (Get bucket under)] (m : Memory) : + (getObject (role := role) bucket under name).eval InMemory m = + (match m.object bucket (under ++ [name]) with + | some body => .ok body + | none => .error (.noSuchKey { bucket := bucket.id, key := under ++ [name] }), m) := + (GetObjectLive.lawful bucket under granted.le).get m name + +/-- A journal kept in a bucket, under a prefix. Using it asks for reading and writing there. -/ +def journal {role : Access Kind} (bucket : AWS.Bucket) (under : Path := ["journal"]) + [counts : Has role (Get bucket under)] [setsCount : Has role (Put bucket under)] + [reads : Has role (Get bucket (under ++ ["lines"]))] + [writes : Has role (Put bucket (under ++ ["lines"]))] : Cloud.Journal role := + journalOf ((GetObjectLive bucket under).build counts.le ⟨⟩) + ((PutObjectLive bucket under).build setsCount.le ⟨⟩) + ((GetObjectLive bucket (under ++ ["lines"])).build reads.le ⟨⟩) + ((PutObjectLive bucket (under ++ ["lines"])).build writes.le ⟨⟩) + +/-- It keeps the journal's law. -/ +theorem journal_lawful {role : Access Kind} (bucket : AWS.Bucket) (under : Path) + [Has role (Get bucket under)] [Has role (Put bucket under)] + [Has role (Get bucket (under ++ ["lines"]))] [Has role (Put bucket (under ++ ["lines"]))] : + (journal (role := role) bucket under).Lawful InMemory (lines bucket under) (Sound bucket under) := by + apply journalOf_lawful + · exact GetObjectLive.lawful _ _ _ + · exact PutObjectLive.lawful _ _ _ + · exact GetObjectLive.lawful _ _ _ + · exact PutObjectLive.lawful _ _ _ + +end S3 + +namespace SQS + +/-- Put a message on a queue. -/ +def sendMessage {role : Access Kind} (queue : AWS.Queue) (body : String) + [granted : Has role (Send queue)] : Run role Never Unit := + ((SendMessageLive queue).build granted.le ⟨⟩).call body + +/-- Sending a message does what the model says. -/ +theorem sendMessage_eval {role : Access Kind} (queue : AWS.Queue) (body : String) + [granted : Has role (Send queue)] (m : Memory) : + (sendMessage (role := role) queue body).eval InMemory m = (.ok (), m.send queue body) := + (SendMessageLive.lawful queue granted.le).send m body + +end SQS + +end Alchemy.AWS + +namespace Alchemy.AWS + +/-- A function's block has its role read off the calls in it. -/ +macro_rules + | `(Lambda.Function $id $props $body) => + `(Alchemy.AWS.Lambda.Function $id $props (granted% $body)) + +end Alchemy.AWS + +namespace Alchemy.AWS +open Alchemy.Cloud + +/-- The functions anyone on the internet can call: those with a public URL. -/ +def exposed (g : Graph Kind) : List String := + g.nodes.filterMap fun node => + match node.kind, node.props with + | .function, (props : FunctionProps) => if props.url then some node.id else none + | _, _ => none + +/-- Nothing that is exposed to the internet can do this. -/ +def nothingExposed (g : Graph Kind) (action : Doing Kind) : Prop := + ∀ detail host, host ∈ exposed g → g.can host (action.attempt detail) = false + +end Alchemy.AWS diff --git a/packages/alchemy-lean/Alchemy/Cloud/AWSLaws.lean b/packages/alchemy-lean/Alchemy/Cloud/AWSLaws.lean new file mode 100644 index 00000000000..2b2bc105724 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/AWSLaws.lean @@ -0,0 +1,203 @@ +import Alchemy.Cloud.AWS +import Alchemy.Cloud.Laws + +/-! +# What the AWS bindings promise + +Each binding has a law: what a call answers and what it does to the cloud. The +laws are stated against the model of S3 and SQS, and each binding's own +implementation is proved to keep its law. Code built on a binding is then +proved from the law, without looking inside the binding. +-/ + +namespace Alchemy.AWS +open Alchemy.Cloud + +variable {access : Access Kind} + +/-! ## The model: what a write does, as seen by a read -/ + +namespace Memory + +theorem object_put_self (m : Memory) (bucket : AWS.Bucket) (key : Path) (body : String) : + (m.put bucket key body).object bucket key = some body := by + simp only [object, put, List.find?_append] + rw [List.find?_eq_none.mpr] + · simp + · intro x mem + simp only [List.mem_filter] at mem + have differs := mem.2 + simp only [Bool.not_eq_true', Bool.and_eq_false_iff, beq_eq_false_iff_ne] at differs + intro same + simp only [Bool.and_eq_true, beq_iff_eq] at same + rcases differs with n | n + · exact n same.1 + · exact n same.2 + +theorem object_put_other (m : Memory) (bucket other : AWS.Bucket) (key otherKey : Path) (body : String) + (ne : ¬(other.id = bucket.id ∧ otherKey = key)) : + (m.put bucket key body).object other otherKey = m.object other otherKey := by + simp only [object, put, List.find?_append] + have last : ([(bucket.id, key, body)].find? fun x => x.1 == other.id && x.2.1 == otherKey) = none := by + simp only [List.find?_cons, List.find?_nil] + split + · next h => + simp only [Bool.and_eq_true, beq_iff_eq] at h + exact absurd ⟨h.1.symm, h.2.symm⟩ ne + · rfl + rw [last, Option.or_none, List.find?_filter] + congr 2 + funext x + obtain ⟨id, k, b⟩ := x + by_cases h : id = other.id ∧ k = otherKey + · obtain ⟨rfl, rfl⟩ := h + have keep : (!(other.id == bucket.id && k == key)) = true := by + simp only [Bool.not_eq_true', Bool.and_eq_false_iff, beq_eq_false_iff_ne] + by_cases same : other.id = bucket.id + · exact .inr fun h => ne ⟨same, h⟩ + · exact .inl same + simp [keep] + · have : (id == other.id && k == otherKey) = false := by simpa using h + simp [this] + +/-- A write leaves every queue as it was. -/ +@[simp] theorem queued_put (m : Memory) (bucket : AWS.Bucket) (key : Path) (body : String) + (queue : AWS.Queue) : (m.put bucket key body).queued queue = m.queued queue := rfl + +/-- A message sent goes to the back of its queue. -/ +theorem queued_send_self (m : Memory) (queue : AWS.Queue) (body : String) : + (m.send queue body).queued queue = m.queued queue ++ [body] := by + simp [queued, send] + +theorem queued_send_other (m : Memory) (queue other : AWS.Queue) (body : String) + (ne : other.id ≠ queue.id) : (m.send queue body).queued other = m.queued other := by + simp [queued, send, Ne.symm ne] + +/-- Sending leaves every object as it was. -/ +@[simp] theorem object_send (m : Memory) (queue : AWS.Queue) (body : String) (bucket : AWS.Bucket) + (key : Path) : (m.send queue body).object bucket key = m.object bucket key := rfl + +@[simp] theorem keys_send (m : Memory) (queue : AWS.Queue) (body : String) (bucket : AWS.Bucket) : + (m.send queue body).keys bucket = m.keys bucket := rfl + +/-- Receiving leaves every object as it was. -/ +@[simp] theorem object_receive (m : Memory) (queue : AWS.Queue) (bucket : AWS.Bucket) (key : Path) : + (m.receive queue).object bucket key = m.object bucket key := by + unfold receive + split <;> rfl + +end Memory + +/-! ## S3 -/ + +namespace S3 + +/-- Reading answers what the model holds at the key, and changes nothing. -/ +structure GetObject.Lawful {bucket : AWS.Bucket} {under : Path} + (client : GetObject.Client bucket under access) : Prop where + get : ∀ (m : Memory) (name : String), + (client.call name).eval InMemory m = + (match m.object bucket (under ++ [name]) with + | some body => .ok body + | none => .error (.noSuchKey { bucket := bucket.id, key := under ++ [name] }), m) + +/-- Writing answers, and leaves the model with the object at the key. -/ +structure PutObject.Lawful {bucket : AWS.Bucket} {under : Path} + (client : PutObject.Client bucket under access) : Prop where + put : ∀ (m : Memory) (name body : String), + (client.call name body).eval InMemory m = (.ok (), m.put bucket (under ++ [name]) body) + +/-- Listing answers the bucket's keys, and changes nothing. -/ +structure ListObjects.Lawful {bucket : AWS.Bucket} (client : ListObjects.Client bucket access) : + Prop where + list : ∀ (m : Memory), client.call.eval InMemory m = (.ok (m.keys bucket), m) + +theorem GetObjectLive.lawful (bucket : AWS.Bucket) (under : Path) + (le : (GetObjectLive bucket under).needs ≤ access) : + GetObject.Lawful ((GetObjectLive bucket under).build le ⟨⟩) where + get m name := by + cases found : m.object bucket (under ++ [name]) <;> + simp [GetObjectLive, Run.eval, Run.performUnder, bind, Run.bind, Run.exec, InMemory, simulate, + found, throw, pure] + +theorem PutObjectLive.lawful (bucket : AWS.Bucket) (under : Path) + (le : (PutObjectLive bucket under).needs ≤ access) : + PutObject.Lawful ((PutObjectLive bucket under).build le ⟨⟩) where + put _ _ _ := rfl + +theorem ListObjectsLive.lawful (bucket : AWS.Bucket) + (le : (ListObjectsLive bucket).needs ≤ access) : + ListObjects.Lawful ((ListObjectsLive bucket).build le ⟨⟩) where + list _ := rfl + +end S3 + +/-! ## SQS -/ + +namespace SQS + +/-- Sending answers, and leaves the model with the message sent. -/ +structure SendMessage.Lawful {queue : AWS.Queue} (client : SendMessage.Client queue access) : + Prop where + send : ∀ (m : Memory) (body : String), + (client.call body).eval InMemory m = (.ok (), m.send queue body) + +/-- Receiving answers the message at the front, if there is one, and takes it off. -/ +structure ReceiveMessage.Lawful {queue : AWS.Queue} (client : ReceiveMessage.Client queue access) : + Prop where + receive : ∀ (m : Memory), + client.call.eval InMemory m = (.ok (m.queued queue).head?, m.receive queue) + +theorem SendMessageLive.lawful (queue : AWS.Queue) + (le : (SendMessageLive queue).needs ≤ access) : + SendMessage.Lawful ((SendMessageLive queue).build le ⟨⟩) where + send _ _ := rfl + +theorem ReceiveMessageLive.lawful (queue : AWS.Queue) + (le : (ReceiveMessageLive queue).needs ≤ access) : + ReceiveMessage.Lawful ((ReceiveMessageLive queue).build le ⟨⟩) where + receive _ := rfl + +end SQS + +end Alchemy.AWS + +namespace Alchemy.AWS +open Alchemy.Cloud + +/-- +Code cannot change an object its role does not let it write. Whatever the code +is, whatever it is asked and whatever the cloud holds: if the role does not +permit writing a key, that key holds afterwards what it held before. +-/ +theorem Run.leaves {access : Access Kind} {ε α : Type} (run : Run access ε α) (m : Memory) + (bucket : AWS.Bucket) (key : Path) + (cannot : access.permits ⟨.bucket, bucket, BucketOp.put key⟩ = false) : + (run.exec InMemory m).state.object bucket key = m.object bucket key := by + induction run generalizing m with + | pure a => rfl + | fail e => rfl + | call ref c ok next ih => + rename_i k + show ((next (simulate ref c m).1).exec InMemory (simulate ref c m).2.1).state.object bucket key = _ + rw [ih] + cases k with + | function => exact nomatch c + | queue => cases c <;> simp [simulate] + | bucket => + cases c with + | getObject key' => rfl + | listObjects => rfl + | putObject key' body => + show (m.put ref key' body).object bucket key = _ + by_cases same : ref.id = bucket.id ∧ key' = key + · obtain ⟨sameId, rfl⟩ := same + have : ref = bucket := by cases ref; cases bucket; simp_all + subst this + have permitted : access.permits ⟨.bucket, ref, BucketOp.put key'⟩ = true := ok + rw [permitted] at cannot + cases cannot + · exact Memory.object_put_other m ref bucket key' key body + (fun h => same ⟨h.1.symm, h.2.symm⟩) + +end Alchemy.AWS diff --git a/packages/alchemy-lean/Alchemy/Cloud/Access.lean b/packages/alchemy-lean/Alchemy/Cloud/Access.lean new file mode 100644 index 00000000000..2166946d069 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Access.lean @@ -0,0 +1,150 @@ +/-! +# Access + +Access is a typed expression: an operation on a resource, or two expressions +together. What it means is the set of attempts it permits, and rules about +access are proved against that meaning. +-/ + +namespace Alchemy.Cloud + +/-- A resource of one kind, named by its logical id. -/ +structure Ref {K : Type} (kind : K) where + id : String +deriving DecidableEq, Repr, Inhabited + +/-- The kinds of resource a cloud has, and the operations each kind allows. -/ +class Kinds (K : Type) where + /-- The operations that can be granted on a resource of this kind. -/ + Op : K → Type + /-- Whether a grant of the first operation also allows the second. A grant always allows itself. -/ + covers : {k : K} → Op k → Op k → Bool := fun _ _ => false + decKind : DecidableEq K := by infer_instance + decOp : (k : K) → DecidableEq (Op k) := by infer_instance + +set_option warn.classDefReducibility false in +attribute [instance] Kinds.decKind Kinds.decOp + +variable {K : Type} [Kinds K] + +/-- One thing a principal might try: an operation on a resource. -/ +structure Attempt (K : Type) [Kinds K] where + kind : K + ref : Ref kind + op : Kinds.Op kind + +/-- An expression of access. -/ +inductive Access (K : Type) [Kinds K] where + /-- No access. -/ + | none + /-- One operation on one resource. -/ + | on {k : K} (ref : Ref k) (op : Kinds.Op k) + /-- Both. -/ + | and (a b : Access K) + +instance : Union (Access K) := ⟨.and⟩ +instance : EmptyCollection (Access K) := ⟨.none⟩ + +/-- Whether a grant of `op` on `ref` permits an attempt. -/ +def permitsOn {k : K} (ref : Ref k) (op : Kinds.Op k) (t : Attempt K) : Bool := + if h : t.kind = k then + ref.id == t.ref.id && (op == (h ▸ t.op) || Kinds.covers op (h ▸ t.op)) + else false + +/-- What an expression means: the attempts it permits. -/ +def Access.permits : Access K → Attempt K → Bool + | .none, _ => false + | .on ref op, t => permitsOn ref op t + | .and a b, t => a.permits t || b.permits t + +/-- The grants an expression is made of. -/ +def Access.atoms : Access K → List (Attempt K) + | .none => [] + | .on ref op => [⟨_, ref, op⟩] + | .and a b => a.atoms ++ b.atoms + +/-- Every grant in a list. -/ +def Access.all (grants : List (Access K)) : Access K := grants.foldr (· ∪ ·) ∅ + +@[simp] theorem Access.permits_none (t : Attempt K) : (∅ : Access K).permits t = false := rfl + +@[simp] theorem Access.permits_union (a b : Access K) (t : Attempt K) : + (a ∪ b).permits t = (a.permits t || b.permits t) := rfl + +@[simp] theorem Access.permits_on {k : K} (ref ref' : Ref k) (op op' : Kinds.Op k) : + (Access.on ref op).permits ⟨k, ref', op'⟩ + = (ref.id == ref'.id && (op == op' || Kinds.covers op op')) := by + simp [Access.permits, permitsOn] + +/-- A grant permits the very thing it grants. -/ +theorem Access.permits_self {k : K} (ref : Ref k) (op : Kinds.Op k) : + (Access.on ref op).permits ⟨k, ref, op⟩ = true := by + simp + +/-- An expression permits an attempt exactly when one of its grants does. -/ +theorem Access.permits_iff_atom (a : Access K) (t : Attempt K) : + a.permits t = true ↔ ∃ g ∈ a.atoms, permitsOn g.ref g.op t = true := by + induction a with + | none => simp [Access.permits, Access.atoms] + | on ref op => simp [Access.permits, Access.atoms] + | and a b iha ihb => + simp only [Access.permits, Access.atoms, Bool.or_eq_true, iha, ihb, List.mem_append] + constructor + · rintro (⟨g, m, h⟩ | ⟨g, m, h⟩) + · exact ⟨g, .inl m, h⟩ + · exact ⟨g, .inr m, h⟩ + · rintro ⟨g, m | m, h⟩ + · exact .inl ⟨g, m, h⟩ + · exact .inr ⟨g, m, h⟩ + +/-- `a ≤ b`: `a` grants no more than `b`. -/ +instance : LE (Access K) := ⟨fun a b => ∀ t, a.permits t = true → b.permits t = true⟩ + +theorem Access.le_refl (a : Access K) : a ≤ a := fun _ h => h + +theorem Access.le_trans {a b c : Access K} (ab : a ≤ b) (bc : b ≤ c) : a ≤ c := + fun t h => bc t (ab t h) + +theorem Access.le_union_left (a b : Access K) : a ≤ a ∪ b := fun t h => by simp [h] + +theorem Access.le_union_right (a b : Access K) : b ≤ a ∪ b := fun t h => by simp [h] + +theorem Access.union_le {a b c : Access K} (ac : a ≤ c) (bc : b ≤ c) : a ∪ b ≤ c := by + intro t h + simp only [Access.permits_union, Bool.or_eq_true] at h + exact h.elim (ac t) (bc t) + +theorem Access.none_le (a : Access K) : (∅ : Access K) ≤ a := fun t h => by simp at h + +/-- +`Has access need`: `access` includes `need`. Instances find it by the shape of +the expression, so it works for resources that are still variables. +-/ +class Has (access need : Access K) : Prop where + le : need ≤ access + +instance (a : Access K) : Has a a := ⟨Access.le_refl a⟩ + +instance (a b need : Access K) [h : Has a need] : Has (a ∪ b) need := + ⟨Access.le_trans h.le (Access.le_union_left a b)⟩ + +instance (a b need : Access K) [h : Has b need] : Has (a ∪ b) need := + ⟨Access.le_trans h.le (Access.le_union_right a b)⟩ + +instance (a m n : Access K) [hm : Has a m] [hn : Has a n] : Has a (m ∪ n) := + ⟨Access.union_le hm.le hn.le⟩ + +instance (a : Access K) : Has a ∅ := ⟨Access.none_le a⟩ + +/-- Access that includes a grant permits whatever that grant covers. -/ +theorem Has.permits_covered {access : Access K} {k : K} {ref : Ref k} {granted op : Kinds.Op k} + (h : Has access (.on ref granted)) (covered : (granted == op || Kinds.covers granted op) = true) : + access.permits ⟨k, ref, op⟩ = true := + h.le _ (by simp [covered]) + +/-- Access that includes a grant permits what it grants. -/ +theorem Has.permits {access : Access K} {k : K} {ref : Ref k} {op : Kinds.Op k} + (h : Has access (.on ref op)) : access.permits ⟨k, ref, op⟩ = true := + h.le _ (Access.permits_self ref op) + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Cloud/Api.lean b/packages/alchemy-lean/Alchemy/Cloud/Api.lean new file mode 100644 index 00000000000..e26591ec86e --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Api.lean @@ -0,0 +1,9 @@ +import Distilled.Core + +/-! +# Cloud APIs + +The effect type, service models and wire format come from distilled, so the +providers here are written against the same SDKs that are generated there. +Modules that use them `open Distilled`. +-/ diff --git a/packages/alchemy-lean/Alchemy/Cloud/Cli.lean b/packages/alchemy-lean/Alchemy/Cloud/Cli.lean new file mode 100644 index 00000000000..51501d1c3b7 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Cli.lean @@ -0,0 +1,104 @@ +import Alchemy.Cloud.Engine +import Alchemy.Cloud.Host + +/-! +# Running a stack from the command line + +A stack is a value, so its graph and its plan are computed from it. This +prints them: the same graph and the same plan the theorems are about. +-/ + +namespace Alchemy.Cloud +open Distilled (Api Model) + +variable {K : Type} [Cloud K] + +def Action.sign : Action → String + | .create => "+ create " + | .update => "~ update " + | .replace => "± replace" + | .noop => " no-op " + | .delete => "- delete " + +namespace Graph + +/-- The graph as text: each resource, what it needs, what it may do, and what it listens to. -/ +def report (g : Graph K) (grant : Attempt K → String) (why : Bool := false) : String := + String.intercalate "\n" <| g.order.filterMap fun id => (g.find id).map fun node => + let needs := if node.needs.isEmpty then "" else s!"\n needs {", ".intercalate node.needs}" + let grants := node.access.atoms.map fun atom => + let calls := if why then (g.why id atom).map fun call => s!"\n ← {call}" else [] + s!"\n may {grant atom}{String.join calls}" + let listens := match node.serve with + | some serve => serve.on.map fun sub => s!"\n consumes {sub.source.id}" + | none => [] + s!" {id}{needs}{String.join grants}{String.join listens}" + +end Graph + +/-- What changes on a resource: each setting whose value differs, before and after. -/ +def changes (before after : List (String × String)) : List String := + after.filterMap fun (name, value) => + match before.find? (·.1 == name) with + | some (_, was) => if was == value then none else some s!"{name}: {was} → {value}" + | none => some s!"{name}: {value}" + +/-- The plan as text, with what changes on each resource that is updated or replaced. -/ +def planReport (plan : List (String × Action)) (changed : String → List String := fun _ => []) : + String := + let lines := plan.map fun (id, action) => + let detail := if action == .update || action == .replace + then String.join ((changed id).map fun change => s!"\n {change}") else "" + s!" {action.sign} {id}{detail}" + let count := fun (a : Action) => (plan.filter (·.2 == a)).length + String.intercalate "\n" lines ++ + s!"\n\n {count .create} to create, {count .update} to update, {count .replace} to replace, " ++ + s!"{count .delete} to delete, {count .noop} unchanged" + +/-- +`graph [stage]` prints the stack's graph, and with `--why` the call that asks for each grant. `plan [stage]` prints the plan for a +fresh account, and `plan [stage] after [stage]` the plan for an account the +other stage was deployed to. Deploys are to the model of the cloud, in memory. +-/ +def Stack.cli {Out : Type} {api : Api} {m : Model api} (stack : Stack K Out) + (providers : Providers K api) (fresh : World K m) (grant : Attempt K → String) + (settings : (k : K) → Cloud.Props k → List (String × String)) + (args : List String) : IO UInt32 := do + let stageOf := fun (i : Nat) => (args.filter (· != "--why")).getD i "dev" + let build := fun (stage : String) => + match stack.build stage with + | .ok (_, graph) => + if graph.deployable then Except.ok graph + else .error s!"{stack.name} cannot be deployed: a resource is missing or resources wait on each other" + | .error why => .error s!"{stack.name} does not build: {why}" + match args with + | "graph" :: _ => + match build (stageOf 1) with + | .error why => IO.eprintln why; return 1 + | .ok graph => + IO.println s!"{stack.name} ({stageOf 1})\n\n{graph.report grant (args.contains "--why")}" + return 0 + | "plan" :: _ => + match build (stageOf 1) with + | .error why => IO.eprintln why; return 1 + | .ok graph => + let world ← match args with + | [_, _, "after", earlier] => + match build earlier with + | .ok before => pure (apply providers m before fresh).1 + | .error why => IO.eprintln why; return 1 + | _ => pure fresh + let from_ := match args with + | [_, _, "after", earlier] => s!" after {earlier}" + | _ => " on a fresh account" + let changed := fun (id : String) => + match world.state.row id, graph.find id with + | some row, some node => changes (settings row.kind row.props) (settings node.kind node.props) + | _, _ => [] + IO.println s!"{stack.name} ({stageOf 1}){from_}\n\n{planReport (plan providers graph world.state) changed}" + return 0 + | _ => + IO.println s!"usage: graph [stage] | plan [stage] | plan [stage] after [stage]" + return 1 + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Cloud/Cloudflare.lean b/packages/alchemy-lean/Alchemy/Cloud/Cloudflare.lean new file mode 100644 index 00000000000..c6cb93931c9 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Cloudflare.lean @@ -0,0 +1,403 @@ +import Alchemy.Cloud.Host +import Alchemy.Cloud.Infer +import Alchemy.Cloud.Tactics +import Alchemy.Cloud.Laws +import Alchemy.Cloud.Hosted + +/-! +# A small Cloudflare + +Workers, R2 buckets and Queues. A Worker is written as a `do` block: a queue +consumer is a step, and it ends with what the Worker serves, a `fetch` handler +and typed methods other Workers can call. Its bindings are read off its calls. +-/ + +namespace Alchemy.Cloudflare +open Alchemy.Cloud + +inductive Kind where + | bucket + | queue + | worker +deriving DecidableEq, Repr + +/-! ## Access -/ + +inductive BucketOp where + | read + | write +deriving DecidableEq, Repr + +inductive QueueOp where + | send +deriving DecidableEq, Repr + +inductive WorkerOp where + | call +deriving DecidableEq, Repr + +abbrev Op : Kind → Type + | .bucket => BucketOp + | .queue => QueueOp + | .worker => WorkerOp + +instance : (k : Kind) → DecidableEq (Op k) + | .bucket => inferInstanceAs (DecidableEq BucketOp) + | .queue => inferInstanceAs (DecidableEq QueueOp) + | .worker => inferInstanceAs (DecidableEq WorkerOp) + +instance : Kinds Kind where + Op := Op + +/-! ## Configuration, calls and events -/ + +structure BucketProps where +deriving DecidableEq, Repr + +structure QueueProps where + /-- Messages delivered to a consumer at once. -/ + batchSize : Nat := 10 +deriving DecidableEq, Repr + +structure WorkerProps where + compatibilityDate : String := "2026-01-01" +deriving DecidableEq, Repr + +abbrev Props : Kind → Type + | .bucket => BucketProps + | .queue => QueueProps + | .worker => WorkerProps + +inductive BucketCall where + | get (key : String) + | put (key body : String) + | list + +inductive QueueCall where + | send (body : String) + +inductive WorkerCall where + /-- A method of another Worker, with its arguments, as text. -/ + | rpc (method : String) + +abbrev Call : Kind → Type + | .bucket => BucketCall + | .queue => QueueCall + | .worker => WorkerCall + +abbrev Reply : {k : Kind} → Call k → Type + | .bucket, .get _ => Option String + | .bucket, .put .. => Unit + | .bucket, .list => List String + | .queue, .send _ => Unit + | .worker, .rpc _ => Option String + +def needs : {k : Kind} → Call k → Op k + | .bucket, .get _ => .read + | .bucket, .put .. => .write + | .bucket, .list => .read + | .queue, .send _ => .send + | .worker, .rpc _ => .call + +structure Request where + method : String := "GET" + path : String := "/" + body : String := "" +deriving DecidableEq, Repr + +structure Response where + status : Nat := 200 + body : String := "" +deriving DecidableEq, Repr + +/-- What reaches a Worker: a request over HTTP, or a call from another Worker. -/ +inductive Incoming where + | fetch (request : Request) + | rpc (method : String) + +inductive Outgoing where + | http (response : Response) + | value (reply : String) + | unknownMethod +deriving DecidableEq, Repr + +instance : Cloud Kind where + Props := Props + Call := Call + Reply := Reply + needs := needs + /- A queue tells its consumers each message. -/ + Event := fun + | .queue => String + | _ => Empty + Request := fun + | .worker => Incoming + | _ => Empty + Response := fun + | .worker => Outgoing + | _ => Empty + +/-! ## Resources -/ + +abbrev Bucket := Ref Kind.bucket +abbrev Queue := Ref Kind.queue + +namespace R2 + +def Bucket (id : String) (props : BucketProps := {}) : Construct Kind Cloudflare.Bucket := + resource Kind.bucket id props + +end R2 + +namespace Queues + +def Queue (id : String) (props : QueueProps := {}) : Construct Kind Cloudflare.Queue := + resource Kind.queue id props + +end Queues + +/-! ## Consumers -/ + +namespace Queues + +/-- +Consume a queue: run this for each message. A step of the Worker's block, so the +Worker is registered as the queue's consumer when the stack is built. +-/ +def consume {role : Access Kind} {ε : Type} [Repr ε] (queue : Cloudflare.Queue) + (handle : String → Run role ε Unit) : Host role Unit := + Host.listen { + kind := .queue + source := queue + handle := fun (message : String) => (handle message).mapError reprStr } + +end Queues + +/-! ## Workers -/ + +/-- What a Worker offers other Workers: its methods, and what each answers. -/ +structure Rpc where + Method : Type + Reply : Method → Type + [method : Text Method] + reply : (c : Method) → Text (Reply c) := by intro c; cases c <;> exact inferInstance + +/-- No methods. -/ +def Rpc.none : Rpc where + Method := Empty + Reply := fun _ => Empty + method := { write := nofun, read := fun _ => Option.none } + reply := fun c => nomatch c + +/-- A Worker, by the methods it offers. -/ +structure Worker (rpc : Rpc) where + ref : Ref Kind.worker + +/-- What a Worker serves. -/ +structure Handlers (rpc : Rpc) (role : Access Kind) where + fetch : Request → Run role Never Response := fun _ => pure { status := 404 } + rpc : (c : rpc.Method) → Run role Never (rpc.Reply c) := by intro c; exact nomatch c + +namespace Workers + +/-- +A Worker. Its block binds what it uses, registers what it consumes, and ends +with what it serves. +-/ +def Worker (id : String) (props : WorkerProps) (rpc : Rpc := .none) + (body : {role : Access Kind} → Host role (Handlers rpc role)) : + Construct Kind (Cloudflare.Worker rpc) := do + let ref ← hostOf Kind.worker id props do + let handlers ← body + return fun + | Incoming.fetch request => return Outgoing.http (← handlers.fetch request) + | Incoming.rpc text => + match rpc.method.read text with + | some c => return Outgoing.value ((rpc.reply c).write (← handlers.rpc c)) + | none => return Outgoing.unknownMethod + return ⟨ref⟩ + +/-- How a call to another Worker can fail. -/ +inductive RpcError where + | unknownMethod + | unreadable (reply : String) +deriving DecidableEq, Repr + +end Workers + +/-! ## Operations called directly: the call is what asks for the binding -/ + +namespace R2 + +/-- Read an object. -/ +def get {role : Access Kind} (bucket : Cloudflare.Bucket) (key : String) + [granted : Has role (.on bucket BucketOp.read)] : Run role Never (Option String) := + Run.perform bucket (BucketCall.get key) granted + +/-- The keys of a bucket. -/ +def list {role : Access Kind} (bucket : Cloudflare.Bucket) + [granted : Has role (.on bucket BucketOp.read)] : Run role Never (List String) := + Run.perform bucket BucketCall.list granted + +/-- Write an object. -/ +def put {role : Access Kind} (bucket : Cloudflare.Bucket) (key body : String) + [granted : Has role (.on bucket BucketOp.write)] : Run role Never Unit := + Run.perform bucket (BucketCall.put key body) granted + +/-- Reading a bucket. -/ +abbrev reading (bucket : Cloudflare.Bucket) : Doing Kind := ⟨Unit, fun _ => ⟨.bucket, bucket, BucketOp.read⟩⟩ + +/-- Writing a bucket. -/ +abbrev writing (bucket : Cloudflare.Bucket) : Doing Kind := ⟨Unit, fun _ => ⟨.bucket, bucket, BucketOp.write⟩⟩ + +end R2 + +namespace Queues + +/-- Put a message on a queue. -/ +def send {role : Access Kind} (queue : Cloudflare.Queue) (body : String) + [granted : Has role (.on queue QueueOp.send)] : Run role Never Unit := + Run.perform queue (QueueCall.send body) granted + +/-- Putting messages on a queue. -/ +abbrev sending (queue : Cloudflare.Queue) : Doing Kind := ⟨Unit, fun _ => ⟨.queue, queue, QueueOp.send⟩⟩ + +end Queues + +namespace Workers + +/-- Call a method of another Worker. -/ +def call {role : Access Kind} {rpc : Rpc} (worker : Cloudflare.Worker rpc) (c : rpc.Method) + [granted : Has role (.on worker.ref WorkerOp.call)] : Run role RpcError (rpc.Reply c) := do + match ← Run.perform worker.ref (WorkerCall.rpc (rpc.method.write c)) granted with + | none => .fail .unknownMethod + | some text => + match (rpc.reply c).read text with + | some reply => pure reply + | none => .fail (.unreadable text) + +/-- Calling a Worker's methods. -/ +abbrev calling {rpc : Rpc} (worker : Cloudflare.Worker rpc) : Doing Kind := + ⟨Unit, fun _ => ⟨.worker, worker.ref, WorkerOp.call⟩⟩ + +end Workers + +/-- A Worker's block has its bindings read off the calls in it. -/ +macro_rules + | `(Workers.Worker $id $props $rpc $body) => + `(Alchemy.Cloudflare.Workers.Worker $id $props $rpc (granted% $body)) + +/-! ## In memory -/ + +structure Memory where + objects : List (String × String × String) := [] + /-- Every message ever put on a queue. -/ + sent : List (String × String) := [] +deriving DecidableEq, Repr + +namespace Memory + +def object (m : Memory) (bucket : Cloudflare.Bucket) (key : String) : Option String := + (m.objects.find? fun (id, k, _) => id == bucket.id && k == key).map (·.2.2) + +def keys (m : Memory) (bucket : Cloudflare.Bucket) : List String := + (m.objects.filter (·.1 == bucket.id)).map (·.2.1) + +end Memory + +/-- +What each call does. A call to a Worker runs that Worker's method, to a depth: +a Worker that calls itself for ever is cut off. +-/ +def simulate (g : Graph Kind) : + Nat → {k : Kind} → Ref k → (c : Call k) → Memory → Reply c × Memory × List (Cloud.Emitted Kind) + | depth, k, ref, c, m => + match k, ref, c with + | .bucket, bucket, .get key => (m.object bucket key, m, []) + | .bucket, bucket, .put key body => + ((), { m with + objects := (m.objects.filter fun (id, k, _) => !(id == bucket.id && k == key)) + ++ [(bucket.id, key, body)] }, []) + | .bucket, bucket, .list => (m.keys bucket, m, []) + | .queue, queue, .send body => + ((), { m with sent := m.sent ++ [(queue.id, body)] }, + [(⟨Kind.queue, queue, body⟩ : Cloud.Emitted Kind)]) + | .worker, worker, .rpc method => + match depth with + | 0 => (none, m, []) + | depth + 1 => + match g.handler worker (Incoming.rpc method) with + | none => (none, m, []) + | some ⟨_, run⟩ => + let out := run.exec { State := Memory, init := {}, call := simulate g depth } m + (match out.result with + | .ok (Outgoing.value reply) => some reply + | _ => none, out.state, out.events) + +/-- Cloudflare, in memory, running the Workers of a graph. -/ +abbrev InMemory (g : Graph Kind) (depth : Nat := 8) : Sim Kind where + State := Memory + init := {} + call := simulate g depth + +/-! ## What the operations do + +Each operation, against the model: what it answers and what it leaves. +-/ + +/-- What was just written at a key is what the bucket holds there. -/ +theorem Memory.object_written (m : Memory) (bucket : Cloudflare.Bucket) (key body : String) : + ({ m with + objects := (m.objects.filter fun (id, k, _) => !(id == bucket.id && k == key)) + ++ [(bucket.id, key, body)] } : Memory).object bucket key = some body := by + simp only [Memory.object, List.find?_append] + rw [List.find?_eq_none.mpr] + · simp + · intro x mem + simp only [List.mem_filter] at mem + have differs := mem.2 + simp only [Bool.not_eq_true', Bool.and_eq_false_iff, beq_eq_false_iff_ne] at differs + intro same + simp only [Bool.and_eq_true, beq_iff_eq] at same + rcases differs with n | n + · exact n same.1 + · exact n same.2 + +section Laws +variable {role : Access Kind} (g : Graph Kind) (depth : Nat) + +/-- Reading answers what the bucket holds at the key, and changes nothing. -/ +theorem R2.get_eval (bucket : Cloudflare.Bucket) (key : String) + [Has role (.on bucket BucketOp.read)] (m : Memory) : + (R2.get (role := role) bucket key).eval (InMemory g depth) m = (.ok (m.object bucket key), m) := by + cases depth <;> rfl + +/-- Listing answers the bucket's keys, and changes nothing. -/ +theorem R2.list_eval (bucket : Cloudflare.Bucket) [Has role (.on bucket BucketOp.read)] + (m : Memory) : + (R2.list (role := role) bucket).eval (InMemory g depth) m = (.ok (m.keys bucket), m) := by + cases depth <;> rfl + +/-- Writing leaves the object at the key, replacing whatever was there. -/ +theorem R2.put_eval (bucket : Cloudflare.Bucket) (key body : String) + [Has role (.on bucket BucketOp.write)] (m : Memory) : + (R2.put (role := role) bucket key body).eval (InMemory g depth) m + = (.ok (), { m with + objects := (m.objects.filter fun (id, k, _) => !(id == bucket.id && k == key)) + ++ [(bucket.id, key, body)] }) := by + cases depth <;> rfl + +/-- Sending records the message, and touches no object. -/ +theorem Queues.send_eval (queue : Cloudflare.Queue) (body : String) + [Has role (.on queue QueueOp.send)] (m : Memory) : + (Queues.send (role := role) queue body).eval (InMemory g depth) m + = (.ok (), { m with sent := m.sent ++ [(queue.id, body)] }) := by + cases depth <;> rfl + +end Laws + +/-- A test's expectation: the Worker answers exactly this over HTTP. -/ +def responds (expected : Response) : Cloud.Response Kind.worker → Bool := + fun (got : Outgoing) => got == .http expected + +end Alchemy.Cloudflare diff --git a/packages/alchemy-lean/Alchemy/Cloud/CloudflareControl.lean b/packages/alchemy-lean/Alchemy/Cloud/CloudflareControl.lean new file mode 100644 index 00000000000..ed0c2cb026f --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/CloudflareControl.lean @@ -0,0 +1,195 @@ +import Alchemy.Cloud.Cloudflare +import Alchemy.Cloud.Engine +import Alchemy.Cloud.Cli + +/-! +# Cloudflare's control plane + +Enough of it to plan and apply a stack of buckets, queues and Workers: each is +put, which creates it or brings it to the configuration asked for, and deleted. +A bucket's name may be another account's, and a queue with a consumer cannot be +deleted. The providers are proved lawful against this model, failures included, +so the engine's guarantees hold of a Cloudflare stack as they do of an AWS one. +-/ + +namespace Alchemy.Cloudflare.Control +open Alchemy.Cloud +open Distilled (Eff) + +/-- The operations: put a resource of a kind, or delete one. -/ +inductive Op where + | put (kind : Kind) + | delete (kind : Kind) +deriving DecidableEq, Repr + +/-- Why a bucket could not be put. -/ +inductive PutBucketError where + /-- Another account has a bucket of this name. -/ + | nameTaken +deriving DecidableEq, Repr + +/-- Why a resource could not be deleted. -/ +inductive DeleteError where + /-- There is no such resource. -/ + | notFound + /-- A queue with a consumer cannot be deleted. -/ + | queueHasConsumer +deriving DecidableEq, Repr + +abbrev Error : Op → Type + | .put .bucket => PutBucketError + | .put _ => Empty + | .delete _ => DeleteError + +/-- The control plane: every operation, with what it can fail with. -/ +abbrev Api : Distilled.Api where + Op := Op + In := fun _ => Slot + Out := fun _ => Unit + Err := Error + +/-- An account: which resources exist, and what stands in the way of some operations. -/ +structure Account where + exists_ : Physical Kind → Bool := fun _ => false + /-- Bucket names another account has. -/ + taken : Slot → Bool := fun _ => false + /-- Queues that still have a consumer attached. -/ + consumed : Slot → Bool := fun _ => false + +def Account.created (a : Account) (kind : Kind) (slot : Slot) : Account := + { a with exists_ := fun y => y == ⟨kind, slot.id, slot.generation⟩ || a.exists_ y } + +def Account.removed (a : Account) (kind : Kind) (slot : Slot) : Account := + { a with exists_ := fun y => !(y == ⟨kind, slot.id, slot.generation⟩) && a.exists_ y } + +def step : (op : Op) → Slot → Account → Except (Error op) Unit × Account + | .put .bucket, slot, a => + if a.taken slot then (.error .nameTaken, a) else (.ok (), a.created .bucket slot) + | .put .queue, slot, a => (.ok (), a.created .queue slot) + | .put .worker, slot, a => (.ok (), a.created .worker slot) + | .delete kind, slot, a => + if !a.exists_ ⟨kind, slot.id, slot.generation⟩ then (.error .notFound, a) + else if kind == .queue && a.consumed slot then (.error .queueHasConsumer, a) + else (.ok (), a.removed kind slot) + +/-- Cloudflare, as these providers need to understand it. -/ +abbrev Service : Distilled.Model Api where + State := Account + step := step + +abbrev Calls (α : Type) := Eff Api Failure α + +/-- Put a resource. Only a bucket can be refused: its name may be another account's. -/ +def reconcile : (kind : Kind) → Slot → Calls Slot + | .bucket, slot => do + match ← Eff.ask (api := Api) (.put .bucket) slot with + | .ok () => return slot + | .error .nameTaken => throw "the bucket name is taken by another account" + | .queue, slot => do + match ← Eff.ask (api := Api) (.put .queue) slot with + | .ok () => return slot + | .worker, slot => do + match ← Eff.ask (api := Api) (.put .worker) slot with + | .ok () => return slot + +/-- Delete a resource. One that is already gone is deleted; a queue still consumed is not. -/ +def delete (kind : Kind) (slot : Slot) : Calls Unit := do + match ← Eff.ask (api := Api) (.delete kind) slot with + | .ok () | .error .notFound => return + | .error .queueHasConsumer => throw "the queue still has a consumer" + +/-- Any of the three kinds: everything about it can be changed in place. -/ +def provider (kind : Kind) : Provider Api (Cloud.Props kind) Slot where + diff old new := + match kind, old, new with + | .bucket, (old : BucketProps), (new : BucketProps) => if old = new then .noop else .update + | .queue, (old : QueueProps), (new : QueueProps) => if old = new then .noop else .update + | .worker, (old : WorkerProps), (new : WorkerProps) => if old = new then .noop else .update + reconcile slot _ := reconcile kind slot + delete slot := delete kind slot + +def providers : Providers Kind Api where + Attrs := fun _ => Slot + provider := provider + +/-- What putting a resource does to an account. -/ +theorem reconcile_run (kind : Kind) (slot : Slot) (a : Account) : + (reconcile kind slot).run Service a = + if kind = .bucket ∧ a.taken slot = true + then (.error "the bucket name is taken by another account", a) + else (.ok slot, a.created kind slot) := by + cases kind + · cases taken : a.taken slot <;> + simp [reconcile, Eff.ask, Bind.bind, Eff.bind, Eff.run, step, taken, Pure.pure, throw] + · simp [reconcile, Eff.ask, Bind.bind, Eff.bind, Eff.run, step, Pure.pure] + · simp [reconcile, Eff.ask, Bind.bind, Eff.bind, Eff.run, step, Pure.pure] + +/-- What deleting a resource does to an account. -/ +theorem delete_run (kind : Kind) (slot : Slot) (a : Account) : + (delete kind slot).run Service a = + if a.exists_ ⟨kind, slot.id, slot.generation⟩ = false then (.ok (), a) + else if kind = .queue ∧ a.consumed slot = true + then (.error "the queue still has a consumer", a) + else (.ok (), a.removed kind slot) := by + cases there : a.exists_ ⟨kind, slot.id, slot.generation⟩ + · simp [delete, Eff.ask, Bind.bind, Eff.bind, Eff.run, step, there, Pure.pure] + · cases kind <;> cases busy : a.consumed slot <;> + simp [delete, Eff.ask, Bind.bind, Eff.bind, Eff.run, step, there, busy, Pure.pure, throw] + +/-- These providers meet what the engine relies on, against this model of Cloudflare. -/ +def lawful : Lawful providers Service where + present := fun y a => a.exists_ y + diff_self := by intro k props; cases k <;> simp [providers, provider] + reconcile_ok := by + intro k slot props s attrs s' ok + simp only [providers, provider, reconcile_run] at ok + split at ok + · cases ok + · cases ok; simp [Account.created] + reconcile_frame := by + intro k slot props s y ne + simp only [providers, provider, reconcile_run] + split + · rfl + · simp [Account.created, ne] + delete_ok := by + intro k slot s s' ok + simp only [providers, provider, delete_run] at ok + split at ok + · cases ok; assumption + · split at ok + · cases ok + · cases ok; simp [Account.removed] + delete_frame := by + intro k slot s y ne + simp only [providers, provider, delete_run] + split + · rfl + · split + · rfl + · simp [Account.removed, ne] + +end Alchemy.Cloudflare.Control + +namespace Alchemy.Cloudflare +open Alchemy.Cloud + +/-- A binding, in words. -/ +def describeGrant : Attempt Kind → String + | ⟨.bucket, bucket, .read⟩ => s!"read {bucket.id}" + | ⟨.bucket, bucket, .write⟩ => s!"write {bucket.id}" + | ⟨.queue, queue, .send⟩ => s!"send to {queue.id}" + | ⟨.worker, worker, .call⟩ => s!"call {worker.id}" + +/-- A resource's settings, by name. -/ +def describeSettings : (k : Kind) → Cloud.Props k → List (String × String) + | .bucket, _ => [] + | .queue, (props : QueueProps) => [("batchSize", toString props.batchSize)] + | .worker, (props : WorkerProps) => [("compatibilityDate", props.compatibilityDate)] + +/-- Run a stack from the command line, against an empty model of a Cloudflare account. -/ +def cli {Out : Type} (stack : Stack Kind Out) (args : List String) : IO UInt32 := + stack.cli Control.providers (⟨.empty, {}⟩ : Cloud.World Kind Control.Service) describeGrant + describeSettings args + +end Alchemy.Cloudflare diff --git a/packages/alchemy-lean/Alchemy/Cloud/Effect.lean b/packages/alchemy-lean/Alchemy/Cloud/Effect.lean new file mode 100644 index 00000000000..489916cd0ea --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Effect.lean @@ -0,0 +1,110 @@ +import Alchemy.Cloud.Run + +/-! +# Effect + +`Effect R ε α` is code that needs the services `R`, may fail with `ε`, and +returns `α`. It does not name the access it runs with: a `Layer` supplies the +services, and with them the access they need. +-/ + +namespace Alchemy.Cloud + +variable {K : Type} [Cloud K] + +/-- +A service is a type that depends on the access its code runs with: a structure +whose fields are functions into `Run access`. +-/ +abbrev Service (K : Type) [Cloud K] := Access K → Type + +/-- The error of code that cannot fail. -/ +abbrev Never := Empty + +instance : Repr Never := ⟨fun e _ => nomatch e⟩ + +/-- No services. -/ +structure Nothing (access : Access K) : Type where + +/-- Two sets of services together. -/ +structure Both (R T : Service K) (access : Access K) : Type where + left : R access + right : T access + +/-- `Uses R S`: the services `R` include the service `S`. Found by the shape of `R`. -/ +class Uses (R S : Service K) where + get : {access : Access K} → R access → S access + +instance (S : Service K) : Uses S S := ⟨id⟩ + +instance (R T S : Service K) [Uses R S] : Uses (Both R T) S := ⟨fun both => Uses.get both.left⟩ + +instance (R T S : Service K) [Uses T S] : Uses (Both R T) S := ⟨fun both => Uses.get both.right⟩ + +/-- Code that needs the services `R`, may fail with `ε`, and returns `α`. -/ +structure Effect (R : Service K) (ε α : Type) where + /-- Run with these services, under whatever access they were built for. -/ + run : {access : Access K} → R access → Run access ε α + +namespace Effect + +variable {R T : Service K} {ε ε' α β : Type} + +instance : Monad (Effect R ε) where + pure a := ⟨fun _ => .pure a⟩ + bind effect f := ⟨fun services => (effect.run services).bind fun a => (f a).run services⟩ + +instance : MonadExcept ε (Effect R ε) where + throw e := ⟨fun _ => .fail e⟩ + tryCatch effect handle := + ⟨fun services => (effect.run services).recover fun e => (handle e).run services⟩ + +/-- Recover from a failure, into code that may fail another way. -/ +def recover (effect : Effect R ε α) (handle : ε → Effect R ε' α) : Effect R ε' α := + ⟨fun services => (effect.run services).recover fun e => (handle e).run services⟩ + +/-- The outcome as a value, so a failure can be matched on. -/ +def result (effect : Effect R ε α) : Effect R ε' (Except ε α) := + ⟨fun services => (effect.run services).result⟩ + +def mapError (f : ε → ε') (effect : Effect R ε α) : Effect R ε' α := + ⟨fun services => (effect.run services).mapError f⟩ + +/-- +`Raises ε e`: the errors `ε` include the error `e`. An error is a data type: a +structure, or an inductive with a case for each way to fail. A sum of errors +says how each of its parts goes into it. +-/ +class Raises (ε : Type) (e : semiOutParam Type) where + raise : e → ε + +/-- Every error includes itself. -/ +instance (e : Type) : Raises e e := ⟨id⟩ + +/-- Code that cannot fail runs where anything can. -/ +instance (ε : Type) : Raises ε Never := ⟨fun e => nomatch e⟩ + +/-- Code that fails with `e`, where the errors include `e`. -/ +def raising {e : Type} [Raises ε e] (effect : Effect R e α) : Effect R ε α := + effect.mapError Raises.raise + +/-- Fail with one of the errors `ε` includes. -/ +def raise {e : Type} [Raises ε e] (error : e) : Effect R ε α := ⟨fun _ => .fail (Raises.raise error)⟩ + +/-- +Call a service: `use JobStorage (·.get id)`. The call's error is a data type +`e`, and the result fails with any errors that include it. +-/ +def use (S : Service K) [Uses R S] {e : Type} [Raises ε e] + (f : {access : Access K} → S access → Run access e α) : Effect R ε α := + ⟨fun services => (f (Uses.get services)).mapError Raises.raise⟩ + +/-- Run code that needs fewer services where more are available. -/ +def widen [Uses T R] (effect : Effect R ε α) : Effect T ε α := + ⟨fun services => effect.run (Uses.get services)⟩ + +end Effect + +export Effect (use raise Raises) + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Cloud/Engine.lean b/packages/alchemy-lean/Alchemy/Cloud/Engine.lean new file mode 100644 index 00000000000..462c34eac06 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Engine.lean @@ -0,0 +1,677 @@ +import Alchemy.Cloud.Provider + +/-! +# Plan and apply + +The engine keeps a row of state for each resource and drives providers until +the cloud matches a graph. It writes what it is about to do before it does it, +so that a failure or a crash at any point leaves nothing in the cloud that the +state has lost track of. That is proved here for every provider that is +`Lawful`, not tested case by case. +-/ + +namespace Alchemy.Cloud +open Distilled (Api Eff Model) + +variable {K : Type} [Cloud K] {api : Api} + +/-- Where a resource is in its life. Every status but `ready` is a step that has begun and not finished. -/ +inductive Status where + | creating + | updating + | replacing + | ready + | deleting +deriving DecidableEq, Repr + +/-- What the engine remembers about one resource. -/ +structure Row (K : Type) [Cloud K] where + kind : K + id : String + /-- Which instance of the resource is the current one. -/ + generation : Nat + status : Status + /-- The configuration it has, or is being brought to. -/ + props : Cloud.Props kind + /-- Instances it replaced, still to be removed. -/ + old : List (Physical K) := [] + +namespace Row + +def current (r : Row K) : Physical K := ⟨r.kind, r.id, r.generation⟩ + +/-- A row tracks its current instance and the ones it replaced. -/ +def tracks (r : Row K) (y : Physical K) : Prop := y = r.current ∨ y ∈ r.old + +/-- The row for a node of the graph. -/ +def of (node : Node K) (generation : Nat) (status : Status) (old : List (Physical K)) : Row K := + { kind := node.kind, id := node.id, generation, status, props := node.props, old } + +end Row + +/-- The engine's memory: a row for each resource it manages. -/ +structure State (K : Type) [Cloud K] where + row : String → Option (Row K) + /-- The ids that may have a row. -/ + ids : List String + listed : ∀ id, row id ≠ none → id ∈ ids + +namespace State + +def empty : State K := ⟨fun _ => none, [], fun _ h => absurd rfl h⟩ + +def set (s : State K) (id : String) (r : Row K) : State K where + row := fun i => if i = id then some r else s.row i + ids := id :: s.ids + listed := fun i h => by + by_cases eq : i = id + · simp [eq] + · simp only [eq, ite_false] at h + exact List.mem_cons_of_mem _ (s.listed i h) + +def erase (s : State K) (id : String) : State K where + row := fun i => if i = id then none else s.row i + ids := s.ids + listed := fun i h => by + by_cases eq : i = id + · simp [eq] at h + · simp only [eq, ite_false] at h + exact s.listed i h + +/-- The state tracks a physical resource when some row does. -/ +def tracks (s : State K) (y : Physical K) : Prop := ∃ id r, s.row id = some r ∧ r.tracks y + +@[simp] theorem set_row_self (s : State K) (id : String) (r : Row K) : (s.set id r).row id = some r := by + simp [set] + +theorem set_row_of_ne (s : State K) {id other : String} (r : Row K) (ne : other ≠ id) : + (s.set id r).row other = s.row other := by + simp [set, ne] + +/-- Replacing a row by one that tracks at least as much loses track of nothing. -/ +theorem tracks_set {s : State K} {id : String} {r' : Row K} + (keeps : ∀ r, s.row id = some r → ∀ y, r.tracks y → r'.tracks y) + {y : Physical K} (h : s.tracks y) : (s.set id r').tracks y := by + obtain ⟨i, r, at_, t⟩ := h + by_cases eq : i = id + · subst eq; exact ⟨i, r', by simp, keeps r at_ y t⟩ + · exact ⟨i, r, by rw [set_row_of_ne _ _ eq]; exact at_, t⟩ + +end State + +/-- The engine's memory and the cloud it manages. -/ +structure World (K : Type) [Cloud K] {api : Api} (m : Model api) where + state : State K + cloud : m.State + +variable {m : Model api} + +/-- What a provider's reconcile of a row does to the cloud. -/ +def reconciled (ps : Providers K api) (m : Model api) (r : Row K) (cloud : m.State) : + Except Failure (ps.Attrs r.kind) × m.State := + ((ps.provider r.kind).reconcile r.current.slot r.props).run m cloud + +/-- What a provider's delete of a physical resource does to the cloud. -/ +def deleted (ps : Providers K api) (m : Model api) (y : Physical K) (cloud : m.State) : + Except Failure Unit × m.State := + ((ps.provider y.kind).delete y.slot).run m cloud + +/-- +Everything the engine may do. Each step may be the last: the engine can fail or +be killed after any of them. + +A reconcile or a delete changes the cloud whether or not the state is written +afterwards, which is what a crash between the two looks like. +-/ +inductive Step (ps : Providers K api) (m : Model api) : World K m → World K m → Prop + /-- Write state that still tracks everything it tracked. -/ + | write {w : World K m} {s' : State K} (covers : ∀ y, w.state.tracks y → s'.tracks y) : + Step ps m w ⟨s', w.cloud⟩ + /-- Reconcile a resource the state has a row for. -/ + | reconcile {w : World K m} {s' : State K} (id : String) (r : Row K) + (has : w.state.row id = some r) (covers : ∀ y, w.state.tracks y → s'.tracks y) : + Step ps m w ⟨s', (reconciled ps m r w.cloud).2⟩ + /-- Delete a resource the state tracks, and forget it only if the delete succeeded. -/ + | delete {w : World K m} {s' : State K} (y : Physical K) (tracked : w.state.tracks y) + (covers : ∀ z, w.state.tracks z → + z ≠ y ∨ (deleted ps m y w.cloud).1 ≠ .ok () → s'.tracks z) : + Step ps m w ⟨s', (deleted ps m y w.cloud).2⟩ + +/-- Any number of steps. -/ +inductive Steps (ps : Providers K api) (m : Model api) : World K m → World K m → Prop + | done (w : World K m) : Steps ps m w w + | next {a b c : World K m} : Steps ps m a b → Step ps m b c → Steps ps m a c + +theorem Steps.trans {ps : Providers K api} {a b c : World K m} + (ab : Steps ps m a b) (bc : Steps ps m b c) : Steps ps m a c := by + induction bc with + | done => exact ab + | next _ step ih => exact .next ih step + +/-- Nothing is lost: every resource that exists in the cloud is tracked by the state. -/ +def Tracked {ps : Providers K api} (law : Lawful ps m) (w : World K m) : Prop := + ∀ y, law.present y w.cloud = true → w.state.tracks y + +/-- No step loses track of a resource, whether the provider succeeds or fails. -/ +theorem Step.tracked {ps : Providers K api} (law : Lawful ps m) {w w' : World K m} + (step : Step ps m w w') (h : Tracked law w) : Tracked law w' := by + cases step with + | write covers => exact fun y present => covers y (h y present) + | reconcile id r has covers => + intro y present + by_cases eq : y = r.current + · exact covers y ⟨id, r, has, .inl eq⟩ + · have frame := law.reconcile_frame r.kind r.current.slot r.props w.cloud y eq + exact covers y (h y (by simpa [reconciled, frame] using present)) + | delete y₀ tracked covers => + intro y present + by_cases eq : y = y₀ + · subst eq + by_cases ok : (deleted ps m y w.cloud).1 = .ok () + · have gone := law.delete_ok y.kind y.slot w.cloud (deleted ps m y w.cloud).2 + (by simp only [deleted] at ok ⊢; rw [← ok]) + simp [show (⟨y.kind, y.slot.id, y.slot.generation⟩ : Physical K) = y from rfl] at gone + simp [gone] at present + · exact covers y tracked (.inr ok) + · have frame := law.delete_frame y₀.kind y₀.slot w.cloud y eq + exact covers y (h y (by simpa [deleted, frame] using present)) (.inl eq) + +/-- +The engine leaks nothing. Start with every existing resource tracked, take any +steps in any order, stop anywhere: every existing resource is still tracked, so +a later run can finish or remove it. +-/ +theorem Steps.tracked {ps : Providers K api} (law : Lawful ps m) {w w' : World K m} + (steps : Steps ps m w w') (h : Tracked law w) : Tracked law w' := by + induction steps with + | done => exact h + | next _ step ih => exact step.tracked law ih + +/-! ## Plan -/ + +/-- What it takes to bring a row to a node. A different kind of resource is always a replacement. -/ +def diffRow (ps : Providers K api) (r : Row K) (node : Node K) : Diff := + if h : r.kind = node.kind then + if r.id = node.id then (ps.provider node.kind).diff (h ▸ r.props) node.props else .replace + else .replace + +/-- +The row to write before acting on a node the state already has a row for. A row +whose status is not `ready` records a step that began and did not finish, and +is carried on from where it stopped. +-/ +def carry (ps : Providers K api) (node : Node K) (r : Row K) : Row K := + match diffRow ps r node, r.status with + | .replace, _ => .of node (r.generation + 1) .replacing (r.current :: r.old) + | .noop, .ready => .of node r.generation .ready r.old + | _, .ready => .of node r.generation .updating r.old + | _, .updating => .of node r.generation .updating r.old + | _, .creating => .of node r.generation .creating r.old + | _, .replacing => .of node r.generation .replacing r.old + | _, .deleting => .of node r.generation .creating r.old + +/-- The row to write before acting on a node, given what the state holds. -/ +def intend (ps : Providers K api) (node : Node K) : Option (Row K) → Row K + | none => .of node 0 .creating [] + | some r => carry ps node r + +theorem diffRow_same {ps : Providers K api} {r : Row K} {node : Node K} + (h : diffRow ps r node ≠ .replace) : r.kind = node.kind ∧ r.id = node.id := by + unfold diffRow at h + split at h + · split at h + · exact ⟨‹_›, ‹_›⟩ + · exact absurd rfl h + · exact absurd rfl h + +/-- The row written for a node tracks everything the row before it did. -/ +theorem carry_tracks (ps : Providers K api) (node : Node K) (r : Row K) (y : Physical K) + (t : r.tracks y) : (carry ps node r).tracks y := by + have same (generation status) (h : diffRow ps r node ≠ .replace) : + (Row.of node generation status r.old).tracks y ↔ + (y = ⟨r.kind, r.id, generation⟩ ∨ y ∈ r.old) := by + obtain ⟨kind, id⟩ := diffRow_same h + simp [Row.tracks, Row.of, Row.current, Node.id] at * + simp [kind, id] + have here : y = ⟨r.kind, r.id, r.generation⟩ ∨ y ∈ r.old := t + unfold carry + split + · rcases t with eq | mem + · exact .inr (by simp [Row.of, eq]) + · exact .inr (by simp [Row.of, mem]) + all_goals exact (same _ _ (by simp_all)).2 here + +/-- What the engine would do to a node. -/ +inductive Action where + | create + | update + | replace + | noop + | delete +deriving DecidableEq, Repr + +def planNode (ps : Providers K api) (node : Node K) (row : Option (Row K)) : Action := + match row with + | none => .create + | some r => + match (intend ps node (some r)).status with + | .creating => .create + | .updating => .update + | .replacing => .replace + | .ready => if r.old.isEmpty then .noop else .update + | .deleting => .delete + +/-- What applying a graph to a state would do, without doing it. -/ +def plan (ps : Providers K api) (g : Graph K) (s : State K) : List (String × Action) := + (g.order.filterMap fun id => (g.find id).map fun node => (id, planNode ps node (s.row id))) + ++ ((s.ids.filter fun id => !g.ids.contains id && (s.row id).isSome).eraseDups.map (·, .delete)) + +/-- A resource that is ready, as the graph describes it, needs nothing. -/ +theorem planNode_settled (ps : Providers K api) (law : Lawful ps m) (node : Node K) (generation : Nat) : + planNode ps node (some (.of node generation .ready [])) = .noop := by + have : diffRow ps (.of node generation .ready []) node = .noop := by + simp [diffRow, Row.of, law.diff_self] + have carried : carry ps node (.of node generation .ready []) = .of node generation .ready [] := by + unfold carry; rw [this]; rfl + simp only [planNode, intend] + rw [carried] + simp [Row.of] + +/-! ## Apply -/ + +/-- Remove the instances a row replaced, oldest decision first, forgetting each once it is gone. -/ +def collect (ps : Providers K api) (m : Model api) (id : String) (r : Row K) : + List (Physical K) → World K m → World K m × Bool + | [], w => (w, true) + | y :: rest, w => + let out := deleted ps m y w.cloud + match out.1 with + | .ok () => collect ps m id r rest ⟨w.state.set id { r with old := rest }, out.2⟩ + | .error _ => (⟨w.state, out.2⟩, false) + +/-- Bring one node of the graph into being. -/ +def converge (ps : Providers K api) (m : Model api) (node : Node K) (w : World K m) : + World K m × Bool := + let r := intend ps node (w.state.row node.id) + let w₁ : World K m := ⟨w.state.set node.id r, w.cloud⟩ + if r.status = .ready then collect ps m node.id r r.old w₁ + else + let out := reconciled ps m r w₁.cloud + match out.1 with + | .error _ => (⟨w₁.state, out.2⟩, false) + | .ok _ => + let ready := { r with status := .ready } + collect ps m node.id ready ready.old ⟨w₁.state.set node.id ready, out.2⟩ + +/-- Remove a resource the graph no longer has. -/ +def destroy (ps : Providers K api) (m : Model api) (id : String) (w : World K m) : + World K m × Bool := + match w.state.row id with + | none => (w, true) + | some r => + let leaving := { r with status := .deleting } + let collected := collect ps m id leaving leaving.old ⟨w.state.set id leaving, w.cloud⟩ + if collected.2 then + let out := deleted ps m r.current collected.1.cloud + match out.1 with + | .ok () => (⟨collected.1.state.erase id, out.2⟩, true) + | .error _ => (⟨collected.1.state, out.2⟩, false) + else (collected.1, false) + +/-- Run `step` for each id in turn, and say whether every one succeeded. -/ +def each (step : String → World K m → World K m × Bool) : List String → World K m → World K m × Bool + | [], w => (w, true) + | id :: rest, w => ((each step rest (step id w).1).1, (step id w).2 && (each step rest (step id w).1).2) + +/-- Bring into being the node with this id, if the graph has one. -/ +def convergeId (ps : Providers K api) (m : Model api) (g : Graph K) (id : String) (w : World K m) : + World K m × Bool := + match g.find id with + | some node => converge ps m node w + | none => (w, true) + +/-- +Make the cloud match the graph: bring every node into being in dependency +order, then remove what the graph no longer has. Nothing is removed unless +everything before it succeeded. +-/ +def apply (ps : Providers K api) (m : Model api) (g : Graph K) (w : World K m) : World K m × Bool := + let converged := each (convergeId ps m g) g.order w + if converged.2 = true then + each (destroy ps m) (converged.1.state.ids.filter fun id => !g.ids.contains id).eraseDups converged.1 + else converged + +/-! ## Apply takes only steps -/ + +theorem State.tracks_erase {s : State K} {id : String} {z : Physical K} + (h : s.tracks z) (elsewhere : ∀ r, s.row id = some r → ¬ r.tracks z) : (s.erase id).tracks z := by + obtain ⟨i, r, at_, t⟩ := h + by_cases eq : i = id + · subst eq; exact absurd t (elsewhere r at_) + · exact ⟨i, r, by simp [State.erase, eq, at_], t⟩ + +theorem collect_steps (ps : Providers K api) (id : String) (r : Row K) (olds : List (Physical K)) + (w : World K m) (has : w.state.row id = some { r with old := olds }) : + Steps ps m w (collect ps m id r olds w).1 := by + induction olds generalizing w with + | nil => exact .done w + | cons y rest ih => + have tracked : w.state.tracks y := ⟨id, _, has, .inr (by simp)⟩ + simp only [collect] + split + · next ok => + refine .trans (.next (.done w) (.delete y tracked ?_)) (ih _ (by simp)) + intro z t why + have ne : z ≠ y := why.resolve_right (by simp [ok]) + obtain ⟨i, r₀, at_, t⟩ := t + by_cases eq : i = id + · subst eq + rw [has] at at_ + cases at_ + refine ⟨i, _, State.set_row_self _ _ _, ?_⟩ + rcases t with cur | mem + · exact .inl cur + · exact .inr (by simpa [ne] using mem) + · exact ⟨i, r₀, by rw [State.set_row_of_ne _ _ eq]; exact at_, t⟩ + · exact .next (.done w) (.delete y tracked fun z t _ => t) + +/-- Once every replaced instance is gone, the row has none left; other rows are untouched. -/ +theorem collect_row (ps : Providers K api) (id : String) (r : Row K) (olds : List (Physical K)) + (w : World K m) (has : w.state.row id = some { r with old := olds }) : + ((collect ps m id r olds w).2 = true → + (collect ps m id r olds w).1.state.row id = some { r with old := [] }) ∧ + ∀ other, other ≠ id → (collect ps m id r olds w).1.state.row other = w.state.row other := by + induction olds generalizing w with + | nil => exact ⟨fun _ => has, fun _ _ => rfl⟩ + | cons y rest ih => + simp only [collect] + split + · obtain ⟨row, others⟩ := ih ⟨w.state.set id { r with old := rest }, _⟩ (by simp) + exact ⟨row, fun other ne => by rw [others other ne]; exact State.set_row_of_ne _ _ ne⟩ + · exact ⟨fun h => by simp at h, fun _ _ => rfl⟩ + +theorem converge_steps (ps : Providers K api) (node : Node K) (w : World K m) : + Steps ps m w (converge ps m node w).1 := by + have write : ∀ y, w.state.tracks y → + (w.state.set node.id (intend ps node (w.state.row node.id))).tracks y := by + intro y t + refine State.tracks_set (fun r at_ z tz => ?_) t + rw [at_] + exact carry_tracks ps node r z tz + simp only [converge] + split + · exact .trans (.next (.done w) (.write write)) (collect_steps ps _ _ _ _ (by simp)) + · split + · exact .next (.next (.done w) (.write write)) + (.reconcile node.id _ (State.set_row_self _ _ _) fun _ t => t) + · refine .trans (.next (.next (.done w) (.write write)) + (.reconcile node.id _ (State.set_row_self _ _ _) ?_)) (collect_steps ps _ _ _ _ (by simp)) + intro y t + exact State.tracks_set (fun r at_ z tz => by simp at at_; subst at_; exact tz) t + +theorem destroy_steps (ps : Providers K api) (id : String) (w : World K m) : + Steps ps m w (destroy ps m id w).1 := by + unfold destroy + split + · exact .done w + · next r has => + have write : ∀ y, w.state.tracks y → + (w.state.set id { r with status := .deleting }).tracks y := + fun y t => State.tracks_set (fun r₀ at_ z tz => by rw [has] at at_; cases at_; exact tz) t + have collected := collect_steps ps id { r with status := .deleting } r.old + ⟨w.state.set id { r with status := .deleting }, w.cloud⟩ (by simp) + have rows := collect_row (m := m) ps id { r with status := .deleting } r.old + ⟨w.state.set id { r with status := .deleting }, w.cloud⟩ (by simp) + have steps := Steps.next (.done w) (.write (ps := ps) write) |>.trans collected + simp only [] + split + · next done => + have row := rows.1 done + have tracked : (collect ps m id { r with status := .deleting } r.old + ⟨w.state.set id { r with status := .deleting }, w.cloud⟩).1.state.tracks r.current := + ⟨id, _, row, .inl rfl⟩ + split + · next ok => + refine .next steps (.delete r.current tracked ?_) + intro z t why + have ne : z ≠ r.current := why.resolve_right (by simp [ok]) + refine State.tracks_erase t fun r₀ at_ tz => ?_ + rw [row] at at_ + cases at_ + rcases tz with cur | mem + · exact ne cur + · simp at mem + · exact .next steps (.delete r.current tracked fun z t _ => t) + · exact steps + +theorem each_steps (ps : Providers K api) (step : String → World K m → World K m × Bool) + (sound : ∀ id w, Steps ps m w (step id w).1) (ids : List String) (w : World K m) : + Steps ps m w (each step ids w).1 := by + induction ids generalizing w with + | nil => exact .done w + | cons id rest ih => exact .trans (sound id w) (ih _) + +/-- Everything `apply` does is a step. -/ +theorem apply_steps (ps : Providers K api) (g : Graph K) (w : World K m) : + Steps ps m w (apply ps m g w).1 := by + have converged := each_steps ps (convergeId ps m g) + (fun id w => by unfold convergeId; split; exact converge_steps ps _ w; exact .done w) g.order w + unfold apply + by_cases ok : (each (convergeId ps m g) g.order w).2 = true + · simp only [ok, ite_true] + exact .trans converged (each_steps ps _ (destroy_steps ps) _ _) + · simp only [ok] + exact converged + +/-- +**Apply leaks nothing.** For any graph, any state and any lawful providers, +whatever fails and wherever it stops: if every resource in the cloud was +tracked before, every resource in the cloud is tracked after. +-/ +theorem apply_tracked {ps : Providers K api} (law : Lawful ps m) (g : Graph K) (w : World K m) + (h : Tracked law w) : Tracked law (apply ps m g w).1 := + (apply_steps ps g w).tracked law h + +/-! ## A successful apply leaves exactly the graph -/ + +theorem intend_form (ps : Providers K api) (node : Node K) (row : Option (Row K)) : + ∃ generation status old, intend ps node row = .of node generation status old := by + cases row with + | none => exact ⟨_, _, _, rfl⟩ + | some r => simp only [intend, carry]; split <;> exact ⟨_, _, _, rfl⟩ + +/-- A node is settled when its row says it is ready, as the graph describes it, with nothing left to remove. -/ +def Settled (node : Node K) (s : State K) : Prop := + ∃ generation, s.row node.id = some (.of node generation .ready []) + +theorem converge_others (ps : Providers K api) (node : Node K) (w : World K m) (other : String) + (ne : other ≠ node.id) : (converge ps m node w).1.state.row other = w.state.row other := by + simp only [converge] + split + · rw [(collect_row ps _ _ _ _ (by simp)).2 other ne]; exact State.set_row_of_ne _ _ ne + · split + · exact State.set_row_of_ne _ _ ne + · rw [(collect_row ps _ _ _ _ (by simp)).2 other ne] + simp [State.set_row_of_ne _ _ ne] + +theorem converge_settled (ps : Providers K api) (node : Node K) (w : World K m) + (ok : (converge ps m node w).2 = true) : Settled node (converge ps m node w).1.state := by + obtain ⟨generation, status, old, form⟩ := intend_form ps node (w.state.row node.id) + simp only [converge] at ok ⊢ + rw [form] at ok ⊢ + split at ok + · next ready => + simp only [Row.of] at ready + subst ready + split + · exact ⟨generation, (collect_row ps _ _ _ _ (by simp)).1 ok⟩ + · next h => exact absurd rfl h + · next notReady => + simp only [notReady, ite_false] + cases out : (reconciled ps m (Row.of node generation status old) w.cloud).1 with + | error e => simp [out] at ok + | ok attrs => + simp only [out] at ok ⊢ + exact ⟨generation, (collect_row ps _ _ _ _ (by simp)).1 ok⟩ + +theorem destroy_others (ps : Providers K api) (id : String) (w : World K m) (other : String) + (ne : other ≠ id) : (destroy ps m id w).1.state.row other = w.state.row other := by + unfold destroy + split + · rfl + · next r has => + have rows := (collect_row (m := m) ps id { r with status := .deleting } r.old + ⟨w.state.set id { r with status := .deleting }, w.cloud⟩ (by simp)).2 other ne + simp only [] + split + · split + · simp only [State.erase, ne, ite_false] + rw [rows]; exact State.set_row_of_ne _ _ ne + · rw [rows]; exact State.set_row_of_ne _ _ ne + · rw [rows]; exact State.set_row_of_ne _ _ ne + +theorem destroy_gone (ps : Providers K api) (id : String) (w : World K m) + (ok : (destroy ps m id w).2 = true) : (destroy ps m id w).1.state.row id = none := by + cases has : w.state.row id with + | none => simp only [destroy, has] + | some r => + simp only [destroy, has] at ok ⊢ + split at ok + · next collected => + simp only [collected, ite_true] + split at ok + · simp [State.erase] + · simp at ok + · simp at ok + +/-- What `each` establishes for the ids it ran, and what it leaves alone. -/ +theorem each_keeps (step : String → World K m → World K m × Bool) (P : World K m → Prop) + (ids : List String) (keep : ∀ id ∈ ids, ∀ w, P w → P (step id w).1) (w : World K m) (h : P w) : + P (each step ids w).1 := by + induction ids generalizing w with + | nil => exact h + | cons id rest ih => + exact ih (fun i mem => keep i (List.mem_cons_of_mem _ mem)) _ (keep id (List.mem_cons_self) w h) + +theorem each_all (step : String → World K m → World K m × Bool) (P : String → World K m → Prop) + (establish : ∀ id w, (step id w).2 = true → P id (step id w).1) + (keep : ∀ id other w, other ≠ id → P id w → P id (step other w).1) + (ids : List String) (w : World K m) (ok : (each step ids w).2 = true) : + ∀ id ∈ ids, P id (each step ids w).1 := by + induction ids generalizing w with + | nil => intro _ mem; cases mem + | cons head rest ih => + simp only [each, Bool.and_eq_true] at ok + intro id mem + by_cases later : id ∈ rest + · exact ih _ ok.2 id later + · have eq : id = head := by + rcases List.mem_cons.1 mem with h | h + · exact h + · exact absurd h later + subst eq + refine each_keeps step (P id) rest (fun other mem' w' h => ?_) _ (establish id w ok.1) + exact keep id other w' (fun e => later (e ▸ mem')) h + +theorem find_id {g : Graph K} {id : String} {node : Node K} (h : g.find id = some node) : + node.id = id := by + have := List.find?_some h + simpa using this + +/-- +**A successful apply leaves the state matching the graph.** Every node the +graph can order is settled, and nothing the graph does not have keeps a row. +It holds from any starting state, so it holds after any earlier crash. +-/ +theorem apply_settles (ps : Providers K api) (g : Graph K) (w : World K m) + (ok : (apply ps m g w).2 = true) : + (∀ id ∈ g.order, ∀ node, g.find id = some node → Settled node (apply ps m g w).1.state) ∧ + ∀ id, id ∉ g.ids → (apply ps m g w).1.state.row id = none := by + unfold apply at ok ⊢ + by_cases first : (each (convergeId ps m g) g.order w).2 = true + · simp only [first, ite_true] at ok ⊢ + have settled := each_all (convergeId ps m g) + (fun id w => ∀ node, g.find id = some node → Settled node w.state) + (fun id w ok node found => by + simp only [convergeId, found] at ok ⊢ + exact converge_settled ps node w ok) + (fun id other w ne h node found => by + obtain ⟨generation, row⟩ := h node found + refine ⟨generation, ?_⟩ + rw [← row] + unfold convergeId + split + · next n foundOther => + exact converge_others ps n w node.id (by rw [find_id found, find_id foundOther]; exact ne.symm) + · rfl) + g.order w first + generalize each (convergeId ps m g) g.order w = mid at settled ok ⊢ + have gone := each_all (destroy ps m) (fun id w => w.state.row id = none) + (destroy_gone ps) + (fun id other w ne h => by rw [destroy_others ps other w id ne.symm]; exact h) + _ mid.1 ok + constructor + · intro id inOrder node found + refine each_keeps (destroy ps m) (fun w => Settled node w.state) _ (fun other mem w' h => ?_) _ + (settled id inOrder node found) + obtain ⟨generation, row⟩ := h + refine ⟨generation, ?_⟩ + rw [← row] + refine destroy_others ps other w' node.id fun same => ?_ + have notInGraph : other ∉ g.ids := by + have := List.mem_filter.1 (List.mem_eraseDups.1 mem) + simpa using this.2 + exact notInGraph (by + rw [← same] + have := List.mem_of_find?_eq_some found + exact List.mem_map_of_mem (f := Node.id) this) + · intro id notInGraph + by_cases has : mid.1.state.row id = none + · exact each_keeps (destroy ps m) (fun w => w.state.row id = none) _ + (fun other _ w' h => by + by_cases same : id = other + · subst same + unfold destroy + rw [h] + exact h + · rw [destroy_others ps other w' id same]; exact h) _ has + · exact gone id (List.mem_eraseDups.2 (List.mem_filter.2 + ⟨mid.1.state.listed id has, by simpa using notInGraph⟩)) + · simp [first] at ok + +theorem find_of_mem_ids {g : Graph K} {id : String} (h : id ∈ g.ids) : ∃ node, g.find id = some node := by + obtain ⟨node, mem, rfl⟩ := List.mem_map.1 h + cases found : g.find node.id with + | some n => exact ⟨n, rfl⟩ + | none => + have := List.find?_eq_none.1 found node mem + simp at this + +/-- +**A successful apply leaves the cloud holding the graph and nothing else.** +If every existing resource was tracked before, then after an apply that +succeeds, every resource that exists is the current instance of a node of the +graph. Nothing from an earlier configuration, an earlier replacement or an +earlier crash is left behind. +-/ +theorem apply_exact {ps : Providers K api} (law : Lawful ps m) (g : Graph K) (w : World K m) + (tracked : Tracked law w) (ordered : ∀ id ∈ g.ids, id ∈ g.order) + (ok : (apply ps m g w).2 = true) (y : Physical K) + (present : law.present y (apply ps m g w).1.cloud = true) : + ∃ node, g.find y.id = some node ∧ y.kind = node.kind := by + obtain ⟨settled, gone⟩ := apply_settles ps g w ok + obtain ⟨id, r, at_, t⟩ := apply_tracked law g w tracked y present + by_cases inGraph : id ∈ g.ids + · obtain ⟨node, found⟩ := find_of_mem_ids inGraph + obtain ⟨generation, row⟩ := settled id (ordered id inGraph) node found + rw [find_id found] at row + rw [row] at at_ + cases at_ + rcases t with cur | old + · subst cur + exact ⟨node, by simpa [Row.current, Row.of, find_id found] using found, rfl⟩ + · simp [Row.of] at old + · rw [gone id inGraph] at at_ + cases at_ + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Cloud/Graph.lean b/packages/alchemy-lean/Alchemy/Cloud/Graph.lean new file mode 100644 index 00000000000..441c4cf9f7b --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Graph.lean @@ -0,0 +1,203 @@ +import Alchemy.Cloud.Layer + +/-! +# The resource graph + +A `Construct` declares resources and the hosts that use them. Building a stack +runs its constructs and gives a `Graph`: a plain value that a deploy walks, a +runtime serves from, and a proof computes with. +-/ + +namespace Alchemy.Cloud + +variable {K : Type} [Cloud K] + +/-- An error a host left unhandled, as it is reported. -/ +abbrev Failure := String + +/-- A host listening to a resource. -/ +structure Subscription (access : Access K) where + kind : K + source : Ref kind + /-- What listening exercises of the host's access. -/ + needs : List (Attempt K) := [] + handle : Cloud.Event kind → Run access Failure Unit + +/-- What a host runs: its access, how it answers a request, and what it listens to. -/ +structure Serve (k : K) where + access : Access K + fetch : Cloud.Request k → Run access Failure (Cloud.Response k) + on : List (Subscription access) := [] + +/-- A resource in the graph. A host is a resource that also runs code. -/ +structure Node (K : Type) [Cloud K] where + kind : K + ref : Ref kind + props : Cloud.Props kind + serve : Option (Serve kind) := none + /-- Where in the code each grant is asked for: the grant, and the call that asks. -/ + sites : List (Access K × String) := [] + +namespace Node + +def id (n : Node K) : String := n.ref.id + +/-- The access a node runs with. A resource that runs no code has none. -/ +def access (n : Node K) : Access K := + match n.serve with + | some serve => serve.access + | none => ∅ + +/-- The ids of the resources a node needs to exist before it does. -/ +def needs (n : Node K) : List String := + let listened := match n.serve with + | some serve => serve.on.map (·.source.id) + | none => [] + (Cloud.refs n.props ++ n.access.atoms.map (·.ref.id) ++ listened).eraseDups + +end Node + +/-- The resources of a stack. -/ +structure Graph (K : Type) [Cloud K] where + nodes : List (Node K) := [] + +namespace Graph + +def ids (g : Graph K) : List String := g.nodes.map (·.id) + +def find (g : Graph K) (id : String) : Option (Node K) := g.nodes.find? (·.id == id) + +/-- The access a host runs with. -/ +def roleOf (g : Graph K) (id : String) : Access K := + match g.find id with + | some node => node.access + | none => ∅ + +/-- Every node with the access it runs with. -/ +def roles (g : Graph K) : List (String × Access K) := g.nodes.map fun n => (n.id, n.access) + +/-- The hosts that may do this. -/ +def whoCan (g : Graph K) (t : Attempt K) : List String := + (g.roles.filter (·.2.permits t)).map (·.1) + +theorem mem_whoCan (g : Graph K) (t : Attempt K) (host : String) : + host ∈ g.whoCan t ↔ (g.roles.any fun role => role.1 == host && role.2.permits t) = true := by + simp [whoCan] + constructor + · rintro ⟨access, mem, permits⟩; exact ⟨host, access, mem, rfl, permits⟩ + · rintro ⟨_, access, mem, rfl, permits⟩; exact ⟨access, mem, permits⟩ + +/-- Whether this host may do this. -/ +def can (g : Graph K) (host : String) (t : Attempt K) : Bool := + g.roles.any fun role => role.1 == host && role.2.permits t + +/-- Each node with what it needs: the edges of the graph. -/ +def edges (g : Graph K) : List (String × String) := + g.nodes.flatMap fun n => n.needs.map fun to => (n.id, to) + +/-- Grants and references that name a resource the stack never declared. -/ +def dangling (g : Graph K) : List (String × String) := g.edges.filter fun e => !g.ids.contains e.2 + +def orderLoop (g : Graph K) : Nat → List String → List String + | 0, done => done + | fuel + 1, done => + let ready := (g.nodes.filter fun n => + !done.contains n.id && n.needs.all fun need => need == n.id || done.contains need).map (·.id) + if ready.isEmpty then done else g.orderLoop fuel (done ++ ready) + +/-- An order to create the resources in: each after everything it needs. -/ +def order (g : Graph K) : List String := g.orderLoop g.nodes.length [] + +/-- Every resource can be created: nothing dangles and nothing waits on itself in a circle. -/ +def deployable (g : Graph K) : Bool := g.dangling.isEmpty && g.order.length == g.nodes.length + +end Graph + +/-- What a construct can read about where it is being built. -/ +structure Env where + stage : String + +/-- Declares resources. The same construct is run to deploy a stack and to serve it. -/ +abbrev Construct (K : Type) [Cloud K] := ReaderT Env (StateT (Graph K) (Except String)) + +/-- The stage being built: "prod", "dev", ... -/ +def stage : Construct K String := return (← read).stage + +def declare (node : Node K) : Construct K Unit := do + let graph ← get + if graph.ids.contains node.id then + throw s!"two resources are named \"{node.id}\"" + set { graph with nodes := graph.nodes ++ [node] } + +/-- Declare a resource. -/ +def resource (k : K) (id : String) (props : Cloud.Props k) : Construct K (Ref k) := do + declare { kind := k, ref := ⟨id⟩, props } + return ⟨id⟩ + +/-- Declare a host. Its body declares what it uses and returns what it runs. -/ +def host (k : K) (id : String) (props : Cloud.Props k) (body : Construct K (Serve k)) : + Construct K (Ref k) := do + let serve ← body + declare { kind := k, ref := ⟨id⟩, props, serve := some serve } + return ⟨id⟩ + +/-- Code that listens to a resource, written against the services it needs. -/ +structure Listener (R : Service K) where + kind : K + source : Ref kind + /-- What listening exercises of the host's access. -/ + needs : List (Attempt K) := [] + /-- How it can fail. -/ + Error : Type + describe : Error → String + handle : Cloud.Event kind → Effect R Error Unit + +/-- +What a host runs, and the layer that gives it its services. Written last in a +host's body. The host's access is what the layer needs, and nothing else. What +answers a request has handled every error; a listener may leave one, and it is +reported as it prints. +-/ +def serve {k : K} {R : Service K} (layer : Layer Nothing R) + (fetch : Cloud.Request k → Effect R Never (Cloud.Response k)) + (on : List (Listener R) := []) : Construct K (Serve k) := + return { + access := layer.needs + fetch := fun request => ((fetch request).provide layer).mapError fun e => nomatch e + on := on.map fun listener => + { kind := listener.kind, source := listener.source, needs := listener.needs + handle := fun event => ((listener.handle event).provide layer).mapError listener.describe } } + +/-- A stack: a named construct, and what it reports once deployed. -/ +structure Stack (K : Type) [Cloud K] (Out : Type) where + name : String + body : Construct K Out + +namespace Stack + +variable {Out : Type} + +def build (s : Stack K Out) (stage : String) : Except String (Out × Graph K) := + (s.body.run { stage }).run {} + +/-- The graph of a stack at a stage. Empty if the stack does not build. -/ +def graph (s : Stack K Out) (stage : String) : Graph K := + match s.build stage with + | .ok (_, graph) => graph + | .error _ => {} + +/-- What the stack reports at a stage: its handles, for tests and theorems to name. -/ +def outputs [Inhabited Out] (s : Stack K Out) (stage : String) : Out := + match s.build stage with + | .ok (out, _) => out + | .error _ => default + +/-- Why the stack does not build, if it does not. -/ +def problem (s : Stack K Out) (stage : String) : Option String := + match s.build stage with + | .ok _ => none + | .error e => some e + +end Stack + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Cloud/Host.lean b/packages/alchemy-lean/Alchemy/Cloud/Host.lean new file mode 100644 index 00000000000..be0d1fc8264 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Host.lean @@ -0,0 +1,140 @@ +import Alchemy.Cloud.Sim + +/-! +# A host's body + +`Host role` is the `do` block a host is written in. Listening to a resource is +a step: it registers the listener. The block ends with what the host serves. + +Nobody writes the role. It is the grants the calls in the block ask for, read +off the code when the file is checked. +-/ + +namespace Alchemy.Cloud + +variable {K : Type} [Cloud K] + +/-- Whether an expression contains this very grant. -/ +def Access.holds (role : Access K) (grant : Attempt K) : Bool := + role.atoms.any fun atom => + if h : atom.kind = grant.kind then (h ▸ atom.ref) == grant.ref && (h ▸ atom.op) == grant.op + else false + +/-- Whether an expression contains every grant of another. -/ +def Access.covers (role need : Access K) : Bool := need.atoms.all role.holds + +theorem Access.le_of_covers {role need : Access K} (covers : role.covers need = true) : + need ≤ role := by + intro t permitted + rw [Access.permits_iff_atom] at permitted ⊢ + obtain ⟨grant, mem, on⟩ := permitted + have held := List.all_eq_true.mp covers grant mem + obtain ⟨atom, atomMem, same⟩ := List.any_eq_true.mp held + obtain ⟨kind, ref, op⟩ := atom + obtain ⟨kind', ref', op'⟩ := grant + split at same + · next h => + cases h + simp only [Bool.and_eq_true, beq_iff_eq] at same + obtain ⟨rfl, rfl⟩ := same + exact ⟨_, atomMem, on⟩ + · cases same + +/-- Both, leaving out an empty left side. -/ +def Access.join : Access K → Access K → Access K + | .none, more => more + | role, more => role ∪ more + +/-- What a host's block has said so far: what it listens to, and where it asks for each grant. -/ +structure Hosting (role : Access K) where + on : List (Subscription role) := [] + sites : List (Access K × String) := [] + +/-- +The `do` block of a host that runs with `role`. A step that needs a grant the +role lacks stops the block with that grant, and the block is run again with it. +-/ +abbrev Host (role : Access K) := + StateT (Hosting role) (ExceptT (Access K) (Construct K)) + +namespace Host + +variable {role : Access K} + +/-- Ask for a grant. Gives the proof that the role includes it. -/ +def grant (need : Access K) : Host role (PLift (need ≤ role)) := + if covers : role.covers need = true then pure ⟨Access.le_of_covers covers⟩ + else throwThe (Access K) need + +/-- The services of a layer, with what it needs added to the role. -/ +def provide {R : Service K} (layer : Layer Nothing R) : Host role (R role) := do + let ⟨le⟩ ← grant layer.needs + return layer.build le ⟨⟩ + +/-- Note where grants are asked for. -/ +def note (sites : List (Access K × String)) : Host role Unit := + modify fun hosting => { hosting with sites := hosting.sites ++ sites } + +/-- Register a listener. -/ +def listen (subscription : Subscription role) : Host role Unit := + modify fun hosting => { hosting with on := hosting.on ++ [subscription] } + +end Host + +/-- Run a host's block until its role has every grant it asks for. -/ +def settleHost {F : Access K → Type} (body : {role : Access K} → Host role (F role)) + (graph : Graph K) : + Nat → Access K → Construct K ((role : Access K) × F role × Hosting role) + | 0, _ => throw "a host asks for a different grant every time it is built" + | passes + 1, role => do + set graph + match ← ((body (role := role)).run {}).run with + | .ok (a, hosting) => return ⟨role, a, hosting⟩ + | .error missing => settleHost body graph passes (role.join missing) + +/-- +Declare a host from its block. The block is run as the stack is built: its +bindings become the host's role, and its listeners are registered. +-/ +def hostOf (k : K) (id : String) (props : Cloud.Props k) + (body : {role : Access K} → Host role (Cloud.Request k → Run role Never (Cloud.Response k))) : + Construct K (Ref k) := do + let ⟨role, fetch, hosting⟩ ← + settleHost (F := fun role => Cloud.Request k → Run role Never (Cloud.Response k)) body (← get) 64 ∅ + declare { + kind := k, ref := ⟨id⟩, props + serve := some { + access := role + fetch := fun request => (fetch request).mapError fun e => nomatch e + on := hosting.on } + sites := hosting.sites } + return ⟨id⟩ + +end Alchemy.Cloud + +namespace Alchemy.Cloud + +variable {K : Type} [Cloud K] + +/-- Whether this grant is asked for by a call in the node's code. -/ +def Node.calledFor (node : Node K) (grant : Attempt K) : Bool := + node.sites.any fun site => site.1.holds grant + +/-- +Every grant of every host is asked for by a call written in that host's code. +It is read off the code when the file is checked: no run is needed. A grant no +call asks for cannot be in a role at all. +-/ +def Graph.NoUnusedPermissions (g : Graph K) : Prop := + (g.nodes.all fun node => node.access.atoms.all node.calledFor) = true + +instance (g : Graph K) : Decidable g.NoUnusedPermissions := + inferInstanceAs (Decidable (_ = true)) + +/-- The calls that ask for a grant. -/ +def Graph.why (g : Graph K) (host : String) (grant : Attempt K) : List String := + match g.find host with + | some node => (node.sites.filter (·.1.holds grant)).map (·.2) + | none => [] + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Cloud/Hosted.lean b/packages/alchemy-lean/Alchemy/Cloud/Hosted.lean new file mode 100644 index 00000000000..50b2e93d18d --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Hosted.lean @@ -0,0 +1,241 @@ +import Alchemy.Engine +import Alchemy.Cloud.Layer +import Lean.Data.Json +import Alchemy.Codec + +/-! +# A model, hosted + +A domain model run by a host. Every command it is sent and every answer an +outside system gives is written to a journal before it is applied, so the model +is whatever its journal replays to. + +Whatever a journal holds, it replays to a world the model can reach. So every +rule proved of the model holds of the model as it is deployed. +-/ + +namespace Alchemy.Cloud + +open Lean (Json ToJson FromJson toJson fromJson?) + +variable {K : Type} [Cloud K] + +/-- A value as text for a journal, and back. -/ +class Text (α : Type) where + write : α → String + read : String → Option α + +instance : Text Empty where + write := nofun + read _ := none + +instance {α : Type} [ToJson α] [FromJson α] : Text α where + write a := (toJson a).compress + read text := do (fromJson? (← (Json.parse text).toOption)).toOption + +/-- One line of a model's history: something a caller sent, or an answer an outside system gave. -/ +inductive Journal.Line where + | input (text : String) + | answer (text : String) + /-- A decision across instances that a caller asked for. -/ + | decided (text : String) +deriving DecidableEq, Repr + +/-- Where a model's history is kept: lines, in the order they were written. -/ +structure Journal (access : Access K) where + read : Run access Never (List Journal.Line) + append : Journal.Line → Run access Never Unit + +/-- How a model is spoken to: what callers send, and how its history is written down. -/ +structure Served (m : Model) where + /-- What callers send. -/ + Input : Type + /-- The command an input is. -/ + command : Input → Send m.signature.aggregates + /-- Callers are only offered commands the model offers. -/ + offered : ∀ input, m.offered (command input) := by intro _; trivial + /-- How an input is kept in the journal. What is written reads back. -/ + input : Codec Input := by exact Codec.of + /-- How each outside answer is kept in the journal. -/ + reply : (c : m.signature.Call) → Codec (m.signature.Reply c) := by + intro c; cases c <;> exact Codec.of + /-- What callers send that is decided across instances. -/ + Deciding : Type := Empty + /-- The decision such an input is: one of the model's, who asks, and its command. -/ + decision : Deciding → (d : Decision m.signature.aggregates) × PLift (d ∈ m.decisions) × + d.Actor × d.Command := by exact nofun + deciding : Codec Deciding := by first | exact Codec.empty | exact Codec.of + +namespace Served + +variable {m : Model} + +def fuel : Nat := 1000 + +/-- The world after one line of the journal. A line that does not read is skipped. -/ +def apply (served : Served m) (w : Alchemy.World m.signature) : + Journal.Line → Alchemy.World m.signature + | .input text => + match served.input.read text with + | some input => m.play fuel w (.send (served.command input)) + | none => w + | .answer text => + match m.waiting w with + | c :: _ => + match (served.reply c).read text with + | some reply => m.play fuel w (.answer c reply) + | none => w + | [] => w + | .decided text => + match served.deciding.read text with + | some input => + m.play fuel w (.decide (served.decision input).1 (served.decision input).2.2.1 + (served.decision input).2.2.2) + | none => w + +/-- The world a journal leaves. -/ +def replay (served : Served m) (lines : List Journal.Line) : Alchemy.World m.signature := + lines.foldl served.apply (World.start m.signature) + +theorem apply_reachable (served : Served m) (w : Alchemy.World m.signature) (line : Journal.Line) + (reach : m.Reachable w) : m.Reachable (served.apply w line) := by + cases line with + | input text => + show m.Reachable (match served.input.read text with + | some input => m.play fuel w (.send (served.command input)) + | none => w) + split + · exact m.play_send_reachable fuel w _ (served.offered _) reach + · exact reach + | answer text => + show m.Reachable (match m.waiting w with + | c :: _ => + match (served.reply c).read text with + | some reply => m.play fuel w (.answer c reply) + | none => w + | [] => w) + split + · split + · exact m.play_answer_reachable fuel w _ _ reach + · exact reach + · exact reach + | decided text => + show m.Reachable (match served.deciding.read text with + | some input => + m.play fuel w (.decide (served.decision input).1 (served.decision input).2.2.1 + (served.decision input).2.2.2) + | none => w) + split + · next input _ => + exact m.play_decide_reachable fuel w _ (served.decision input).2.1.down _ _ reach + · exact reach + +/-- +Whatever a journal holds, written by this host or not, in order or not, it +replays to a world the model can reach. +-/ +theorem replay_reachable (served : Served m) (lines : List Journal.Line) : + m.Reachable (served.replay lines) := by + unfold replay + suffices ∀ w, m.Reachable w → m.Reachable (lines.foldl served.apply w) from this _ .start + intro w reach + induction lines generalizing w with + | nil => exact reach + | cons line rest ih => exact ih _ (served.apply_reachable w line reach) + +/-- +A rule each aggregate keeps holds of every instance of the deployed model, +whatever its journal holds. +-/ +theorem always (served : Served m) {P : Model.Rule m.signature.aggregates} + (initially : ∀ n, P n (m.signature.aggregates.of n).initial) + (kept : ∀ n, (m.signature.aggregates.of n).Keeps (P n)) + (decided : ∀ d ∈ m.decisions, ∀ r (ctx : Context d.Actor) c, + Model.Holds P r → Model.Holds P (r.decide d ctx c)) + (lines : List Journal.Line) : Model.Holds P (served.replay lines).toRecorded := + m.always initially kept decided _ (served.replay_reachable lines) + +end Served + +/-- A served model running on a host: where its journal is, and who answers its calls. -/ +structure Hosted {m : Model} (served : Served m) (role : Access K) where + journal : Journal role + /-- Each outside system the model calls. -/ + call : (c : m.signature.Call) → Run role Never (m.signature.Reply c) + +/-- Host a model: give it a journal, and say who answers each call it makes. -/ +def Served.host {m : Model} (served : Served m) {role : Access K} (journal : Journal role) + (call : (c : m.signature.Call) → Run role Never (m.signature.Reply c)) : Hosted served role := + { journal, call } + +namespace Hosted + +variable {m : Model} {served : Served m} {role : Access K} + +/-- The model as its journal has it. -/ +def world (hosted : Hosted served role) : Run role Never (Alchemy.World m.signature) := do + return served.replay (← hosted.journal.read) + +/-- Calls the outside systems the model is waiting on, until none is left. -/ +def answerCalls (hosted : Hosted served role) : + Nat → Alchemy.World m.signature → Run role Never (Alchemy.World m.signature) + | 0, w => pure w + | calls + 1, w => + match m.waiting w with + | [] => pure w + | c :: _ => do + let reply ← hosted.call c + hosted.journal.append (.answer ((served.reply c).write reply)) + hosted.answerCalls calls (m.play Served.fuel w (.answer c reply)) + +/-- +Send the model a command. Answers what the aggregate answered, and the world +once every policy that reacts has run and every outside call was made. +-/ +def send (hosted : Hosted served role) (input : served.Input) : + Run role Never + (Answer m.signature.aggregates (served.command input).to × Alchemy.World m.signature) := do + let before ← hosted.world + let command := served.command input + hosted.journal.append (.input (served.input.write input)) + let after ← hosted.answerCalls 100 (m.play Served.fuel before (.send command)) + return (before.toRecorded.outcome before.now command, after) + +/-- +Have the model decide across instances. Answers the rejection, if it is +refused, and the world once everything that follows has run. +-/ +def decide (hosted : Hosted served role) (input : served.Deciding) : + Run role Never (Except (served.decision input).1.Rejection Unit × Alchemy.World m.signature) := do + let before ← hosted.world + hosted.journal.append (.decided (served.deciding.write input)) + let after ← hosted.answerCalls 100 + (m.play Served.fuel before (.decide (served.decision input).1 (served.decision input).2.2.1 + (served.decision input).2.2.2)) + return (((served.decision input).1.decide ⟨(served.decision input).2.2.1, before.now⟩ + before.state (served.decision input).2.2.2).map fun _ => (), after) + +/-- +What the caller of a command is told: the rejection, or the aggregate's reply +from the state the command left. +-/ +def answered (command : Send m.signature.aggregates) + (answer : Answer m.signature.aggregates command.to) (after : Alchemy.World m.signature) : + Except (m.signature.aggregates.of command.to).Rejection + (m.signature.aggregates.of command.to).Reply := + answer.map fun _ => + (m.signature.aggregates.of command.to).reply + (after.state command.to ((m.signature.aggregates.of command.to).keyOf command.command)) + command.command + +/-- Send the model a command, and answer its caller: a rejection, or the aggregate's reply. -/ +def ask (hosted : Hosted served role) (input : served.Input) : + Run role Never + (Except (m.signature.aggregates.of (served.command input).to).Rejection + (m.signature.aggregates.of (served.command input).to).Reply) := do + let (answer, after) ← hosted.send input + return answered (served.command input) answer after + +end Hosted + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Cloud/HostedLaws.lean b/packages/alchemy-lean/Alchemy/Cloud/HostedLaws.lean new file mode 100644 index 00000000000..8588e663607 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/HostedLaws.lean @@ -0,0 +1,181 @@ +import Alchemy.Cloud.Hosted +import Alchemy.Cloud.Laws + +/-! +# What a journal promises, and what hosting gives for it + +A journal's law: reading answers its lines, and appending adds one at the end. +From that law alone, a host that sends its model a command leaves a journal +that replays to exactly the world it answered with. So what a host says +happened is what it wrote down, and the next request starts from it. +-/ + +namespace Alchemy.Cloud + +variable {K : Type} [Cloud K] {role : Access K} + +/-- +A journal keeps its law against a cloud, given how to read its lines off that +cloud and which clouds it is sound on: reading answers the lines and changes +nothing, and appending adds one line at the end and keeps the cloud sound. +-/ +structure Journal.Lawful (sim : Sim K) (journal : Journal role) + (lines : sim.State → List Journal.Line) (sound : sim.State → Prop) : Prop where + read : ∀ s, journal.read.eval sim s = (.ok (lines s), s) + append : ∀ s line, sound s → + ((journal.append line).eval sim s).1 = .ok () ∧ + lines ((journal.append line).eval sim s).2 = lines s ++ [line] ∧ + sound ((journal.append line).eval sim s).2 + +/-- What is written to a journal reads back as what it was. -/ +structure Served.Faithful {m : Model} (served : Served m) : Prop where + input : ∀ input, served.input.read (served.input.write input) = some input + reply : ∀ c reply, (served.reply c).read ((served.reply c).write reply) = some reply + +/-- Every served model is faithful: its codecs carry the proof. -/ +theorem Served.faithful {m : Model} (served : Served m) : served.Faithful := + ⟨served.input.back, fun c => (served.reply c).back⟩ + +namespace Hosted + +variable {m : Model} {served : Served m} {sim : Sim K} {lines : sim.State → List Journal.Line} + {sound : sim.State → Prop} + +/-- Reading the model back answers what its journal replays to, and changes nothing. -/ +theorem world_eval (hosted : Hosted served role) (lawful : hosted.journal.Lawful sim lines sound) + (s : sim.State) : hosted.world.eval sim s = (.ok (served.replay (lines s)), s) := by + show Run.eval sim (Run.bind _ _) s = _ + rw [Run.eval_bind, lawful.read] + rfl + +/-- +Answering the calls the model waits on keeps the journal and the world in step: +if the journal replayed to the world before, it replays to the world after. +-/ +theorem answerCalls_recorded (hosted : Hosted served role) + (lawful : hosted.journal.Lawful sim lines sound) (faithful : served.Faithful) + (quiet : ∀ c s, sound s → + lines ((hosted.call c).eval sim s).2 = lines s ∧ sound ((hosted.call c).eval sim s).2) : + ∀ (calls : Nat) (w : Alchemy.World m.signature) (s : sim.State), sound s → + served.replay (lines s) = w → + ∃ w', ((hosted.answerCalls calls w).eval sim s).1 = .ok w' ∧ + served.replay (lines ((hosted.answerCalls calls w).eval sim s).2) = w' ∧ + sound ((hosted.answerCalls calls w).eval sim s).2 := by + intro calls + induction calls with + | zero => intro w s ok same; exact ⟨w, rfl, same, ok⟩ + | succ calls ih => + intro w s sounds same + unfold answerCalls + split + · exact ⟨w, rfl, same, sounds⟩ + · next c rest waiting => + show ∃ w', (Run.eval sim (Run.bind (hosted.call c) _) s).1 = _ ∧ _ + obtain ⟨reply, answered⟩ := Run.eval_never sim (hosted.call c) s + obtain ⟨still, callSound⟩ := quiet c s sounds + obtain ⟨appended, grown, appendSound⟩ := lawful.append ((hosted.call c).eval sim s).2 + (.answer ((served.reply c).write reply)) callSound + have step : served.replay (lines ((hosted.journal.append + (.answer ((served.reply c).write reply))).eval sim ((hosted.call c).eval sim s).2).2) + = m.play Served.fuel w (.answer c reply) := by + rw [grown, still, Served.replay, List.foldl_append, ← Served.replay, same] + simp [Served.apply, waiting, faithful.reply] + obtain ⟨w', ok, recorded, endSound⟩ := ih _ _ appendSound step + refine ⟨w', ?_, ?_, ?_⟩ + · rw [Run.eval_bind, answered] + show (Run.eval sim (Run.bind _ _) _).1 = _ + rw [Run.eval_bind, appended] + exact ok + · show served.replay (lines (Run.eval sim (Run.bind (hosted.call c) _) s).2) = _ + rw [Run.eval_bind, answered] + show served.replay (lines (Run.eval sim (Run.bind _ _) _).2) = _ + rw [Run.eval_bind, appended] + exact recorded + · show sound (Run.eval sim (Run.bind (hosted.call c) _) s).2 + rw [Run.eval_bind, answered] + show sound (Run.eval sim (Run.bind _ _) _).2 + rw [Run.eval_bind, appended] + exact endSound + +/-- +A host answers what the model answers, and records what it applies. The answer +is the one the model, as the journal had it, gives the command. Afterwards the journal +replays to exactly the world the host answered with: whatever the cloud held +before, whatever the outside systems answered. It needs only the journal's law, +that what is written reads back, and that answering a call leaves the journal alone. +The cloud stays sound, so the same holds of the next request. +-/ +theorem send_recorded (hosted : Hosted served role) + (lawful : hosted.journal.Lawful sim lines sound) (faithful : served.Faithful) + (quiet : ∀ c s, sound s → + lines ((hosted.call c).eval sim s).2 = lines s ∧ sound ((hosted.call c).eval sim s).2) + (input : served.Input) (s : sim.State) (sounds : sound s) : + ∃ after, ((hosted.send input).eval sim s).1 = + .ok ((served.replay (lines s)).toRecorded.outcome (served.replay (lines s)).now + (served.command input), after) ∧ + served.replay (lines ((hosted.send input).eval sim s).2) = after ∧ + sound ((hosted.send input).eval sim s).2 := by + obtain ⟨appended, grown, appendSound⟩ := + lawful.append s (.input (served.input.write input)) sounds + have step : served.replay (lines ((hosted.journal.append + (.input (served.input.write input))).eval sim s).2) + = m.play Served.fuel (served.replay (lines s)) (.send (served.command input)) := by + rw [grown, Served.replay, List.foldl_append, ← Served.replay] + simp [Served.apply, faithful.input] + obtain ⟨after, ok, recorded, endSound⟩ := + hosted.answerCalls_recorded lawful faithful quiet 100 _ _ appendSound step + refine ⟨after, ?_, ?_, ?_⟩ + · show (Run.eval sim (Run.bind hosted.world _) s).1 = _ + rw [Run.eval_bind, hosted.world_eval lawful] + show (Run.eval sim (Run.bind _ _) s).1 = _ + rw [Run.eval_bind, appended] + show (Run.eval sim (Run.bind _ _) _).1 = _ + rw [Run.eval_bind, ok] + rfl + · show served.replay (lines (Run.eval sim (Run.bind hosted.world _) s).2) = _ + rw [Run.eval_bind, hosted.world_eval lawful] + show served.replay (lines (Run.eval sim (Run.bind _ _) s).2) = _ + rw [Run.eval_bind, appended] + show served.replay (lines (Run.eval sim (Run.bind _ _) _).2) = _ + rw [Run.eval_bind, ok] + exact recorded + · show sound (Run.eval sim (Run.bind hosted.world _) s).2 + rw [Run.eval_bind, hosted.world_eval lawful] + show sound (Run.eval sim (Run.bind _ _) s).2 + rw [Run.eval_bind, appended] + show sound (Run.eval sim (Run.bind _ _) _).2 + rw [Run.eval_bind, ok] + exact endSound + +/-- +A host answers what the model answers. The caller of a command is told the +rejection the model, as the journal had it, gives; or the aggregate's reply +from the state the journal has afterwards. And the journal is still sound. +-/ +theorem ask_recorded (hosted : Hosted served role) + (lawful : hosted.journal.Lawful sim lines sound) (faithful : served.Faithful) + (quiet : ∀ c s, sound s → + lines ((hosted.call c).eval sim s).2 = lines s ∧ sound ((hosted.call c).eval sim s).2) + (input : served.Input) (s : sim.State) (sounds : sound s) : + ((hosted.ask input).eval sim s).1 = + .ok (answered (served.command input) + ((served.replay (lines s)).toRecorded.outcome (served.replay (lines s)).now + (served.command input)) + (served.replay (lines ((hosted.ask input).eval sim s).2))) ∧ + sound ((hosted.ask input).eval sim s).2 := by + obtain ⟨after, answer, recorded, stillSound⟩ := + hosted.send_recorded lawful faithful quiet input s sounds + have evaluated : (hosted.ask input).eval sim s + = (.ok (answered (served.command input) + ((served.replay (lines s)).toRecorded.outcome (served.replay (lines s)).now + (served.command input)) after), + ((hosted.send input).eval sim s).2) := by + show Run.eval sim (Run.bind _ _) s = _ + rw [Run.eval_bind, answer] + rfl + rw [evaluated] + exact ⟨by rw [← recorded], stillSound⟩ + +end Hosted + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Cloud/Infer.lean b/packages/alchemy-lean/Alchemy/Cloud/Infer.lean new file mode 100644 index 00000000000..c0546fcbd85 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Infer.lean @@ -0,0 +1,258 @@ +import Lean +import Alchemy.Cloud.Host + +/-! +# A role read off the code + +`granted% body` checks a host's block and finds every grant its code asks for, +wherever in the block the call is written. The host's role is those grants. +Nobody takes a binding first: calling an operation is what asks for the grant. +-/ + +namespace Alchemy.Cloud + +variable {K : Type} [Cloud K] + +/-- Ask for a grant, and go on with the proof that the role includes it. -/ +def Host.granted {role : Access K} {α : Type} (need : Access K) + (sites : List (Access K × String)) (go : need ≤ role → Host role α) : Host role α := do + let ⟨le⟩ ← Host.grant need + Host.note sites + go le + +open Lean Elab Term Meta + +/-- Every grant the block asks for: each use of the stand-in instance, with what it was asked for. -/ +private partial def askedFor (stand : Expr) (e : Expr) (found : Array Expr) : Array Expr := + match e with + | .app f a => + if f == stand then (if found.contains a then found else found.push a) + else askedFor stand a (askedFor stand f found) + | .lam _ t b _ | .forallE _ t b _ => askedFor stand b (askedFor stand t found) + | .letE _ t v b _ => askedFor stand b (askedFor stand v (askedFor stand t found)) + | .mdata _ b | .proj _ _ b => askedFor stand b found + | _ => found + +/-- For each effect, the call in its body that asks for each of its grants, in order. -/ +initialize effectSites : SimplePersistentEnvExtension (Name × Array String) (NameMap (Array String)) ← + registerSimplePersistentEnvExtension { + addEntryFn := fun map (name, sites) => map.insert name sites + addImportedFn := fun imported => + imported.foldl (fun map entries => entries.foldl (fun map (name, sites) => map.insert name sites) map) {} + } + +/-- A call, as it is written, with where it is. -/ +private def siteOf (stx : Syntax) : TermElabM String := do + let text := (stx.reprint.getD "").trimAscii.toString + let text := " ".intercalate ((text.splitOn "\n").map (·.trimAscii.toString)) + let text := if text.length > 60 then (text.take 57).toString ++ "…" else text + let file := (System.FilePath.mk (← getFileName)).fileName.getD "" + match stx.getPos? with + | some pos => return s!"{file}:{(← getFileMap).toPosition pos |>.line} {text}" + | none => return text + +/-- +Where each grant is asked for. The block is checked once with its role left +open, so each call that needs a grant is left waiting, with its place in the +source. Nothing of that check is kept but the places. +-/ +private def sitesOf (body : Syntax) (role blockType : Expr) : TermElabM (Array (Expr × String)) := do + try + withoutModifyingState do + let open_ ← mkFreshExprMVar (← inferType role) + let blockType := blockType.replaceFVar role open_ + let _ ← elabTermEnsuringType body blockType + synthesizeSyntheticMVars (postpone := .yes) + let mut found := #[] + -- How many grants each call has asked for so far: an effect asks for several, in order. + let mut asked : Array (String.Pos.Raw × Nat) := #[] + for waiting in (← get).pendingMVars.reverse do + let some decl ← getSyntheticMVarDecl? waiting | continue + let type ← instantiateMVars (← waiting.getType) + if type.isAppOf ``Alchemy.Cloud.Has && type.getAppNumArgs ≥ 2 && (type.getArg! (type.getAppNumArgs - 2)).isMVar then + let need := type.getArg! (type.getAppNumArgs - 1) + let position := decl.stx.getPos?.getD 0 + let index := ((asked.find? (·.1 == position)).map (·.2)).getD 0 + asked := (asked.filter (·.1 != position)).push (position, index + 1) + unless need.hasMVar do + let here ← siteOf decl.stx + -- A call to an effect: point at the call inside it. + let head := if decl.stx.isIdent then decl.stx else decl.stx[0] + let inside ← try + let name ← realizeGlobalConstNoOverload head + pure (((effectSites.getState (← getEnv)).find? name).bind (·[index]?)) + catch _ => pure none + match inside with + | some site => found := found.push (need, s!"{site} (in {head.getId})") + | none => found := found.push (need, here) + return found + catch _ => return #[] + +/-- The block for one role, with every grant it asks for taken at the start. -/ +private def grantedFor (body : Syntax) (role blockType : Expr) : TermElabM Expr := do + let access ← inferType role + let places ← sitesOf body role blockType + -- While the block is checked, any grant it asks for is taken as given. + let standType ← withLocalDeclD `need access fun need => do + mkForallFVars #[need] (← mkAppM ``Alchemy.Cloud.Has #[role, need]) + let block ← withLocalDecl `granted .instImplicit standType fun stand => do + let block ← elabTermEnsuringType body blockType + synthesizeSyntheticMVarsNoPostponing + mkLambdaFVars #[stand] (← instantiateMVars block) + let .lam _ _ blockBody _ := block | throwError "granted%: unexpected block" + let marker := Lean.mkConst `Alchemy.Cloud.Infer.marker + let marked := blockBody.instantiate1 marker + let needs := askedFor marker marked #[] + for need in needs do + if need.hasLooseBVars then + throwError "a call's resource is only known when the code runs, so its grant cannot be \ + read off the code" + let empty ← mkAppOptM ``EmptyCollection.emptyCollection #[access, none] + let all ← needs.foldlM (init := none) fun (all : Option Expr) need => do + match all with + | none => return some need + | some all => return some (← mkAppM ``Union.union #[all, need]) + let all := all.getD empty + -- Each grant with the calls that ask for it. + let siteType ← mkAppM ``Prod #[access, mkConst ``String] + let mut sites : Array Expr := #[] + for need in needs do + for (asked, place) in places do + if ← withoutModifyingState (isDefEq asked need) then + sites := sites.push (← mkAppM ``Prod.mk #[need, mkStrLit place]) + let siteList ← mkListLit siteType sites.toList + let withGrant ← withLocalDeclD `le (← mkAppM ``LE.le #[all, role]) fun le => do + let mut proofs : Array (Expr × Expr) := #[] + for need in needs do + let within ← synthInstance (← mkAppM ``Alchemy.Cloud.Has #[all, need]) + let part ← mkProjection within `le + let has ← mkAppM ``Alchemy.Cloud.Has.mk #[← mkAppM ``Alchemy.Cloud.Access.le_trans #[part, le]] + proofs := proofs.push (need, has) + let filled := marked.replace fun e => + match e with + | .app f a => if f == marker then (proofs.find? (·.1 == a)).map (·.2) else none + | _ => none + mkLambdaFVars #[le] filled + mkAppM ``Alchemy.Cloud.Host.granted #[all, siteList, withGrant] + +/-- +`granted% block`: the block, with its role worked out from the calls in it. +-/ +elab "granted% " body:term : term <= expected => do + tryPostponeIfMVar expected + let expected ← instantiateMVars expected + if expected.isForall then + forallBoundedTelescope expected (some 1) fun binders blockType => do + mkLambdaFVars binders (← grantedFor body binders[0]! blockType) + else + -- Lean has already taken the role as a variable: it is the block type's own. + let args := expected.getAppArgs + unless expected.getAppFn.isConstOf ``Alchemy.Cloud.Host && args.size ≥ 3 do + throwError "granted% is for a host's block, but this is expected to be{indentExpr expected}" + grantedFor body args[2]! expected + +end Alchemy.Cloud + +namespace Alchemy.Cloud + +open Lean Elab Term Meta Command + +/-- +`effect def name (params) : type := body` defines a function a host's code can +call, and works out the grants its body asks for. They become the function's +own requirements, so nobody lists them: a host that calls it is asked for them. +The type names the role as `role`. +-/ +syntax (name := effectCommand) (docComment)? "effect " "def " ident bracketedBinder* " : " term " := " term : command + +@[command_elab effectCommand] def elabEffect : CommandElab := fun stx => do + let `($[$doc:docComment]? effect def $name:ident $binders* : $type := $body) := stx | throwUnsupportedSyntax + let declName := (← getCurrNamespace) ++ name.getId + let needsClass ← IO.mkRef (none : Option (Array (TSyntax ``Parser.Term.bracketedBinder) × Array (Ident × Term) × Array Ident)) + runTermElabM fun _ => do + elabBinders binders fun params => do + -- The role is the parameter the result's type runs under. + let roleParam? ← params.findM? fun param => do + return (← inferType param).isAppOf ``Alchemy.Cloud.Access + let some role := roleParam? | throwError "an effect takes its role as a parameter: {lit}role : Access K{rit}" + let access ← inferType role + let resultType ← Term.elabType type + let places ← sitesOf body role resultType + let standType ← withLocalDeclD `need access fun need => do + mkForallFVars #[need] (← mkAppM ``Alchemy.Cloud.Has #[role, need]) + let block ← withLocalDecl `granted .instImplicit standType fun stand => do + let value ← elabTermEnsuringType body resultType + synthesizeSyntheticMVarsNoPostponing + mkLambdaFVars #[stand] (← instantiateMVars value) + let .lam _ _ blockBody _ := block | throwError "effect: unexpected body" + let marker := Lean.mkConst `Alchemy.Cloud.Infer.marker + let marked := blockBody.instantiate1 marker + let needs := askedFor marker marked #[] + for need in needs do + if need.hasLooseBVars then + throwError "a call's resource is only known when the code runs, so its grant cannot be \ + read off the code" + -- One requirement per grant the body asks for. + let rec go (i : Nat) (given : Array Expr) : TermElabM Unit := do + if h : i < needs.size then + let hasType ← mkAppM ``Alchemy.Cloud.Has #[role, needs[i]] + withLocalDecl (Name.mkSimple s!"grant{i}") .instImplicit hasType fun inst => + go (i + 1) (given.push inst) + else + let filled := marked.replace fun e => + match e with + | .app f a => + if f == marker then (needs.findIdx? (· == a)).bind fun j => given[j]? else none + | _ => none + let all := params ++ given + let value ← mkLambdaFVars all filled + let declType ← mkForallFVars all resultType + let value ← instantiateMVars value + let declType ← instantiateMVars declType + addAndCompile <| .defnDecl { + name := declName, levelParams := [], type := declType, value + hints := .abbrev, safety := .safe } + -- What the effect needs, as one requirement a theorem about it can name. + let used := params.filter fun param => + param == role || needs.any fun need => need.containsFVar param.fvarId! + let binders ← used.mapM fun param => do + let name := mkIdent (← param.fvarId!.getUserName) + let type ← PrettyPrinter.delab (← inferType param) + `(bracketedBinder| ($name : $type)) + let fields ← (List.range needs.size).toArray.mapM fun i => do + let has ← PrettyPrinter.delab (← mkAppM ``Alchemy.Cloud.Has #[role, needs[i]!]) + pure (mkIdent (Name.mkSimple s!"grant{i}"), has) + let arguments ← used.mapM fun param => do pure (mkIdent (← param.fvarId!.getUserName)) + needsClass.set (some (binders, fields, arguments)) + let mut sites : Array String := #[] + for need in needs do + let mut site := "" + for (asked, place) in places do + if site.isEmpty then + if ← withoutModifyingState (isDefEq asked need) then site := place + sites := sites.push site + modifyEnv fun env => effectSites.addEntry env (declName, sites) + if let some doc := doc then addDocString declName (mkNullNode binders) doc + go 0 #[] + -- `name.Needs`: everything the effect needs, as one requirement. + if let some (classBinders, fields, arguments) ← needsClass.get then + let needsId := mkIdentFrom name (name.getId ++ `Needs) + let names := fields.map (·.1) + let types := fields.map (·.2) + elabCommand (← `(command| + class $needsId:ident $classBinders* : Prop where + $[$names:ident : $types]*)) + for field in names do + let projection := mkIdentFrom name (name.getId ++ `Needs ++ field.getId) + elabCommand (← `(command| attribute [instance] $projection)) + -- And the other way: a role that has each grant has the requirement. + let found ← names.mapM fun _ => `(inferInstance) + let given ← types.mapM fun type => `(bracketedBinder| [$type]) + let allBinders := classBinders ++ given + elabCommand (← `(command| + instance $allBinders:bracketedBinder* : $needsId $arguments* := ⟨$found,*⟩)) +where + lit := "{" + rit := "}" + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Cloud/Laws.lean b/packages/alchemy-lean/Alchemy/Cloud/Laws.lean new file mode 100644 index 00000000000..5618f2822b7 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Laws.lean @@ -0,0 +1,97 @@ +import Alchemy.Cloud.Sim + +/-! +# Reasoning about code that runs + +`Run.eval` is what a piece of code answers and the cloud it leaves. The lemmas +here step through code one call at a time, so a law about a binding, or a +theorem about code built on bindings, is proved without running anything. +-/ + +namespace Alchemy.Cloud + +variable {K : Type} [Cloud K] {access : Access K} {ε ε' α β : Type} + +namespace Run + +/-- What running code answers, and the cloud it leaves. -/ +def eval (sim : Sim K) (run : Run access ε α) (s : sim.State) : Except ε α × sim.State := + ((run.exec sim s).result, (run.exec sim s).state) + +variable (sim : Sim K) + +@[simp] theorem eval_pure (a : α) (s : sim.State) : + (Run.pure a : Run access ε α).eval sim s = (.ok a, s) := rfl + +@[simp] theorem eval_pure' (a : α) (s : sim.State) : + (pure a : Run access ε α).eval sim s = (.ok a, s) := rfl + +@[simp] theorem eval_fail (e : ε) (s : sim.State) : + (Run.fail e : Run access ε α).eval sim s = (.error e, s) := rfl + +@[simp] theorem eval_call {k : K} (ref : Ref k) (c : Cloud.Call k) (ok) + (next : Cloud.Reply c → Run access ε α) (s : sim.State) : + (Run.call ref c ok next).eval sim s = (next (sim.call ref c s).1).eval sim (sim.call ref c s).2.1 := + rfl + +/-- One call: what the cloud answers, and the cloud it leaves. -/ +@[simp] theorem eval_perform {k : K} (ref : Ref k) (c : Cloud.Call k) (h) (s : sim.State) : + (Run.perform ref c h : Run access ε _).eval sim s = (.ok (sim.call ref c s).1, (sim.call ref c s).2.1) := + rfl + +@[simp] theorem eval_performUnder {k : K} (ref : Ref k) (c : Cloud.Call k) (granted) (h) (covered) + (s : sim.State) : + (Run.performUnder ref c granted h covered : Run access ε _).eval sim s + = (.ok (sim.call ref c s).1, (sim.call ref c s).2.1) := + rfl + +/-- Two steps in a row: the second runs in the cloud the first left. -/ +theorem eval_bind (x : Run access ε α) (f : α → Run access ε β) (s : sim.State) : + (x.bind f).eval sim s = + match (x.eval sim s).1 with + | .ok a => (f a).eval sim (x.eval sim s).2 + | .error e => (.error e, (x.eval sim s).2) := by + induction x generalizing s with + | pure a => rfl + | fail e => rfl + | call ref c ok next ih => exact ih _ _ + +theorem eval_bind' (x : Run access ε α) (f : α → Run access ε β) (s : sim.State) : + (x >>= f).eval sim s = + match (x.eval sim s).1 with + | .ok a => (f a).eval sim (x.eval sim s).2 + | .error e => (.error e, (x.eval sim s).2) := + eval_bind sim x f s + +theorem eval_recover (x : Run access ε α) (f : ε → Run access ε' α) (s : sim.State) : + (x.recover f).eval sim s = + match (x.eval sim s).1 with + | .ok a => (.ok a, (x.eval sim s).2) + | .error e => (f e).eval sim (x.eval sim s).2 := by + induction x generalizing s with + | pure a => rfl + | fail e => rfl + | call ref c ok next ih => exact ih _ _ + +theorem eval_mapError (g : ε → ε') (x : Run access ε α) (s : sim.State) : + (x.mapError g).eval sim s = ((x.eval sim s).1.mapError g, (x.eval sim s).2) := by + unfold mapError + rw [eval_recover] + cases (x.eval sim s).1 <;> rfl + +theorem eval_result (x : Run access ε α) (s : sim.State) : + (x.result : Run access ε' _).eval sim s = (.ok (x.eval sim s).1, (x.eval sim s).2) := by + unfold result + rw [eval_recover, eval_bind] + cases (x.eval sim s).1 <;> rfl + +/-- Code that cannot fail answers. -/ +theorem eval_never (x : Run access Never α) (s : sim.State) : ∃ a, (x.eval sim s).1 = .ok a := by + induction x generalizing s with + | pure a => exact ⟨a, rfl⟩ + | fail e => exact nomatch e + | call ref c ok next ih => exact ih _ _ + +end Run + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Cloud/Layer.lean b/packages/alchemy-lean/Alchemy/Cloud/Layer.lean new file mode 100644 index 00000000000..caa6ac0e693 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Layer.lean @@ -0,0 +1,99 @@ +import Alchemy.Cloud.Effect + +/-! +# Layer + +A `Layer In Out` builds the services `Out` from the services `In`, and says +what access they need. Layers compose, and the access of the result is the +union of what its parts need, so a host's role is whatever its layers ask for. +-/ + +namespace Alchemy.Cloud + +variable {K : Type} [Cloud K] + +/-- Builds the services `Out` from the services `In`, given the access it needs. -/ +structure Layer (In Out : Service K) where + /-- The access the services need. -/ + needs : Access K := ∅ + /-- The services, for any access that includes what they need. -/ + build : {access : Access K} → needs ≤ access → In access → Out access + +namespace Layer + +variable {In Mid Out R T S : Service K} + +/-- +Building something with the services `In` at hand, under some access. A `do` +block: `let objects ← S3.GetObject bucket` takes a binding, and +`let jobs ← service JobStorage` any other service. +-/ +abbrev Make (In : Service K) (access : Access K) := ReaderT (In access) Id + +/-- One of the services at hand. -/ +def service (S : Service K) [Uses In S] {access : Access K} : Make In access (S access) := + fun services => Uses.get services + +/-- +`Gives m S access`: in `m`, the service `S` can be asked for, and comes built +for `access`. It is what lets a binding be written as a step: `← S3.GetObject bucket`. +-/ +class Gives (m : Type → Type) (S : Service K) (access : outParam (Access K)) where + give : m (S access) + +/-- A layer's block gives any service its dependencies include. -/ +instance (S : Service K) [Uses In S] {access : Access K} : Gives (Make In access) S access := + ⟨service S⟩ + +/-- Services that need no access of their own: built from the services they are given. -/ +def make (build : {access : Access K} → Make In access (Out access)) : Layer In Out where + build _ services := build.run services + +/-- A service built from one of the services available. -/ +def over (S : Service K) [Uses In S] (build : {access : Access K} → S access → Out access) : + Layer In Out := + make fun services => build (Uses.get services) + +/-- Give a layer the services it needs. The result needs what both need. -/ +def provide (layer : Layer Mid Out) (deps : Layer In Mid) : Layer In Out where + needs := deps.needs ∪ layer.needs + build le services := + layer.build (Access.le_trans (Access.le_union_right _ _) le) + (deps.build (Access.le_trans (Access.le_union_left _ _) le) services) + +/-- Services built from the services of another layer. They need what that layer needs. -/ +def «from» (deps : Layer In Mid) (build : {access : Access K} → Make Mid access (Out access)) : + Layer In Out where + needs := deps.needs + build le services := build.run (deps.build le services) + +/-- Both layers' services. They need what both need. -/ +def merge (a : Layer In R) (b : Layer In T) : Layer In (Both R T) where + needs := a.needs ∪ b.needs + build le services := + { left := a.build (Access.le_trans (Access.le_union_left _ _) le) services + right := b.build (Access.le_trans (Access.le_union_right _ _) le) services } + +/-- `a ++ b`: both layers' services. -/ +@[default_instance] instance : HAppend (Layer In R) (Layer In T) (Layer In (Both R T)) := ⟨merge⟩ + +@[simp] theorem needs_merge (a : Layer In R) (b : Layer In T) : + (a ++ b).needs = a.needs ∪ b.needs := rfl + +@[simp] theorem needs_provide (layer : Layer Mid Out) (deps : Layer In Mid) : + (layer.provide deps).needs = deps.needs ∪ layer.needs := rfl + +/-- The services of a layer that needs no others, built with exactly the access it asks for. -/ +def services (layer : Layer Nothing R) : R layer.needs := + layer.build (Access.le_refl _) ⟨⟩ + +end Layer + +export Layer (service Gives) + +/-- Run code with the services of a layer. It runs with the access the layer needs. -/ +def Effect.provide {R : Service K} {ε α : Type} (effect : Effect R ε α) (layer : Layer Nothing R) : + Run layer.needs ε α := + effect.run layer.services + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Cloud/Provider.lean b/packages/alchemy-lean/Alchemy/Cloud/Provider.lean new file mode 100644 index 00000000000..0f7015c6448 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Provider.lean @@ -0,0 +1,80 @@ +import Alchemy.Cloud.Graph +import Alchemy.Cloud.Api + +/-! +# Resource providers + +A provider says how one kind of resource is brought to match its configuration +and how it is removed. `Lawful` is what the engine needs to be true of the +providers it drives; it is proved against a model of the service. +-/ + +namespace Alchemy.Cloud +open Distilled (Api Eff Model) + +/-- What it takes to move a resource from one configuration to another. -/ +inductive Diff where + /-- Nothing to do. -/ + | noop + /-- It can be changed in place. -/ + | update + /-- It cannot: a new one must replace it. -/ + | replace +deriving DecidableEq, Repr + +/-- Which instance of a logical resource: replacing a resource makes its next generation. -/ +structure Slot where + id : String + generation : Nat +deriving DecidableEq, Repr + +/-- One physical resource in the cloud. -/ +structure Physical (K : Type) where + kind : K + id : String + generation : Nat +deriving DecidableEq, Repr + +def Physical.slot {K : Type} (x : Physical K) : Slot := ⟨x.id, x.generation⟩ + +/-- How one kind of resource is managed. -/ +structure Provider (api : Api) (Props Attrs : Type) where + /-- What it takes to go from the old configuration to the new. -/ + diff : Props → Props → Diff + /-- + Make the resource exist and match the configuration, whatever is there now: + nothing, an older configuration, or a half-finished earlier attempt. + -/ + reconcile : Slot → Props → Eff api Failure Attrs + /-- Remove the resource. Removing one that is already gone succeeds. -/ + delete : Slot → Eff api Failure Unit + +/-- A provider for every kind of a cloud. -/ +structure Providers (K : Type) [Cloud K] (api : Api) where + Attrs : K → Type + provider : (k : K) → Provider api (Cloud.Props k) (Attrs k) + +variable {K : Type} [Cloud K] {api : Api} + +/-- What the engine relies on. Proved for a set of providers against a model of their service. -/ +structure Lawful (ps : Providers K api) (m : Model api) where + /-- Whether a physical resource exists. -/ + present : Physical K → m.State → Bool + /-- A configuration needs nothing to become itself. -/ + diff_self : ∀ k (props : Cloud.Props k), (ps.provider k).diff props props = .noop + /-- A reconcile that succeeds leaves the resource there. -/ + reconcile_ok : ∀ k slot props s attrs s', + ((ps.provider k).reconcile slot props).run m s = (.ok attrs, s') → + present ⟨k, slot.id, slot.generation⟩ s' = true + /-- A reconcile, however it ends, creates and removes nothing else. -/ + reconcile_frame : ∀ k slot props s (y : Physical K), y ≠ ⟨k, slot.id, slot.generation⟩ → + present y (((ps.provider k).reconcile slot props).run m s).2 = present y s + /-- A delete that succeeds leaves the resource gone. -/ + delete_ok : ∀ k slot s s', + ((ps.provider k).delete slot).run m s = (.ok (), s') → + present ⟨k, slot.id, slot.generation⟩ s' = false + /-- A delete, however it ends, creates and removes nothing else. -/ + delete_frame : ∀ k slot s (y : Physical K), y ≠ ⟨k, slot.id, slot.generation⟩ → + present y (((ps.provider k).delete slot).run m s).2 = present y s + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Cloud/Run.lean b/packages/alchemy-lean/Alchemy/Cloud/Run.lean new file mode 100644 index 00000000000..84372c1b40f --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Run.lean @@ -0,0 +1,98 @@ +import Alchemy.Cloud.Access + +/-! +# Run + +Code that runs inside a host. Its type names the access it runs with, and every +call it makes carries the proof that this access permits it. +-/ + +namespace Alchemy.Cloud + +/-- A cloud: its kinds of resource, how each is configured, called and listened to. -/ +class Cloud (K : Type) extends Kinds K where + /-- How a resource of this kind is configured. -/ + Props : K → Type + /-- What running code can ask of a resource of this kind. -/ + Call : K → Type + /-- What a call answers. -/ + Reply : {k : K} → Call k → Type + /-- The access a call needs. -/ + needs : {k : K} → Call k → Op k + /-- What a resource of this kind tells its subscribers. -/ + Event : K → Type + /-- What a host of this kind is asked, and what it answers. -/ + Request : K → Type + Response : K → Type + /-- The resources a configuration refers to, by id. -/ + refs : {k : K} → Props k → List String := fun _ => [] + +variable {K : Type} [Cloud K] + +/-- A computation that runs with `access`, may fail with `ε`, and returns `α`. -/ +inductive Run (access : Access K) (ε α : Type) : Type where + | pure (a : α) + | fail (e : ε) + /-- Ask a resource something. `ok` is the proof that `access` permits it. -/ + | call {k : K} (ref : Ref k) (c : Cloud.Call k) + (ok : access.permits ⟨k, ref, Cloud.needs c⟩ = true) + (next : Cloud.Reply c → Run access ε α) + +namespace Run + +variable {access : Access K} {ε ε' α β : Type} + +def bind : Run access ε α → (α → Run access ε β) → Run access ε β + | .pure a, f => f a + | .fail e, _ => .fail e + | .call ref c ok next, f => .call ref c ok fun reply => (next reply).bind f + +instance : Monad (Run access ε) where + pure := .pure + bind := Run.bind + +/-- Recover from a failure. -/ +def recover : Run access ε α → (ε → Run access ε' α) → Run access ε' α + | .pure a, _ => .pure a + | .fail e, f => f e + | .call ref c ok next, f => .call ref c ok fun reply => (next reply).recover f + +instance : MonadExcept ε (Run access ε) where + throw := .fail + tryCatch := Run.recover + +/-- The outcome as a value, so a failure can be matched on. -/ +def result (run : Run access ε α) : Run access ε' (Except ε α) := + (run.bind fun a => (.pure (.ok a) : Run access ε (Except ε α))).recover fun e => .pure (.error e) + +def mapError (f : ε → ε') (run : Run access ε α) : Run access ε' α := + run.recover fun e => .fail (f e) + +/-- Run with more access than needed. -/ +def weaken {more : Access K} (le : access ≤ more) : Run access ε α → Run more ε α + | .pure a => .pure a + | .fail e => .fail e + | .call ref c ok next => .call ref c (le _ ok) fun reply => (next reply).weaken le + +/-- Ask a resource something. The access must include what the call needs. -/ +def perform {k : K} (ref : Ref k) (c : Cloud.Call k) + (h : Has access (.on ref (Cloud.needs c))) : Run access ε (Cloud.Reply c) := + .call ref c h.permits .pure + +/-- Ask a resource something under a wider grant that covers it, such as a key under a prefix. -/ +def performUnder {k : K} (ref : Ref k) (c : Cloud.Call k) (granted : Kinds.Op k) + (h : Has access (.on ref granted)) + (covered : (granted == Cloud.needs c || Kinds.covers granted (Cloud.needs c)) = true) : + Run access ε (Cloud.Reply c) := + .call ref c (h.permits_covered covered) .pure + +/-- Run against the real thing, given how to make each call. -/ +def io (make : {k : K} → Ref k → (c : Cloud.Call k) → IO (Cloud.Reply c)) : + Run access ε α → IO (Except ε α) + | .pure a => return .ok a + | .fail e => return .error e + | .call ref c _ next => do (next (← make ref c)).io make + +end Run + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Cloud/SQSQueue.lean b/packages/alchemy-lean/Alchemy/Cloud/SQSQueue.lean new file mode 100644 index 00000000000..8a3216e4a97 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/SQSQueue.lean @@ -0,0 +1,173 @@ +import Alchemy.Cloud.Provider +import Distilled.AWS.Services.SQS + +/-! +# An SQS queue, on the generated SDK + +The provider calls the SQS operations distilled generates from AWS's own model +of the service. Every error each operation can return is matched by name, and +what the provider does is proved against a model of SQS. +-/ + +namespace Alchemy.AWS.Queue +open Alchemy.Cloud Distilled +open Distilled.AWS (SQS.QueueAttributeName) +open Distilled.AWS.SQS (QueueAttributeName) + +structure Props where + /-- First in, first out. Fixed when the queue is created. -/ + fifo : Bool := false + /-- Seconds a received message stays hidden. -/ + visibilityTimeout : Nat := 30 +deriving DecidableEq, Repr + +abbrev Attributes := Dict QueueAttributeName String + +/-- The attributes that can be changed on a queue that exists. -/ +def mutable (props : Props) : Attributes := + ⟨[(.visibilityTimeout, toString props.visibilityTimeout)]⟩ + +/-- The attributes a queue is created with. -/ +def desired (props : Props) : Attributes := + ⟨(mutable props).entries ++ if props.fifo then [(.fifoQueue, "true")] else []⟩ + +abbrev Calls := Eff AWS.SQS.api Failure + +/-- Make the queue of this name exist with these properties, and give its URL. -/ +def reconcile (name : String) (props : Props) : Calls String := do + match ← AWS.SQS.getQueueUrl { queueName := name } with + | .ok found => + let some url := found.queueUrl | throw "SQS gave no URL for the queue" + match ← AWS.SQS.setQueueAttributes { queueUrl := url, attributes := mutable props } with + | .ok () => return url + | .error (.queueDoesNotExist _) => throw "the queue disappeared while it was being configured" + | .error (.overLimit _) | .error (.requestThrottled _) => throw "SQS is throttling requests" + | .error (.invalidAttributeName _) | .error (.invalidAttributeValue _) => + throw "SQS rejected the queue's attributes" + | .error (.invalidAddress _) | .error (.invalidSecurity _) | .error (.unsupportedOperation _) => + throw "SQS refused the request" + | .error (.queueDoesNotExist _) => + match ← AWS.SQS.createQueue { queueName := name, attributes := some (desired props) } with + | .ok created => + let some url := created.queueUrl | throw "SQS gave no URL for the queue" + return url + | .error (.queueNameExists _) => throw "a queue of this name exists with other attributes" + | .error (.queueDeletedRecently _) => + throw "a queue of this name was deleted less than a minute ago" + | .error (.invalidAttributeName _) | .error (.invalidAttributeValue _) => + throw "SQS rejected the queue's attributes" + | .error (.requestThrottled _) => throw "SQS is throttling requests" + | .error (.invalidAddress _) | .error (.invalidSecurity _) | .error (.unsupportedOperation _) => + throw "SQS refused the request" + | .error (.requestThrottled _) => throw "SQS is throttling requests" + | .error (.invalidAddress _) | .error (.invalidSecurity _) | .error (.unsupportedOperation _) => + throw "SQS refused the request" + +/-- Remove the queue of this name. One that is already gone counts as removed. -/ +def delete (name : String) : Calls Unit := do + match ← AWS.SQS.getQueueUrl { queueName := name } with + | .error (.queueDoesNotExist _) => return + | .error (.requestThrottled _) => throw "SQS is throttling requests" + | .error (.invalidAddress _) | .error (.invalidSecurity _) | .error (.unsupportedOperation _) => + throw "SQS refused the request" + | .ok found => + let some url := found.queueUrl | throw "SQS gave no URL for the queue" + match ← AWS.SQS.deleteQueue { queueUrl := url } with + | .ok () | .error (.queueDoesNotExist _) => return + | .error (.requestThrottled _) => throw "SQS is throttling requests" + | .error (.invalidAddress _) | .error (.invalidSecurity _) | .error (.unsupportedOperation _) => + throw "SQS refused the request" + +/-- The physical name of an instance of a queue. A first-in-first-out queue's name must end in `.fifo`. -/ +def nameOf (slot : Slot) (props : Props) : String := + s!"{slot.id}-{slot.generation}{if props.fifo then ".fifo" else ""}" + +def provider : Provider AWS.SQS.api Props String where + diff old new := if old = new then .noop else if old.fifo = new.fifo then .update else .replace + reconcile slot props := reconcile (nameOf slot props) props + delete slot := do + -- the instance may have been made under either name + delete (nameOf slot { fifo := false }) + delete (nameOf slot { fifo := true }) + +/-! ## A model of SQS -/ + +/-- The queues of an account, by name. In the model a queue's URL is its name. -/ +structure Queues where + byName : String → Option Attributes := fun _ => none + +def Queues.put (q : Queues) (name : String) (value : Option Attributes) : Queues := + ⟨fun n => if n = name then value else q.byName n⟩ + +def step : (op : AWS.SQS.Op) → AWS.SQS.Input op → Queues → + Except (AWS.SQS.Error op) (AWS.SQS.Output op) × Queues + | .getQueueUrl, input, q => + match q.byName input.queueName with + | some _ => (.ok { queueUrl := some input.queueName }, q) + | none => (.error (.queueDoesNotExist {}), q) + | .createQueue, input, q => + match q.byName input.queueName with + | none => (.ok { queueUrl := some input.queueName }, + q.put input.queueName (some (input.attributes.getD {}))) + | some existing => + if existing = input.attributes.getD {} then (.ok { queueUrl := some input.queueName }, q) + else (.error (.queueNameExists {}), q) + | .setQueueAttributes, input, q => + match q.byName input.queueUrl with + | some existing => (.ok (), q.put input.queueUrl + (some (input.attributes.entries.foldl (fun d (k, v) => d.set k v) existing))) + | none => (.error (.queueDoesNotExist {}), q) + | .deleteQueue, input, q => + match q.byName input.queueUrl with + | some _ => (.ok (), q.put input.queueUrl none) + | none => (.error (.queueDoesNotExist {}), q) + | op, _, q => (.ok (AWS.SQS.Output.empty op), q) + +/-- SQS, as far as creating, configuring and removing queues goes. -/ +def Service : Model AWS.SQS.api where + State := Queues + step := step + +/-! ## What is proved -/ + +macro "run_sqs" : tactic => + `(tactic| simp only [reconcile, delete, AWS.SQS.getQueueUrl, AWS.SQS.createQueue, + AWS.SQS.setQueueAttributes, AWS.SQS.deleteQueue, Eff.ask, Bind.bind, Eff.bind, Eff.run, + Service, step, Pure.pure, throw] at *) + +/-- +A reconcile that succeeds leaves a queue of that name whose visibility timeout +is the one asked for, whatever was there before. +-/ +theorem reconciled (name : String) (props : Props) (q q' : Queues) (url : String) + (ok : (reconcile name props).run Service q = (.ok url, q')) : + ∃ attributes, q'.byName name = some attributes ∧ + attributes.get? .visibilityTimeout = some (toString props.visibilityTimeout) := by + run_sqs + cases existing : q.byName name with + | none => + simp [Eff.run, step, existing] at ok + obtain ⟨_, rfl⟩ := ok + refine ⟨desired props, by simp [Queues.put], ?_⟩ + simp [desired, mutable, Dict.get?] + | some attributes => + simp [Eff.run, step, existing] at ok + obtain ⟨_, rfl⟩ := ok + refine ⟨attributes.set .visibilityTimeout (toString props.visibilityTimeout), + by simp [Queues.put, mutable], Dict.get?_set _ _ _⟩ + +/-- However a reconcile ends, no queue of another name is created, changed or removed. -/ +theorem reconcile_frame (name : String) (props : Props) (q : Queues) (other : String) + (ne : other ≠ name) : ((reconcile name props).run Service q).2.byName other = q.byName other := by + run_sqs + cases existing : q.byName name <;> simp [Eff.run, step, existing, Queues.put, ne] + +/-- A delete that succeeds leaves no queue of that name. -/ +theorem deleted (name : String) (q q' : Queues) + (ok : (delete name).run Service q = (.ok (), q')) : q'.byName name = none := by + run_sqs + cases existing : q.byName name <;> simp [Eff.run, step, existing] at ok <;> rw [← ok] + · exact existing + · simp [Queues.put] + +end Alchemy.AWS.Queue diff --git a/packages/alchemy-lean/Alchemy/Cloud/Sim.lean b/packages/alchemy-lean/Alchemy/Cloud/Sim.lean new file mode 100644 index 00000000000..c465a65e686 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Sim.lean @@ -0,0 +1,274 @@ +import Alchemy.Cloud.Graph + +/-! +# Running a graph in memory + +A `Sim` says what each call does to a cloud held in memory. With one, a graph +runs with no account and no emulator: requests go to hosts, calls change the +state, and events reach the hosts that listen. +-/ + +namespace Alchemy.Cloud + +variable {K : Type} [Cloud K] + +/-- Something a resource told its subscribers. -/ +structure Emitted (K : Type) [Cloud K] where + kind : K + source : Ref kind + event : Cloud.Event kind + +/-- A cloud in memory. -/ +structure Sim (K : Type) [Cloud K] where + State : Type + init : State + /-- What a call answers, what it leaves behind, and what it tells subscribers. -/ + call : {k : K} → Ref k → (c : Cloud.Call k) → State → Cloud.Reply c × State × List (Emitted K) + +/-- What running some code did. -/ +structure Outcome (K : Type) [Cloud K] (sim : Sim K) (ε α : Type) where + result : Except ε α + state : sim.State + events : List (Emitted K) + /-- Every call made, as the attempt it was. -/ + attempts : List (Attempt K) + +namespace Run + +variable {access : Access K} {ε α : Type} + +/-- Run against a cloud in memory. -/ +def exec (sim : Sim K) : Run access ε α → sim.State → Outcome K sim ε α + | .pure a, s => ⟨.ok a, s, [], []⟩ + | .fail e, s => ⟨.error e, s, [], []⟩ + | .call ref c _ next, s => + let step := sim.call ref c s + let rest := (next step.1).exec sim step.2.1 + { rest with + events := step.2.2 ++ rest.events + attempts := ⟨_, ref, Cloud.needs c⟩ :: rest.attempts } + +/-- +Code only does what its access permits: every call it makes, against any cloud +in any state, is one its access allows. +-/ +theorem exec_permitted (sim : Sim K) (run : Run access ε α) (s : sim.State) : + ∀ t ∈ (run.exec sim s).attempts, access.permits t = true := by + induction run generalizing s with + | pure a => simp [exec] + | fail e => simp [exec] + | call ref c ok next ih => + intro t mem + simp only [exec, List.mem_cons] at mem + rcases mem with rfl | mem + · exact ok + · exact ih _ _ t mem + +end Run + +/-- +Code given its services by a layer only does what that layer asks for: every +call it makes, against any cloud in any state, is one the layer's needs allow. +-/ +theorem Effect.provide_permitted {R : Service K} {ε α : Type} (sim : Sim K) (effect : Effect R ε α) + (layer : Layer Nothing R) (s : sim.State) : + ∀ t ∈ ((effect.provide layer).exec sim s).attempts, layer.needs.permits t = true := + Run.exec_permitted sim _ s + +/-- A stack running in memory. -/ +structure Running (K : Type) [Cloud K] (sim : Sim K) where + state : sim.State + /-- Events not yet delivered. -/ + pending : List (Emitted K) := [] + /-- Every call made so far, with the host that made it. -/ + used : List (String × Attempt K) := [] + /-- Listeners that gave up, and why. -/ + failures : List String := [] + +namespace Graph + +variable {sim : Sim K} + +def start (_ : Graph K) (sim : Sim K) : Running K sim := { state := sim.init } + +/-- What a host would run for this request, if it is a host of this kind. -/ +def handler (g : Graph K) {k : K} (host : Ref k) (request : Cloud.Request k) : + Option ((access : Access K) × Run access Failure (Cloud.Response k)) := + match g.find host.id with + | none => none + | some node => + if h : node.kind = k then + match node.serve with + | none => none + | some serve => some ⟨serve.access, h ▸ serve.fetch (h ▸ request)⟩ + else none + +/-- Send a host a request. -/ +def invoke (g : Graph K) {k : K} (host : Ref k) (request : Cloud.Request k) (w : Running K sim) : + Option (Except Failure (Cloud.Response k)) × Running K sim := + match g.handler host request with + | none => (none, w) + | some ⟨_, run⟩ => + let out := run.exec sim w.state + (some out.result, + { w with + state := out.state + pending := w.pending ++ out.events + used := w.used ++ out.attempts.map fun t => (host.id, t) }) + +/-- What a subscription would run for this event, if it listens to its source. -/ +def Subscription.react {access : Access K} (sub : Subscription access) (e : Emitted K) : + Option (Run access Failure Unit) := + if h : e.kind = sub.kind then + if sub.source.id == e.source.id then some (sub.handle (h ▸ e.event)) else none + else none + +/-- Deliver an event to one host's listeners. -/ +def deliverTo (node : Node K) (e : Emitted K) (w : Running K sim) : Running K sim := + match node.serve with + | none => w + | some serve => + serve.on.foldl (init := w) fun w sub => + match Subscription.react sub e with + | none => w + | some run => + let out := run.exec sim w.state + { state := out.state + pending := w.pending ++ out.events + used := w.used ++ (sub.needs ++ out.attempts).map fun t => (node.id, t) + failures := match out.result with + | .ok () => w.failures + | .error why => w.failures ++ [s!"{node.id}: {why}"] } + +/-- Deliver events until none are left, or the fuel runs out. -/ +def settle (g : Graph K) : Nat → Running K sim → Running K sim + | 0, w => w + | fuel + 1, w => + match w.pending with + | [] => w + | e :: rest => g.settle fuel (g.nodes.foldl (fun w node => deliverTo node e w) { w with pending := rest }) + +/-- A step of a test of a stack: a request and what it must answer, or a fact about the cloud. -/ +inductive Step (K : Type) [Cloud K] (sim : Sim K) where + /-- A request to a host, and what the answer must be. -/ + | request {k : K} (host : Ref k) (request : Cloud.Request k) (expect : Cloud.Response k → Bool) + /-- Something that must be true of the cloud now. -/ + | holds (what : String) (check : sim.State → Bool) + +/-- Run a test. `none` once a step fails. -/ +def play (g : Graph K) (steps : List (Step K sim)) : Option (Running K sim) := + steps.foldl (init := some (g.start sim)) fun w step => + match w, step with + | none, _ => none + | some w, .request host request expect => + match g.invoke host request w with + | (some (.ok response), w) => + let w := g.settle 1000 w + if expect response && w.failures.isEmpty then some w else none + | _ => none + | some w, .holds _ check => if check w.state then some w else none + +/-- Whether a test passes. -/ +def passes (g : Graph K) (steps : List (Step K sim)) : Bool := (g.play steps).isSome + +/-- The grants a world never exercised, with the host that holds each. -/ +def unused (g : Graph K) (w : Running K sim) : List (String × Attempt K) := + g.nodes.flatMap fun node => + (node.access.atoms.filter fun grant => + !w.used.any fun (host, t) => host == node.id && permitsOn grant.ref grant.op t).map + fun grant => (node.id, grant) + +/-- +Whether the tests together exercise every grant of every host. A grant no +test needs is one to remove, or a test to write. +-/ +def exercised (g : Graph K) (tests : List (List (Step K sim))) : Bool := + let used := tests.flatMap fun test => + match g.play test with + | some w => w.used + | none => [] + (g.unused { state := sim.init, used }).isEmpty + +end Graph + +end Alchemy.Cloud + +namespace Alchemy.Cloud.Graph + +variable {K : Type} [Cloud K] {sim : Sim K} + +/-- +Least privilege: no host holds a grant it never needs. For every grant of +every host there is a run of the stack in which that host makes a call the +grant is what permits. +-/ +def LeastPrivilege (g : Graph K) (sim : Sim K) : Prop := + ∀ node ∈ g.nodes, ∀ grant ∈ node.access.atoms, + ∃ (story : List (Step K sim)) (w : Running K sim) (t : Attempt K), + g.play story = some w ∧ (node.id, t) ∈ w.used ∧ permitsOn grant.ref grant.op t = true + +/-- Tests that between them use every grant are the runs that prove it. -/ +theorem LeastPrivilege.of_tests {g : Graph K} (tests : List (List (Step K sim))) + (exercised : g.exercised tests = true) : g.LeastPrivilege sim := by + intro node nodeMem grant grantMem + simp only [Graph.exercised, unused, List.isEmpty_iff, List.flatMap_eq_nil_iff, + List.map_eq_nil_iff, List.filter_eq_nil_iff] at exercised + have used := exercised node nodeMem grant grantMem + rw [Bool.not_eq_true, Bool.not_eq_false'] at used + obtain ⟨⟨host, t⟩, mem, ok⟩ := List.any_eq_true.mp used + simp only [Bool.and_eq_true, beq_iff_eq] at ok + obtain ⟨story, _, mem⟩ := List.mem_flatMap.mp mem + split at mem + · next w played => exact ⟨story, w, t, played, ok.1 ▸ mem, ok.2⟩ + · cases mem + +end Alchemy.Cloud.Graph + +namespace Alchemy.Cloud + +variable {K : Type} [Cloud K] + +/-- What one host can do to the cloud: answer a request, or handle an event it listens for. -/ +def Node.Does (node : Node K) (sim : Sim K) (s s' : sim.State) : Prop := + match node.serve with + | none => False + | some serve => + (∃ request, s' = ((serve.fetch request).exec sim s).state) ∨ + ∃ sub ∈ serve.on, ∃ event, s' = ((sub.handle event).exec sim s).state + +/-- +The states of the cloud a stack can reach: from an empty cloud, any host +answering any request or handling any event, in any order, any number of times. +-/ +inductive Graph.Reaches (g : Graph K) (sim : Sim K) : sim.State → Prop where + | start : Graph.Reaches g sim sim.init + | step {s s'} (node : Node K) : node ∈ g.nodes → Graph.Reaches g sim s → node.Does sim s s' → + Graph.Reaches g sim s' + +/-- A rule that holds of an empty cloud, and that no host breaks, holds of every state the stack reaches. -/ +theorem Graph.Reaches.invariant {g : Graph K} {sim : Sim K} {rule : sim.State → Prop} + (initially : rule sim.init) + (kept : ∀ node ∈ g.nodes, ∀ s s', rule s → node.Does sim s s' → rule s') : + ∀ s, g.Reaches sim s → rule s := by + intro s reach + induction reach with + | start => exact initially + | step node mem _ does ih => exact kept node mem _ _ ih does + +end Alchemy.Cloud + +namespace Alchemy.Cloud + +variable {K : Type} [Cloud K] + +/-- What a host's listeners would run for an event, each with the role it runs under. -/ +def Graph.listens (g : Graph K) (host : String) (e : Emitted K) : + List ((access : Access K) × Run access Failure Unit) := + match g.find host with + | none => [] + | some node => + match node.serve with + | none => [] + | some serve => serve.on.filterMap fun sub => (Graph.Subscription.react sub e).map fun run => ⟨serve.access, run⟩ + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Cloud/Tactics.lean b/packages/alchemy-lean/Alchemy/Cloud/Tactics.lean new file mode 100644 index 00000000000..722f2fa3eaf --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Tactics.lean @@ -0,0 +1,194 @@ +import Lean +import Alchemy.Attr +import Alchemy.Cloud.Sim +import Alchemy.Aggregate + +/-! +# Tactics + +What settles the common claims about a stack. +-/ + +namespace Alchemy.Cloud + +open Lean Elab Term Meta in +/-- A term, computed: `computed% prod.roles` is the list the stack builds. -/ +elab "computed% " t:term : term => do + let e ← instantiateMVars (← elabTerm t none) + withTransparency .all (reduce e (skipProofs := true) (skipTypes := true)) + +end Alchemy.Cloud + +namespace Alchemy.Cloud + +variable {K : Type} [Cloud K] + +/-- A kind of thing that can be done to a resource: "writing this bucket under this prefix". -/ +structure Doing (K : Type) [Cloud K] where + /-- What tells one such attempt from another: the rest of a key, say. -/ + Detail : Type + attempt : Detail → Attempt K + +namespace Graph + +/-- Only these hosts can do this. -/ +def only (g : Graph K) {k : K} (hosts : List (Ref k)) (action : Doing K) : Prop := + ∀ detail host, host ∈ g.whoCan (action.attempt detail) → host ∈ hosts.map (·.id) + +/-- Nothing in the stack can do this. -/ +def nobody (g : Graph K) (action : Doing K) : Prop := + ∀ detail host, host ∉ g.whoCan (action.attempt detail) + +/-- This host can never do this. -/ +def never (g : Graph K) {k : K} (host : Ref k) (action : Doing K) : Prop := + ∀ detail, g.can host.id (action.attempt detail) = false + +/-- This host can do this, whatever the detail. -/ +def may (g : Graph K) {k : K} (host : Ref k) (action : Doing K) : Prop := + ∀ detail, g.can host.id (action.attempt detail) = true + +end Graph + +open Lean Elab Tactic Meta in +/-- Stops with the stack's roles, for a rule that does not hold of them. -/ +elab "roles_do_not_allow " g:term : tactic => do + let roles ← Term.elabTerm (← `(Graph.roles $g)) none + let roles ← withTransparency .all (reduce roles (skipProofs := true) (skipTypes := true)) + throwError "This rule does not hold of the stack. Some role allows what the rule forbids, or \ + lacks what it requires. The roles, as the code gives them:{indentExpr roles}\n\ + `graph --why` prints the call behind each permission." + +/-- +Proves a rule about who can do what in a stack: `stack_rule in prod`. It uses +whatever is tagged `@[stack_facts]`, which is where a stack's outputs go. +-/ +syntax "stack_rule" " in " term (" using " "[" Lean.Parser.Tactic.simpLemma,* "]")? : tactic + +macro_rules + | `(tactic| stack_rule in $g) => + `(tactic| ( + try simp only [Graph.only, Graph.nobody, Graph.never, Graph.may] + intros + have roles : Graph.roles $g = computed% (Graph.roles $g) := rfl + first + | (simp [Graph.mem_whoCan, Graph.can, Access.permits, permitsOn, Kinds.covers, + roles, stack_facts] at * <;> done) + | (simp [Graph.mem_whoCan, Graph.can, Access.permits, permitsOn, Kinds.covers, + roles, stack_facts] at * <;> grind) + | roles_do_not_allow $g)) + | `(tactic| stack_rule in $g using [$lemmas,*]) => + `(tactic| ( + try simp only [Graph.only, Graph.nobody, Graph.never, Graph.may] + intros + have roles : Graph.roles $g = computed% (Graph.roles $g) := rfl + first + | (simp [Graph.mem_whoCan, Graph.can, Access.permits, permitsOn, Kinds.covers, + roles, stack_facts, $lemmas,*] at * <;> done) + | (simp [Graph.mem_whoCan, Graph.can, Access.permits, permitsOn, Kinds.covers, + roles, stack_facts, $lemmas,*] at * <;> grind) + | roles_do_not_allow $g)) + +end Alchemy.Cloud + +namespace Alchemy + +/-- +Proves that an aggregate keeps a rule: `aggregate_rule [decide, evolve, Rule]`. +It takes each command in turn, each way `decide` can answer it, and checks the +events it records. The names are the `decide` function, then whatever else the +rule is stated with. +-/ +syntax "aggregate_rule" " [" ident,+ "]" : tactic + +open Lean in +macro_rules + | `(tactic| aggregate_rule [$names,*]) => do + let names := names.getElems + let decide := names[0]! + let unfolded := #[mkIdent ``Alchemy.Aggregate.apply] ++ names.extract 1 names.size + let params ← unfolded.mapM fun name => `(Lean.Parser.Tactic.grindParam| $name:ident) + `(tactic| ( + intro ctx s c es h eq + cases c <;> simp only [$decide:ident] at eq <;> (repeat' split at eq) <;> + grind [$params,*])) + +/-- +Proves a property of what commands do to the state, such as `Idempotent` or +`Commute`: `command_law [decide, evolve]`. It takes each command and each way +`decide` can answer it. +-/ +syntax "command_law" " [" ident,+ "]" : tactic + +open Lean in +macro_rules + | `(tactic| command_law [$names,*]) => do + let unfolded := #[mkIdent ``Alchemy.Aggregate.step, mkIdent ``Alchemy.Aggregate.apply] + ++ names.getElems + let params ← unfolded.mapM fun name => `(Lean.Parser.Tactic.simpLemma| $name:ident) + let grinds ← unfolded.mapM fun name => `(Lean.Parser.Tactic.grindParam| $name:ident) + `(tactic| ( + simp only [Alchemy.Aggregate.Idempotent, Alchemy.Aggregate.IdempotentAt, + Alchemy.Aggregate.Commute] + intros + first + | (rename_i c _ _; cases c <;> simp [$params,*] <;> (repeat' split) <;> grind [$grinds,*]) + | (simp [$params,*] <;> (repeat' split) <;> grind [$grinds,*]))) + +/-- +Proves a rule that ties an aggregate's state to its history, such as `Tallies` +or `Precedes`: `history_rule [decide, evolve, worth]`. It takes each command, +each way `decide` can answer it, and the events it records. +-/ +syntax "history_rule" " [" ident,+ "]" : tactic + +open Lean in +macro_rules + | `(tactic| history_rule [$names,*]) => do + let names := names.getElems + let decide := names[0]! + let unfolded := #[mkIdent ``Alchemy.Aggregate.apply] ++ names.extract 1 names.size + let params ← unfolded.mapM fun name => `(Lean.Parser.Tactic.simpLemma| $name:ident) + `(tactic| first + | (intro ctx s c es h + cases c <;> simp only [$decide:ident] at h <;> (repeat' split at h) <;> cases h <;> + simp [$params,*]) + | (refine ⟨by simp, ?_, ?_⟩ <;> intro ctx s c es h <;> intros <;> cases c <;> + simp only [$decide:ident] at h <;> (repeat' split at h) <;> cases h <;> + simp_all [$params,*])) + +open Lean Elab Tactic Meta in +/-- The names a rule about an aggregate is stated with: its `decide` and `evolve`, and the rule. -/ +private def namesIn (goal : Expr) : MetaM (Array Ident) := do + let goal ← instantiateMVars goal + let args := goal.getAppArgs + let some aggregate := args[0]? | throwError "this is not a rule about an aggregate" + let .const aggregateName _ := aggregate.getAppFn + | throwError "the aggregate must be named, as in {lit}Order.Keeps …{rit}" + let mut names := #[mkIdent (`_root_ ++ aggregateName ++ `decide), + mkIdent (`_root_ ++ aggregateName ++ `evolve)] + for arg in args.extract 1 args.size do + if let .const name _ := arg.getAppFn then names := names.push (mkIdent (`_root_ ++ name)) + return names +where + lit := "`" + rit := "`" + +open Lean Elab Tactic in +/-- `aggregate_rule`, with the names read off the goal: `Order.Keeps ChargedOnce`. -/ +elab "aggregate_rule" : tactic => withMainContext do + let names ← namesIn (← getMainTarget) + evalTactic (← `(tactic| aggregate_rule [$names,*])) + +open Lean Elab Tactic in +/-- `command_law`, with the names read off the goal: `Order.Idempotent`. -/ +elab "command_law" : tactic => withMainContext do + let names ← namesIn (← getMainTarget) + evalTactic (← `(tactic| command_law [$(names.extract 0 2),*])) + +open Lean Elab Tactic in +/-- `history_rule`, with the names read off the goal: `Order.Tallies charged worth`. -/ +elab "history_rule" : tactic => withMainContext do + let names ← namesIn (← getMainTarget) + evalTactic (← `(tactic| history_rule [$names,*])) + +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Cloud/Tell.lean b/packages/alchemy-lean/Alchemy/Cloud/Tell.lean new file mode 100644 index 00000000000..9e4ead09387 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Cloud/Tell.lean @@ -0,0 +1,92 @@ +import Alchemy.Story +import Alchemy.Cloud.Sim +import Alchemy.Cloud.Hosted + +/-! +# A story, told to the stack + +A story is written in the model's own words: commands, events, views. Told to +the model alone, the story plays the outside systems. Told to a stack, each +command goes in through the host that runs the model, and the stack's own +bindings answer the model's calls. One story can be told both ways. +-/ + +namespace Alchemy.Cloud + +variable {K : Type} [Cloud K] + +/-- How a stack is told a story about the model it hosts. -/ +structure Telling (m : Model) (sim : Sim K) where + kind : K + /-- The host that runs the model. -/ + host : Ref kind + /-- A command, as the request that sends it. -/ + request : Send m.signature.aggregates → Cloud.Request kind + /-- The model as the cloud has it. -/ + world : sim.State → Alchemy.World m.signature + +namespace Graph + +variable {m : Model} {sim : Sim K} + +/-- Where a telling stands: the stack as it runs, and what the story has asserted. -/ +structure Told (m : Model) (sim : Sim K) where + running : Running K sim + asserted : List Nat := [] + pending : Option ((n : m.signature.aggregates.Name) × (m.signature.aggregates.of n).Rejection) := + none + +def tellStep (g : Graph K) (telling : Telling m sim) (told : Told m sim) : + Story.ModelStep m → Except String (Told m sim) + | .when s => + if told.pending.isSome then .error "a rejection was not asserted before the next command" + else + let before := telling.world told.running.state + let pending := + match before.toRecorded.outcome before.now s with + | .ok _ => none + | .error r => some ⟨s.to, r⟩ + match g.invoke telling.host (telling.request s) told.running with + | (some (.ok _), running) => + let running := g.settle 1000 running + if running.failures.isEmpty then .ok { told with running, pending } + else .error s!"a listener failed: {running.failures}" + | (some (.error why), _) => .error s!"the host failed: {why}" + | (none, _) => .error "the stack has no such host" + -- The stack answers the model's calls itself, so the story's own answers are passed over. + -- If they are not the answers the stack gives, what is recorded differs and a later step fails. + | .call _ | .answer .. => .ok told + | .given .. | .decide .. | .pass _ | .next _ => .error "this step is not told to a stack" + | step => + -- Everything else only looks: at what was recorded, at a state, at a view. + match Story.stepModel + { world := telling.world told.running.state, asserted := told.asserted, + pending := told.pending } step with + | .ok progress => .ok { told with asserted := progress.asserted, pending := progress.pending } + | .error why => .error why + +def tellAll (g : Graph K) (telling : Telling m sim) (told : Told m sim) : + List (Story.ModelStep m) → Nat → Except String Unit + | [], index => + Story.runModel + { world := telling.world told.running.state, asserted := told.asserted, + pending := told.pending } [] index + | step :: rest, index => + match g.tellStep telling told step with + | .ok told' => tellAll g telling told' rest (index + 1) + | .error why => .error s!"step {index + 1}: {why}" + +/-- Tells a story to the stack. `.ok ()` when every step holds. -/ +def tell (g : Graph K) (telling : Telling m sim) (steps : List (Story.ModelStep m)) : + Except String Unit := + g.tellAll telling { running := g.start sim } steps 0 + +/-- Whether a story holds of the stack. -/ +def tells (g : Graph K) (telling : Telling m sim) (steps : List (Story.ModelStep m)) : Bool := + match g.tell telling steps with + | .ok _ => true + | .error _ => false + +end Graph + +end Alchemy.Cloud diff --git a/packages/alchemy-lean/Alchemy/Codec.lean b/packages/alchemy-lean/Alchemy/Codec.lean new file mode 100644 index 00000000000..dbab996b14d --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Codec.lean @@ -0,0 +1,158 @@ +import Lean +import Std.Data.String.ToNat + +/-! +# Writing values down, and reading them back + +A journal keeps what a model was sent as text. For the model as deployed to be +the model that was proved, what is read back must be what was written. So the +text form here comes with that proof: `read (write a) = some a`. + +A value is written as a list of tokens, one for its case and one for each +field. A list of tokens is written as text with every character marked, so no +character of a token can be taken for a separator. +-/ + +namespace Alchemy + +namespace Packed + +/-- Tokens as characters: each character after a `c`, each token ended by a `;`. -/ +def pack : List String → List Char + | [] => [] + | token :: rest => (token.toList.flatMap fun ch => ['c', ch]) ++ ';' :: pack rest + +/-- Characters back to tokens. `token` is the one being read, backwards. -/ +def unpack : List Char → List Char → List String → Option (List String) + | [], [], done => some done.reverse + | [], _ :: _, _ => none + | ch :: rest, token, done => + if ch = ';' then unpack rest [] (String.ofList token.reverse :: done) + else + match rest with + | next :: rest => unpack rest (next :: token) done + | [] => none +termination_by chars => chars.length + +theorem unpack_marked (chars tail token : List Char) (done : List String) : + unpack ((chars.flatMap fun ch => ['c', ch]) ++ tail) token done + = unpack tail (chars.reverse ++ token) done := by + induction chars generalizing token with + | nil => rfl + | cons ch chars ih => + show unpack ('c' :: ch :: ((chars.flatMap fun ch => ['c', ch]) ++ tail)) token done = _ + rw [unpack] + simp only [show ('c' = ';') = False by decide, ite_false] + rw [ih] + simp + +theorem unpack_pack (tokens done : List String) : + unpack (pack tokens) [] done = some (done.reverse ++ tokens) := by + induction tokens generalizing done with + | nil => simp [pack, unpack] + | cons token tokens ih => + rw [pack, unpack_marked, unpack.eq_def] + simp only [ite_true, List.append_nil, List.reverse_reverse] + rw [ih] + simp [String.ofList_toList] + +/-- Tokens as text. -/ +def write (tokens : List String) : String := String.ofList (pack tokens) + +/-- Text back to tokens. -/ +def read (text : String) : Option (List String) := unpack text.toList [] [] + +/-- What is written reads back. -/ +theorem read_write (tokens : List String) : read (write tokens) = some tokens := by + simp [read, write, String.toList_ofList, unpack_pack] + +end Packed + +/-- A value as one token, and back, with the proof that it comes back. -/ +class Token (α : Type) where + write : α → String + read : String → Option α + back : ∀ a, read (write a) = some a + +/-- A value as tokens, and back, with the proof that it comes back. -/ +class Tokens (α : Type) where + write : α → List String + read : List String → Option α + back : ∀ a, read (write a) = some a + +instance : Token String := ⟨id, some, fun _ => rfl⟩ + +instance : Token Nat where + write := toString + read := String.toNat? + back n := by simp [Nat.toString_eq_repr, Nat.toNat?_repr] + +instance : Token Bool where + write b := if b then "yes" else "no" + read text := if text = "yes" then some true else if text = "no" then some false else none + back b := by cases b <;> simp + +/-- A value with several tokens is one token: its tokens, written as text. -/ +instance (priority := low) {α : Type} [Tokens α] : Token α where + write a := Packed.write (Tokens.write a) + read text := (Packed.read text).bind Tokens.read + back a := by simp [Packed.read_write, Tokens.back] + +instance : Tokens Unit := ⟨fun _ => [], fun _ => some (), fun _ => rfl⟩ + +instance {α : Type} [Token α] : Tokens (Option α) where + write + | none => ["none"] + | some a => ["some", Token.write a] + read + | ["none"] => some none + | ["some", text] => (Token.read text).map some + | _ => none + back a := by cases a <;> simp [Token.back] + +/-- How a kind of value is kept in a journal: as text, with the proof that it reads back. -/ +structure Codec (α : Type) where + write : α → String + read : String → Option α + back : ∀ a, read (write a) = some a + +/-- The codec of a value that has tokens. -/ +def Codec.of {α : Type} [Tokens α] : Codec α where + write a := Packed.write (Tokens.write a) + read text := (Packed.read text).bind Tokens.read + back a := by simp [Packed.read_write, Tokens.back] + +/-- Nothing to keep. -/ +def Codec.empty : Codec Empty := ⟨nofun, fun _ => none, nofun⟩ + +open Lean Elab Command Meta in +/-- +`derive_tokens T` writes `T` as tokens: a token for the case, then one for each +field. It comes with the proof that what is written reads back. +-/ +elab "derive_tokens " type:ident : command => do + let typeName ← liftCoreM <| realizeGlobalConstNoOverload type + let info ← getConstInfoInduct typeName + let mut writes : Array (TSyntax ``Parser.Term.matchAlt) := #[] + let mut reads : Array (TSyntax ``Parser.Term.matchAlt) := #[] + for ctorName in info.ctors do + let ctor ← getConstInfoCtor ctorName + let fields := (List.range ctor.numFields).toArray.map fun i => mkIdent (Name.mkSimple s!"field{i}") + let texts := (List.range ctor.numFields).toArray.map fun i => mkIdent (Name.mkSimple s!"text{i}") + let tag := Syntax.mkStrLit ctorName.getString! + let ctorId := mkIdent ctorName + writes := writes.push ⟨(← `(Parser.Term.matchAltExpr| + | $ctorId:ident $fields* => [$tag, $[Alchemy.Token.write $fields],*])).raw⟩ + let built ← `(some ($ctorId:ident $fields*)) + let body ← (fields.zip texts).foldrM (init := built) fun (field, text) rest => + `(Option.bind (Alchemy.Token.read $text) fun $field => $rest) + reads := reads.push ⟨(← `(Parser.Term.matchAltExpr| | [$tag, $texts,*] => $body)).raw⟩ + reads := reads.push ⟨(← `(Parser.Term.matchAltExpr| | _ => none)).raw⟩ + let typeId := mkIdent typeName + elabCommand (← `(command| + instance : Alchemy.Tokens $typeId where + write := fun value => match value with $writes:matchAlt* + read := fun tokens => match tokens with $reads:matchAlt* + back := by intro value; cases value <;> simp [Alchemy.Token.back])) + +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Compose.lean b/packages/alchemy-lean/Alchemy/Compose.lean new file mode 100644 index 00000000000..061136f8504 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Compose.lean @@ -0,0 +1,353 @@ +import Alchemy.Engine + +/-! +# Models that call one another + +A model calls systems outside it. When one of those systems is another model, +a `Link` says which calls it answers and how. The two then run together, and +everything proved of either still holds: a linked model is only ever answered +with something an outside system may answer, and only ever sent a command it +offers. +-/ + +namespace Alchemy + +/-- How some of one model's calls are answered by another model. -/ +structure Link (a b : Model) where + /-- The command a call becomes for the other model, if the other model answers it. -/ + ask : a.signature.Call → Option (Send b.signature.aggregates) + /-- What the caller is told, from what the other model answered. -/ + reply : (c : a.signature.Call) → (s : Send b.signature.aggregates) → + Answer b.signature.aggregates s.to → a.signature.Reply c + /-- A call only becomes a command the other model offers. -/ + offered : ∀ c s, ask c = some s → b.offered s := by intros; trivial + +namespace Link + +variable {a b : Model} (link : Link a b) + +/-- The two models' worlds, side by side. -/ +abbrev Worlds (_ : Link a b) := World a.signature × World b.signature + +/-- One thing two linked models can do. -/ +inductive Step : link.Worlds → link.Worlds → Prop where + /-- The calling model takes a step of its own. -/ + | left (wa wa' wb) : a.Step wa wa' → Step (wa, wb) (wa', wb) + /-- The answering model takes a step of its own. -/ + | right (wa wb wb') : b.Step wb wb' → Step (wa, wb) (wa, wb') + /-- A waiting call is answered by the other model: it is sent the command, and its answer goes back. -/ + | call (wa wb) (f) (before after : List (Fiber a.signature)) (c) (k) (s) : + wa.fibers = before ++ f :: after → + f.program = .call c k → + link.ask c = some s → + Step (wa, wb) + ({ wa with fibers := before ++ + { f with program := k (link.reply c s (wb.toRecorded.outcome wb.now s)) } :: after }, + wb.dispatch s) + +/-- The worlds two linked models can get to. -/ +inductive Reachable : link.Worlds → Prop where + | start : Reachable (World.start a.signature, World.start b.signature) + | step {w w'} : Reachable w → link.Step w w' → Reachable w' + +/-- Linked, the calling model is still only where it could get to alone. -/ +theorem reachable_left {w : link.Worlds} (reach : link.Reachable w) : a.Reachable w.1 := by + induction reach with + | start => exact .start + | step _ step ih => + cases step with + | left wa wa' wb h => exact .step ih h + | right wa wb wb' h => exact ih + | call wa wb f before after c k s fibers program asked => + exact .step ih (.answer wa f before after c k _ fibers program) + +/-- And so is the answering model. -/ +theorem reachable_right {w : link.Worlds} (reach : link.Reachable w) : b.Reachable w.2 := by + induction reach with + | start => exact .start + | step _ step ih => + cases step with + | left wa wa' wb h => exact ih + | right wa wb wb' h => exact .step ih h + | call wa wb f before after c k s fibers program asked => + exact .step ih (.send wb s (link.offered c s asked)) + +/-- +So whatever is proved of each model alone holds of the two linked: a rule of +the caller's worlds and a rule of the answerer's worlds hold together. +-/ +theorem both {P : World a.signature → Prop} {Q : World b.signature → Prop} + (left : ∀ w, a.Reachable w → P w) (right : ∀ w, b.Reachable w → Q w) + {w : link.Worlds} (reach : link.Reachable w) : P w.1 ∧ Q w.2 := + ⟨left _ (link.reachable_left reach), right _ (link.reachable_right reach)⟩ + +/-- A rule about the two together: it holds at the start, and no step breaks it. -/ +theorem invariant {rule : link.Worlds → Prop} + (initially : rule (World.start a.signature, World.start b.signature)) + (kept : ∀ w w', link.Reachable w → rule w → link.Step w w' → rule w') : + ∀ w, link.Reachable w → rule w := by + intro w reach + induction reach with + | start => exact initially + | step before step ih => exact kept _ _ before ih step + +/-! ## Running two linked models -/ + +def fuel : Nat := 1000 + +/-- The first waiting call the other model answers is answered by it. -/ +def answerNext (w : link.Worlds) : Option link.Worlds := + (a.waiting w.1).findSome? fun c => + match link.ask c with + | none => none + | some s => + let answer := w.2.toRecorded.outcome w.2.now s + (a.answer w.1 c (link.reply c s answer)).map fun wa => + (a.settle fuel wa, b.settle fuel (w.2.dispatch s)) + +/-- Answers linked calls until none is waiting, or the fuel runs out. -/ +def settle : Nat → link.Worlds → link.Worlds + | 0, w => w + | calls + 1, w => + match link.answerNext w with + | none => w + | some w' => settle calls w' + +/-- A move of the calling model, then everything that follows in both. -/ +def play (w : link.Worlds) (move : Model.Move a) : link.Worlds := + link.settle 100 (a.play fuel w.1 move, w.2) + +/-- Both worlds after every move of the calling model, from the start. -/ +def run (moves : List (Model.Move a)) : link.Worlds := + moves.foldl link.play (World.start a.signature, World.start b.signature) + +end Link + +end Alchemy + +namespace Alchemy + +/-- +Any number of models that call one another. For each model, `ask` says which of +its calls another model answers and with what command, and `reply` what the +caller is told. +-/ +structure Network (ι : Type) [DecidableEq ι] (model : ι → Model) where + ask : (i : ι) → (model i).signature.Call → + Option ((j : ι) × Send (model j).signature.aggregates) + reply : (i : ι) → (c : (model i).signature.Call) → (j : ι) → + (s : Send (model j).signature.aggregates) → Answer (model j).signature.aggregates s.to → + (model i).signature.Reply c + /-- A call only becomes a command the answering model offers. -/ + offered : ∀ i c j s, ask i c = some ⟨j, s⟩ → (model j).offered s := by intros; trivial + /-- + The models, for running the network. A run looks for a waiting call among them + in this order. Proofs do not depend on it: `Step` lets any call be answered next. + -/ + parts : List ι := [] + +namespace Network + +variable {ι : Type} [DecidableEq ι] {model : ι → Model} (net : Network ι model) + +/-- Every model's world. -/ +abbrev Worlds (_ : Network ι model) := (i : ι) → World (model i).signature + +/-- The worlds with one model's replaced. -/ +def set (w : net.Worlds) (i : ι) (wi : World (model i).signature) : net.Worlds := + fun k => if h : i = k then h ▸ wi else w k + +@[simp] theorem set_same (w : net.Worlds) (i : ι) (wi : World (model i).signature) : + net.set w i wi i = wi := by simp [set] + +theorem set_other (w : net.Worlds) (i k : ι) (wi : World (model i).signature) (ne : i ≠ k) : + net.set w i wi k = w k := by simp [set, ne] + +/-- One thing a network of models can do. -/ +inductive Step : net.Worlds → net.Worlds → Prop where + /-- One model takes a step of its own. -/ + | own (w) (i) (wi') : (model i).Step (w i) wi' → Step w (net.set w i wi') + /-- A waiting call is answered by another model: it is sent the command, and its answer goes back. -/ + | call (w) (i) (f) (before after : List (Fiber (model i).signature)) (c) (k) (j) (s) : + (w i).fibers = before ++ f :: after → + f.program = .call c k → + net.ask i c = some ⟨j, s⟩ → + i ≠ j → + Step w (net.set + (net.set w i { w i with fibers := before ++ + { f with program := k (net.reply i c j s ((w j).toRecorded.outcome (w j).now s)) } :: after }) + j ((w j).dispatch s)) + +/-- The worlds a network can get to. -/ +inductive Reachable : net.Worlds → Prop where + | start : Reachable fun i => World.start (model i).signature + | step {w w'} : Reachable w → net.Step w w' → Reachable w' + +/-- In a network, each model is still only where it could get to alone. -/ +theorem reachable_each {w : net.Worlds} (reach : net.Reachable w) (k : ι) : + (model k).Reachable (w k) := by + induction reach generalizing k with + | start => exact .start + | step _ step ih => + cases step with + | own i wi' h => + by_cases same : i = k + · subst same; rw [set_same]; exact .step (ih i) h + · rw [net.set_other _ _ _ _ same]; exact ih k + | call i f before after c cont j s fibers program asked differ => + by_cases toK : j = k + · subst toK + rw [set_same] + exact .step (ih j) (.send _ s (net.offered i c j s asked)) + · rw [net.set_other _ _ _ _ toK] + by_cases fromK : i = k + · subst fromK + rw [set_same] + exact .step (ih i) (.answer _ f before after c cont _ fibers program) + · rw [net.set_other _ _ _ _ fromK]; exact ih k + +/-- +So whatever is proved of each model alone holds of all of them together: a rule +for each model's worlds holds of every model in every world the network reaches. +-/ +theorem all {P : (i : ι) → World (model i).signature → Prop} + (each : ∀ i w, (model i).Reachable w → P i w) {w : net.Worlds} (reach : net.Reachable w) : + ∀ i, P i (w i) := + fun i => each i _ (net.reachable_each reach i) + +/-! ## Running a network -/ + +/-- The first waiting call that another model answers is answered by it. -/ +def answerNext (w : net.Worlds) : Option net.Worlds := + net.parts.findSome? fun i => + ((model i).waiting (w i)).findSome? fun c => + match net.ask i c with + | none => none + | some ⟨j, s⟩ => + if i = j then none + else + let answer := (w j).toRecorded.outcome (w j).now s + ((model i).answer (w i) c (net.reply i c j s answer)).map fun wi => + net.set (net.set w i ((model i).settle Link.fuel wi)) j + ((model j).settle Link.fuel ((w j).dispatch s)) + +/-- Answers calls between the models until none is waiting, or the fuel runs out. -/ +def settle : Nat → net.Worlds → net.Worlds + | 0, w => w + | calls + 1, w => + match net.answerNext w with + | none => w + | some w' => settle calls w' + +/-- A move of one model, then everything that follows in all of them. -/ +def play (w : net.Worlds) (move : (i : ι) × Model.Move (model i)) : net.Worlds := + net.settle 100 (net.set w move.1 ((model move.1).play Link.fuel (w move.1) move.2)) + +/-- Every model's world after every move, from the start. -/ +def run (moves : List ((i : ι) × Model.Move (model i))) : net.Worlds := + moves.foldl net.play fun i => World.start (model i).signature + +/-! ## A run is within what the network can reach + +The run picks one order in which to answer waiting calls. Whichever it picks, +it only takes steps the network can take. So every theorem about the worlds a +network can reach holds of every run, whatever the order. +-/ + +theorem set_set (w : net.Worlds) (i : ι) (a b : World (model i).signature) : + net.set (net.set w i a) i b = net.set w i b := by + funext k + by_cases same : i = k + · subst same; simp + · simp [set, same] + +theorem set_self (w : net.Worlds) (i : ι) : net.set w i (w i) = w := by + funext k + by_cases same : i = k + · subst same; simp + · simp [set, same] + +theorem set_comm (w : net.Worlds) (i j : ι) (a : World (model i).signature) + (b : World (model j).signature) (ne : i ≠ j) : + net.set (net.set w i a) j b = net.set (net.set w j b) i a := by + funext k + by_cases toI : i = k + · subst toI + have : ¬j = i := fun h => ne h.symm + simp [set, this] + · by_cases toJ : j = k + · subst toJ; simp [set, toI] + · simp [set, toI, toJ] + +/-- One model running on by its own steps keeps the network within what it can reach. -/ +theorem reachable_runs {w : net.Worlds} (reach : net.Reachable w) (i : ι) + {wi' : World (model i).signature} (runs : (model i).Runs (w i) wi') : + net.Reachable (net.set w i wi') := by + induction runs with + | refl => rw [set_self]; exact reach + | step _ step ih => + have := Reachable.step ih (.own _ i _ (by rw [set_same]; exact step)) + rwa [set_set] at this + +/-- Answering the next waiting call keeps the network within what it can reach. -/ +theorem answerNext_reachable {w w' : net.Worlds} (reach : net.Reachable w) + (next : net.answerNext w = some w') : net.Reachable w' := by + unfold answerNext at next + obtain ⟨i, _, next⟩ := List.exists_of_findSome?_eq_some next + obtain ⟨c, _, next⟩ := List.exists_of_findSome?_eq_some next + cases asked : net.ask i c with + | none => simp [asked] at next + | some target => + obtain ⟨j, s⟩ := target + simp only [asked] at next + by_cases same : i = j + · simp [same] at next + · simp only [same, ite_false] at next + obtain ⟨wi, answered, rfl⟩ := Option.map_eq_some_iff.mp next + obtain ⟨fibers, found, rfl⟩ := Option.map_eq_some_iff.mp answered + obtain ⟨before, f, after, k, split, program, rfl⟩ := + (model i).answerGo_split c _ _ _ found + have called := Reachable.step reach (.call w i f before after c k j s split program asked same) + -- then each of the two settles, by its own steps + have settledJ := net.reachable_runs called j + (wi' := (model j).settle Link.fuel ((w j).dispatch s)) + (by rw [set_same]; exact (model j).settle_runs _ _) + rw [set_set, net.set_comm _ i j _ _ same] at settledJ + have settledI := net.reachable_runs settledJ i + (by rw [set_same]; exact (model i).settle_runs Link.fuel _) + rw [set_set, net.set_comm _ j i _ _ (fun h => same h.symm)] at settledI + exact settledI + +theorem settle_reachable (calls : Nat) : ∀ {w : net.Worlds}, net.Reachable w → + net.Reachable (net.settle calls w) := by + induction calls with + | zero => intro w reach; exact reach + | succ calls ih => + intro w reach + unfold settle + cases next : net.answerNext w with + | none => exact reach + | some w' => exact ih (net.answerNext_reachable reach next) + +/-- +A run of allowed moves is within what the network can reach: commands, +decisions, outside answers, redeliveries and time passing, at any of the models. +So whatever is proved of every reachable world holds of the run, in whatever +order it answered. +-/ +theorem run_reachable (moves : List ((i : ι) × Model.Move (model i))) + (allowed : ∀ move ∈ moves, move.2.Allowed) : net.Reachable (net.run moves) := by + unfold run + suffices ∀ (w : net.Worlds), net.Reachable w → net.Reachable (moves.foldl net.play w) from + this _ .start + induction moves with + | nil => intro w reach; exact reach + | cons move rest ih => + intro w reach + refine ih (fun x mem => allowed x (List.mem_cons_of_mem _ mem)) _ ?_ + exact net.settle_reachable _ (net.reachable_runs reach move.1 + ((model move.1).play_runs _ _ _ (allowed move List.mem_cons_self))) + +end Network + +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Engine.lean b/packages/alchemy-lean/Alchemy/Engine.lean new file mode 100644 index 00000000000..a482c88b880 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Engine.lean @@ -0,0 +1,428 @@ +import Alchemy.Model + +/-! +An engine that runs a model in memory: it picks one order for what `Step` +leaves open (oldest event first, then the first fiber that can go on), so a +model can be run, tested and searched. Everything it does is a `Step`. +-/ +namespace Alchemy +namespace Model + +variable (m : Model) + +/-- The first fiber that can take a step takes it. -/ +def tryFibers (w : World m.signature) : + List (Fiber m.signature) → List (Fiber m.signature) → Option (World m.signature) + | _, [] => none + | before, f :: after => + match m.advance w f with + | some (w', fs) => some { w' with fibers := before ++ fs ++ after } + | none => tryFibers w (before ++ [f]) after + +/-- One step, if anything can go on without a caller, an answer or the clock. -/ +def stepOnce (w : World m.signature) : Option (World m.signature) := + match w.inbox with + | e :: rest => some (m.react { w with inbox := rest } e) + | [] => m.tryFibers w [] w.fibers + +/-- Runs until nothing can go on, or the fuel runs out. -/ +def settle (fuel : Nat) (w : World m.signature) : World m.signature := + match fuel with + | 0 => w + | fuel + 1 => + match m.stepOnce w with + | none => w + | some w' => settle fuel w' + +theorem tryFibers_step (w w' : World m.signature) : + ∀ after before, w.fibers = before ++ after → m.tryFibers w before after = some w' → + m.Step w w' := by + intro after + induction after with + | nil => intro before _ h; simp [tryFibers] at h + | cons f after ih => + intro before fibers h + unfold tryFibers at h + split at h + · next w'' fs adv => + cases h + exact .advance w f before after w'' fs fibers adv + · exact ih (before ++ [f]) (by simpa using fibers) h + +theorem stepOnce_step (w w' : World m.signature) (h : m.stepOnce w = some w') : m.Step w w' := by + unfold stepOnce at h + split at h + · next e rest inbox => + cases h + exact .deliver w e [] rest (by simpa using inbox) + · exact m.tryFibers_step w w' w.fibers [] (by simp) h + +/-- What the engine reaches, the deployed model can reach. -/ +theorem settle_reachable (fuel : Nat) : ∀ w, m.Reachable w → m.Reachable (m.settle fuel w) := by + induction fuel with + | zero => intro w h; exact h + | succ fuel ih => + intro w h + unfold settle + split + · exact h + · next w' one => exact ih w' (.step h (m.stepOnce_step w w' one)) + +/-- The calls waiting for an outside system's answer, oldest first. -/ +def waiting (w : World m.signature) : List m.signature.Call := + w.fibers.filterMap fun f => + match f.program with + | .call c _ => some c + | _ => none + +def answerGo (c : m.signature.Call) (reply : m.signature.Reply c) : + List (Fiber m.signature) → Option (List (Fiber m.signature)) + | [] => none + | f :: rest => + match f.program with + | .call c' k => + if h : c = c' then some ({ f with program := k (h ▸ reply) } :: rest) + else (answerGo c reply rest).map (f :: ·) + | _ => (answerGo c reply rest).map (f :: ·) + +/-- Answers the oldest waiting call that is this one. -/ +def answer (w : World m.signature) (c : m.signature.Call) (reply : m.signature.Reply c) : + Option (World m.signature) := + (m.answerGo c reply w.fibers).map fun fibers => { w with fibers } + +/-- The first scheduled command that is due, with what is scheduled before and after it. -/ +def nextDue (now : Time) : List (Time × Send m.signature.aggregates) → + Option (List (Time × Send m.signature.aggregates) × (Time × Send m.signature.aggregates) × + List (Time × Send m.signature.aggregates)) + | [] => none + | x :: rest => + if x.1 ≤ now then some ([], x, rest) + else (nextDue now rest).map fun found => (x :: found.1, found.2.1, found.2.2) + +theorem nextDue_spec (now : Time) : ∀ (schedule before : List (Time × Send m.signature.aggregates)) + (x : Time × Send m.signature.aggregates) (after : List (Time × Send m.signature.aggregates)), + m.nextDue now schedule = some (before, x, after) → + schedule = before ++ x :: after ∧ x.1 ≤ now := by + intro schedule + induction schedule with + | nil => intro _ _ _ h; simp [nextDue] at h + | cons y rest ih => + intro before x after h + unfold nextDue at h + split at h + · next due => cases h; exact ⟨rfl, due⟩ + · obtain ⟨found, inner, eq⟩ := Option.map_eq_some_iff.mp h + obtain ⟨b, z, a⟩ := found + cases eq + obtain ⟨rfl, due⟩ := ih b z a inner + exact ⟨rfl, due⟩ + +/-- Sends the scheduled commands that are due, one at a time, letting each settle. -/ +def fireDue (fuel : Nat) : Nat → World m.signature → World m.signature + | 0, w => w + | count + 1, w => + match m.nextDue w.now w.schedule with + | none => w + | some (before, x, after) => + fireDue fuel count (m.settle fuel ({ w with schedule := before ++ after }.dispatch x.2)) + +/-- Moves the clock on, and sends every scheduled command that is now due. -/ +def pass (fuel : Nat) (w : World m.signature) (duration : Time) : World m.signature := + m.fireDue fuel fuel { w with now := w.now + duration } + +/-- What a caller, an outside system or the clock does to a model. -/ +inductive Move (m : Model) where + | send (s : Send m.signature.aggregates) + | decide (d : Decision m.signature.aggregates) (actor : d.Actor) (c : d.Command) + | answer (c : m.signature.Call) (reply : m.signature.Reply c) + | pass (duration : Time) + /-- A fault: the event at this place in the log reaches the policies again. -/ + | redeliver (seq : Nat) + +/-- The world after a move, once everything that follows from it has run. -/ +def play (fuel : Nat) (w : World m.signature) : Move m → World m.signature + | .send s => m.settle fuel (w.dispatch s) + | .decide d actor c => m.settle fuel (w.decide d actor c) + | .answer c reply => + match m.answer w c reply with + | some w' => m.settle fuel w' + | none => w + | .pass duration => m.pass fuel w duration + | .redeliver seq => + match w.log[seq]? with + | some e => m.settle fuel (m.react w e) + | none => w + +/-- The world after every move, from the start. -/ +def run (moves : List (Move m)) (fuel : Nat := 1000) : World m.signature := + moves.foldl (m.play fuel) (World.start m.signature) + +end Model +end Alchemy + +namespace Alchemy +namespace Model + +variable (m : Model) + +theorem answerGo_split (c : m.signature.Call) (reply : m.signature.Reply c) : + ∀ (fibers fibers' : List (Fiber m.signature)), m.answerGo c reply fibers = some fibers' → + ∃ before f after k, fibers = before ++ f :: after ∧ f.program = .call c k ∧ + fibers' = before ++ { f with program := k reply } :: after := by + intro fibers + induction fibers with + | nil => intro _ h; simp [answerGo] at h + | cons f rest ih => + intro fibers' h + unfold answerGo at h + split at h + · next c' k program => + split at h + · next same => + subst same + cases h + exact ⟨[], f, rest, k, rfl, program, rfl⟩ + · obtain ⟨tail, found, rfl⟩ := Option.map_eq_some_iff.mp h + obtain ⟨before, g, after, k', rfl, program', rfl⟩ := ih tail found + exact ⟨f :: before, g, after, k', rfl, program', rfl⟩ + · obtain ⟨tail, found, rfl⟩ := Option.map_eq_some_iff.mp h + obtain ⟨before, g, after, k', rfl, program', rfl⟩ := ih tail found + exact ⟨f :: before, g, after, k', rfl, program', rfl⟩ + +/-- An answer the engine applies is one an outside system may give. -/ +theorem answer_step (w w' : World m.signature) (c : m.signature.Call) (reply : m.signature.Reply c) + (h : m.answer w c reply = some w') : m.Step w w' := by + obtain ⟨fibers, found, rfl⟩ := Option.map_eq_some_iff.mp h + obtain ⟨before, f, after, k, split, program, rfl⟩ := m.answerGo_split c reply _ _ found + exact .answer w f before after c k reply split program + +/-- Sending an offered command, and letting what follows run, stays within what the model can reach. -/ +theorem play_send_reachable (fuel : Nat) (w : World m.signature) (s : Send m.signature.aggregates) + (offered : m.offered s) (reach : m.Reachable w) : m.Reachable (m.play fuel w (.send s)) := + m.settle_reachable fuel _ (.step reach (.send w s offered)) + +/-- So does an outside system's answer. -/ +theorem play_answer_reachable (fuel : Nat) (w : World m.signature) (c : m.signature.Call) + (reply : m.signature.Reply c) (reach : m.Reachable w) : + m.Reachable (m.play fuel w (.answer c reply)) := by + show m.Reachable (match m.answer w c reply with + | some w' => m.settle fuel w' + | none => w) + split + · next w' h => exact m.settle_reachable fuel _ (.step reach (m.answer_step w w' c reply h)) + · exact reach + +/-- Deciding, and letting what follows run, stays within what the model can reach. -/ +theorem play_decide_reachable (m : Model) (fuel : Nat) (w : World m.signature) + (d : Decision m.signature.aggregates) (mem : d ∈ m.decisions) (actor : d.Actor) (c : d.Command) + (reach : m.Reachable w) : m.Reachable (m.play fuel w (.decide d actor c)) := + m.settle_reachable fuel _ (.step reach (.decide w d actor c mem)) + +end Model +end Alchemy + +namespace Alchemy +namespace Model + +variable (m : Model) + +/-! ## Eventually + +Safety says nothing bad happens. These say something good does: that a model +left to run comes to rest, and what is true of it once it has. +-/ + +/-- Nothing can go on without a caller, an outside answer or the clock. -/ +def AtRest (w : World m.signature) : Prop := m.stepOnce w = none + +theorem settle_atRest (fuel : Nat) (w : World m.signature) (rest : m.AtRest w) : + m.settle fuel w = w := by + cases fuel with + | zero => rfl + | succ fuel => simp [settle, show m.stepOnce w = none from rest] + +/-- +A model comes to rest. Given a measure that every step lowers, running on from +any world reaches one where nothing can go on, within as many steps as the measure. +-/ +theorem comesToRest (measure : World m.signature → Nat) + (lowers : ∀ w w', m.stepOnce w = some w' → measure w' < measure w) : + ∀ fuel w, measure w ≤ fuel → m.AtRest (m.settle fuel w) := by + intro fuel + induction fuel with + | zero => + intro w small + show m.stepOnce w = none + cases step : m.stepOnce w with + | none => rfl + | some w' => have := lowers w w' step; omega + | succ fuel ih => + intro w small + unfold settle + cases step : m.stepOnce w with + | none => exact step + | some w' => + have := lowers w w' step + exact ih w' (by omega) + +/-- +The same, for the worlds of some kind that steps stay within: the measure need +only fall there. +-/ +theorem comesToRestWithin (within : World m.signature → Prop) (measure : World m.signature → Nat) + (stays : ∀ w w', within w → m.stepOnce w = some w' → within w') + (lowers : ∀ w w', within w → m.stepOnce w = some w' → measure w' < measure w) : + ∀ fuel w, within w → measure w ≤ fuel → m.AtRest (m.settle fuel w) := by + intro fuel + induction fuel with + | zero => + intro w inside small + show m.stepOnce w = none + cases step : m.stepOnce w with + | none => rfl + | some w' => have := lowers w w' inside step; omega + | succ fuel ih => + intro w inside small + unfold settle + cases step : m.stepOnce w with + | none => exact step + | some w' => + have := lowers w w' inside step + exact ih w' (stays w w' inside step) (by omega) + +/-- Running on from `w`, the model comes to rest with `P` true. -/ +def Eventually (w : World m.signature) (P : World m.signature → Prop) : Prop := + ∃ steps, m.AtRest (m.settle steps w) ∧ P (m.settle steps w) + +/-- What is true of every world at rest that the model reaches is true eventually, if it comes to rest. -/ +theorem eventually_of_rest {P : World m.signature → Prop} (measure : World m.signature → Nat) + (lowers : ∀ w w', m.stepOnce w = some w' → measure w' < measure w) + (atRest : ∀ w, m.Reachable w → m.AtRest w → P w) + (w : World m.signature) (reach : m.Reachable w) : m.Eventually w P := + ⟨measure w, m.comesToRest measure lowers _ w (Nat.le_refl _), + atRest _ (m.settle_reachable _ w reach) (m.comesToRest measure lowers _ w (Nat.le_refl _))⟩ + +/-- What holds of every reachable world holds eventually, from one that is already at rest. -/ +theorem eventually_now {P : World m.signature → Prop} (w : World m.signature) + (rest : m.AtRest w) (holds : P w) : m.Eventually w P := + ⟨0, rest, holds⟩ + +/-- +A rule about the model once it has settled: every event delivered, and no +policy or saga part-way through or waiting. +-/ +def OnceSettled (P : World m.signature → Prop) : Prop := + ∀ w, m.Reachable w → w.Settled → P w + +/-- A rule that follows from an invariant once nothing is in flight holds once settled. -/ +theorem onceSettled_of_invariant {I P : World m.signature → Prop} + (initially : I (World.start m.signature)) (kept : ∀ w w', I w → m.Step w w' → I w') + (settled : ∀ w, I w → w.Settled → P w) : m.OnceSettled P := + fun w reach rest => settled w (m.worldInvariant initially kept w reach) rest + +end Model +end Alchemy + +namespace Alchemy +namespace Model + +variable (m : Model) + +/-- From one world to another by steps the model can take. -/ +inductive Runs : World m.signature → World m.signature → Prop where + | refl (w) : Runs w w + | step {w w' w''} : Runs w w' → m.Step w' w'' → Runs w w'' + +theorem Runs.trans {m : Model} {a b c : World m.signature} (ab : m.Runs a b) (bc : m.Runs b c) : + m.Runs a c := by + induction bc with + | refl => exact ab + | step _ step ih => exact .step ih step + +/-- The engine's settling is steps the model can take. -/ +theorem settle_runs (fuel : Nat) : ∀ w, m.Runs w (m.settle fuel w) := by + induction fuel with + | zero => intro w; exact .refl w + | succ fuel ih => + intro w + unfold settle + cases one : m.stepOnce w with + | none => exact .refl w + | some w' => exact Runs.trans (.step (.refl w) (m.stepOnce_step w w' one)) (ih w') + +/-- Sending an offered command, and settling, is steps the model can take. -/ +theorem play_send_runs (fuel : Nat) (w : World m.signature) (s : Send m.signature.aggregates) + (offered : m.offered s) : m.Runs w (m.play fuel w (.send s)) := + Runs.trans (.step (.refl w) (.send w s offered)) (m.settle_runs fuel _) + +/-- Firing what is due is steps the model can take. -/ +theorem fireDue_runs (fuel : Nat) : ∀ count w, m.Runs w (m.fireDue fuel count w) := by + intro count + induction count with + | zero => intro w; exact .refl w + | succ count ih => + intro w + unfold fireDue + cases found : m.nextDue w.now w.schedule with + | none => exact .refl w + | some next => + obtain ⟨before, x, after⟩ := next + obtain ⟨split, due⟩ := m.nextDue_spec w.now _ _ _ _ found + exact Runs.trans + (Runs.trans (.step (.refl w) (.fire w x.1 x.2 before after split due)) (m.settle_runs fuel _)) + (ih _) + +/-- What a move needs, to be one the model allows: an offered command, or one of its decisions. -/ +def Move.Allowed {m : Model} : Move m → Prop + | .send s => m.offered s + | .decide d _ _ => d ∈ m.decisions + | _ => True + +/-- Any allowed move, and everything that follows from it, is steps the model can take. -/ +theorem play_runs (fuel : Nat) (w : World m.signature) (move : Move m) (allowed : move.Allowed) : + m.Runs w (m.play fuel w move) := by + cases move with + | send s => exact m.play_send_runs fuel w s allowed + | decide d actor c => + exact Runs.trans (.step (.refl w) (.decide w d actor c allowed)) (m.settle_runs fuel _) + | answer c reply => + show m.Runs w (match m.answer w c reply with + | some w' => m.settle fuel w' + | none => w) + cases answered : m.answer w c reply with + | none => exact .refl w + | some w' => + exact Runs.trans (.step (.refl w) (m.answer_step w w' c reply answered)) (m.settle_runs fuel _) + | pass duration => + exact Runs.trans (.step (.refl w) (.tick w (w.now + duration) (Nat.le_add_right _ _))) + (m.fireDue_runs fuel fuel _) + | redeliver seq => + show m.Runs w (match w.log[seq]? with + | some e => m.settle fuel (m.react w e) + | none => w) + cases found : w.log[seq]? with + | none => exact .refl w + | some e => + exact Runs.trans (.step (.refl w) (.redeliver w e (List.mem_of_getElem? found))) + (m.settle_runs fuel _) + +theorem Runs.reachable {m : Model} {w w' : World m.signature} (runs : m.Runs w w') + (reach : m.Reachable w) : m.Reachable w' := by + induction runs with + | refl => exact reach + | step _ step ih => exact .step ih step + +/-- A run of allowed moves is within what the model can reach. -/ +theorem run_reachable (moves : List (Move m)) (allowed : ∀ move ∈ moves, move.Allowed) + (fuel : Nat := 1000) : m.Reachable (m.run moves fuel) := by + unfold run + suffices ∀ w, m.Reachable w → m.Reachable (moves.foldl (m.play fuel) w) from this _ .start + induction moves with + | nil => intro w reach; exact reach + | cons move rest ih => + intro w reach + exact ih (fun x mem => allowed x (List.mem_cons_of_mem _ mem)) _ + ((m.play_runs fuel w move (allowed move List.mem_cons_self)).reachable reach) + +end Model +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/History.lean b/packages/alchemy-lean/Alchemy/History.lean new file mode 100644 index 00000000000..e26c3fa8b0a --- /dev/null +++ b/packages/alchemy-lean/Alchemy/History.lean @@ -0,0 +1,191 @@ +import Alchemy.Model + +/-! +# What an instance's history says about it + +Rules about one state are lifted by `Model.always`. These lift rules that tie a +state to the events its instance recorded: a quantity that is the sum of what +was recorded, an event that is only ever recorded after another. Each is proved +of the aggregate alone, one command at a time, and holds of every instance in +every world a model can reach. +-/ +namespace Alchemy + +variable {g : Aggregates} + +namespace Recorded + +/-- The events one instance recorded, in order. -/ +def eventsAt (r : Recorded g) (n : g.Name) (id : (g.of n).Id) : List (g.of n).Event := + r.log.filterMap fun e => + if h : e.source = n then (if h ▸ e.id = id then some (h ▸ e.event) else none) else none + +/-- Recording on an instance adds the events to its own, in order. -/ +theorem eventsAt_record_self (r : Recorded g) (time : Time) (n : g.Name) (id : (g.of n).Id) + (es : List (g.of n).Event) : + (r.record time n id es).eventsAt n id = r.eventsAt n id ++ es := by + simp only [eventsAt, record, List.filterMap_append] + congr 1 + have pairs : ∀ pairs : List ((g.of n).Event × Nat), + (pairs.map fun (e, i) => (⟨n, id, e, r.log.length + i, time⟩ : Emitted g)).filterMap + (fun e => if h : e.source = n then (if h ▸ e.id = id then some (h ▸ e.event) else none) + else none) = pairs.map Prod.fst := by + intro pairs + induction pairs with + | nil => rfl + | cons p ps ih => simp_all + rw [pairs] + simp + +/-- Recording on another instance of the same aggregate leaves an instance's events alone. -/ +theorem eventsAt_record_of_ne (r : Recorded g) (time : Time) (n : g.Name) (id id' : (g.of n).Id) + (es : List (g.of n).Event) (h : id ≠ id') : + (r.record time n id es).eventsAt n id' = r.eventsAt n id' := by + simp only [eventsAt, record, List.filterMap_append] + suffices ∀ pairs : List ((g.of n).Event × Nat), + (pairs.map fun (e, i) => (⟨n, id, e, r.log.length + i, time⟩ : Emitted g)).filterMap + (fun e => if h : e.source = n then (if h ▸ e.id = id' then some (h ▸ e.event) else none) + else none) = [] by + rw [this]; simp + intro pairs + induction pairs with + | nil => rfl + | cons p ps ih => simp_all + +/-- Recording on another aggregate leaves an instance's events alone. -/ +theorem eventsAt_record_of_ne_name (r : Recorded g) (time : Time) (n n' : g.Name) + (id : (g.of n).Id) (id' : (g.of n').Id) (es : List (g.of n).Event) (h : n ≠ n') : + (r.record time n id es).eventsAt n' id' = r.eventsAt n' id' := by + simp [eventsAt, record, List.filterMap_append, h] + +end Recorded + +namespace Aggregate + +variable (a : Aggregate) + +/-- +A rule that ties an instance's state to the events it recorded, and that every +accepted command keeps. +-/ +structure Explains (R : a.State → List a.Event → Prop) : Prop where + initially : R a.initial [] + kept : ∀ ctx s c es past, R s past → a.decide ctx s c = .ok es → + R (a.apply s es ctx.now) (past ++ es) + +/-- +A quantity of the state that every accepted command moves by exactly what its +events are worth: a balance, a total charged, a count. +-/ +def Tallies (quantity : a.State → Int) (worth : a.Event → Int) : Prop := + ∀ ctx s c es, a.decide ctx s c = .ok es → + quantity (a.apply s es ctx.now) = quantity s + (es.map worth).sum + +/-- So the quantity is always what it started as, plus the worth of everything recorded. -/ +theorem Tallies.explains {a : Aggregate} {quantity : a.State → Int} {worth : a.Event → Int} + (tallies : a.Tallies quantity worth) : + a.Explains fun s past => quantity s = quantity a.initial + (past.map worth).sum where + initially := by simp + kept := by + intro ctx s c es past h decided + rw [tallies ctx s c es decided, h, List.map_append, List.sum_append] + omega + +/-- In these events, `effect` only comes after `cause`. -/ +def Follows {Event : Type} (cause effect : Event → Prop) (past : List Event) : Prop := + ∀ before e after, past = before ++ e :: after → effect e → ∃ c ∈ before, cause c + +/-- +`effect` is only recorded once `cause` has been. `seen` is how the state shows +that `cause` was recorded: a command records `effect` only on a state that shows +it, and only a `cause` makes a state show it. +-/ +structure Precedes (cause effect : a.Event → Prop) (seen : a.State → Prop) : Prop where + /-- Nothing was recorded on a new instance. -/ + fresh : ¬seen a.initial + /-- `effect` is recorded only where `cause` shows. -/ + guarded : ∀ ctx s c es, a.decide ctx s c = .ok es → ∀ e ∈ es, effect e → seen s + /-- Only a `cause` makes the state show it. -/ + marks : ∀ ctx s c es, a.decide ctx s c = .ok es → seen (a.apply s es ctx.now) → + seen s ∨ ∃ c ∈ es, cause c + +theorem Precedes.explains {a : Aggregate} {cause effect : a.Event → Prop} {seen : a.State → Prop} + (precedes : a.Precedes cause effect seen) : + a.Explains fun s past => (seen s → ∃ c ∈ past, cause c) ∧ Follows cause effect past where + initially := ⟨fun shown => absurd shown precedes.fresh, by + intro before e after split + cases before <;> cases split⟩ + kept := by + intro ctx s c es past ⟨shows, follows⟩ decided + refine ⟨fun shown => ?_, ?_⟩ + · rcases precedes.marks ctx s c es decided shown with before | ⟨x, mem, is⟩ + · obtain ⟨x, mem, is⟩ := shows before + exact ⟨x, List.mem_append_left _ mem, is⟩ + · exact ⟨x, List.mem_append_right _ mem, is⟩ + · intro before e after split isEffect + rcases List.append_eq_append_iff.mp split with ⟨middle, rfl, inNew⟩ | ⟨middle, rfl, inPast⟩ + · obtain ⟨x, mem, is⟩ := shows (precedes.guarded ctx s c es decided e (by rw [inNew]; simp) isEffect) + exact ⟨x, List.mem_append_left _ mem, is⟩ + · cases middle with + | nil => + rw [List.nil_append] at inPast + obtain ⟨x, mem, is⟩ := + shows (precedes.guarded ctx s c es decided e (by rw [← inPast]; simp) isEffect) + exact ⟨x, by simpa using mem, is⟩ + | cons x rest => + cases inPast + exact follows before e rest rfl isEffect + +/-- Any two commands, whoever sends them and when, leave the same state in either order. -/ +def Commutes : Prop := + ∀ (x y : a.Sent) s, a.step y.1 (a.step x.1 s x.2) y.2 = a.step x.1 (a.step y.1 s y.2) x.2 + +/-- So the order commands arrive in does not matter: any reordering leaves the same state. -/ +theorem Commutes.replay_perm {a : Aggregate} (commutes : a.Commutes) {cs cs' : List a.Sent} + (reordered : cs.Perm cs') : ∀ s, a.replay s cs = a.replay s cs' := by + induction reordered with + | nil => intro s; rfl + | cons x _ ih => intro s; exact ih _ + | swap x y rest => intro s; simp only [replay, List.foldl_cons, commutes y x s] + | trans _ _ first second => intro s; exact (first s).trans (second s) + +/-- A command delivered twice in a row leaves what it leaves delivered once. -/ +theorem Idempotent.replay_again {a : Aggregate} (idempotent : a.Idempotent) (x : a.Sent) + (cs : List a.Sent) (s : a.State) : a.replay s (x :: x :: cs) = a.replay s (x :: cs) := by + simp only [replay, List.foldl_cons, idempotent x.2 x.1 s] + +end Aggregate + +namespace Model + +/-- +A rule that ties state to history, proved of one aggregate, holds of every +instance of it in every world a model with no decisions can reach. +-/ +theorem explained (m : Model) (noDecisions : m.decisions = []) (n : m.signature.aggregates.Name) + {R : (m.signature.aggregates.of n).State → List (m.signature.aggregates.of n).Event → Prop} + (explains : (m.signature.aggregates.of n).Explains R) + (w : World m.signature) (reach : m.Reachable w) (id : (m.signature.aggregates.of n).Id) : + R (w.state n id) (w.toRecorded.eventsAt n id) := by + refine m.invariant (rule := fun r => ∀ id, R (r.state n id) (r.eventsAt n id)) + (fun _ => explains.initially) ⟨?_, ?_⟩ w reach id + · intro r now s holds id + obtain ⟨to, actor, command⟩ := s + rcases r.dispatch_cases now ⟨to, actor, command⟩ with same | ⟨es, decided, recorded⟩ + · rw [same]; exact holds id + · rw [recorded] + by_cases here : to = n + · subst here + by_cases this : (m.signature.aggregates.of to).keyOf command = id + · subst this + rw [Recorded.record_state_self, Recorded.eventsAt_record_self] + exact explains.kept ⟨actor, now⟩ _ command es _ (holds _) decided + · rw [Recorded.record_state_of_ne _ _ _ _ _ _ this, Recorded.eventsAt_record_of_ne _ _ _ _ _ _ this] + exact holds id + · rw [Recorded.record_state_of_ne_name _ _ _ _ _ _ _ here, + Recorded.eventsAt_record_of_ne_name _ _ _ _ _ _ _ here] + exact holds id + · rw [noDecisions]; intro d mem; cases mem + +end Model +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Host.lean b/packages/alchemy-lean/Alchemy/Host.lean new file mode 100644 index 00000000000..511a9f598b0 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Host.lean @@ -0,0 +1,164 @@ +import Alchemy.Engine +import Std.Http +import Std.Time +import Lean.Data.Json + +/-! +A host: serves a model over HTTP and keeps it across restarts. + +Everything that changes the model is written to a journal before it is applied: +each request that became a move, each answer an outside system gave, and each +time the clock moved. The engine is a function, so replaying the journal gives +back the same world, with every saga where it was. +-/ +namespace Alchemy + +open Lean (Json) + +/-- A response: a status code, a content type and a body. -/ +structure Reply where + status : Nat := 200 + type : String := "application/json" + body : String + +/-- What a request turns out to be. -/ +inductive Routed (m : Model) where + /-- It changes the model. `respond` is given the world before and after. -/ + | move (move : Model.Move m) (respond : World m.signature → World m.signature → Reply) + /-- It only reads. -/ + | read (respond : World m.signature → Reply) + /-- It is neither. -/ + | refuse (reply : Reply) + +structure Host (m : Model) where + /-- What a request is, from its method, its path with any query, and its body. -/ + route : (method path body : String) → Routed m + /-- Calls an outside system. -/ + adapter : (c : m.signature.Call) → IO (m.signature.Reply c) + /-- An answer as text for the journal, and back. -/ + encodeReply : (c : m.signature.Call) → m.signature.Reply c → String + decodeReply : (c : m.signature.Call) → String → Option (m.signature.Reply c) + +namespace Host + +variable {m : Model} + +/-- One line of the journal. -/ +inductive Entry where + | request (method path body : String) + | answer (reply : String) + | clock (now : Time) + +def Entry.toJson : Entry → Json + | .request method path body => + Json.mkObj [("k", "request"), ("method", method), ("path", path), ("body", body)] + | .answer reply => Json.mkObj [("k", "answer"), ("reply", reply)] + | .clock now => Json.mkObj [("k", "clock"), ("now", now)] + +def Entry.ofLine (line : String) : Option Entry := do + let json ← (Json.parse line).toOption + let kind ← (json.getObjValAs? String "k").toOption + match kind with + | "request" => + pure (.request (← (json.getObjValAs? String "method").toOption) + (← (json.getObjValAs? String "path").toOption) (← (json.getObjValAs? String "body").toOption)) + | "answer" => pure (.answer (← (json.getObjValAs? String "reply").toOption)) + | "clock" => pure (.clock (← (json.getObjValAs? Nat "now").toOption)) + | _ => none + +def fuel : Nat := 100000 + +/-- The world after one journal entry. -/ +def apply (host : Host m) (w : World m.signature) : Entry → World m.signature + | .request method path body => + match host.route method path body with + | .move move _ => m.play fuel w move + | _ => w + | .answer text => + match m.waiting w with + | c :: _ => + match host.decodeReply c text with + | some reply => m.play fuel w (.answer c reply) + | none => w + | [] => w + | .clock now => m.play fuel w (.pass (now - w.now)) + +/-- The world a journal leaves. -/ +def replay (host : Host m) (lines : Array String) : World m.signature := + lines.foldl (fun w line => + match Entry.ofLine line with + | some entry => host.apply w entry + | none => w) (World.start m.signature) + +/-- A model that is being served: its world, and the journal it is kept in. -/ +structure Running (m : Model) where + host : Host m + world : IO.Ref (World m.signature) + journal : System.FilePath + /-- Whether the clock follows the wall clock. Off, time only moves when a move says so. -/ + wallClock : Bool + +/-- Writes an entry to the journal, then applies it. -/ +def Running.commit (r : Running m) (entry : Entry) : IO Unit := do + let handle ← IO.FS.Handle.mk r.journal .append + handle.putStrLn entry.toJson.compress + handle.flush + r.world.modify fun w => r.host.apply w entry + +/-- Calls the outside systems the model is waiting on, until none is left. -/ +partial def Running.answerCalls (r : Running m) : IO Unit := do + match m.waiting (← r.world.get) with + | [] => pure () + | c :: _ => + let reply ← r.host.adapter c + r.commit (.answer (r.host.encodeReply c reply)) + r.answerCalls + +def Running.tick (r : Running m) : IO Unit := do + if r.wallClock then + let now := (← Std.Time.Timestamp.now).toSecondsSinceUnixEpoch.val.toNat + if now > (← r.world.get).now then r.commit (.clock now) + +/-- Handles one request. -/ +def Running.handle (r : Running m) (method path body : String) : IO Reply := do + r.tick + match r.host.route method path body with + | .refuse reply => pure reply + | .read respond => pure (respond (← r.world.get)) + | .move _ respond => + let before ← r.world.get + r.commit (.request method path body) + let after ← r.world.get + r.answerCalls + pure (respond before after) + +open Std.Http Std.Async in +/-- +Serves the model on a port, until the process ends. The journal is replayed +first, so the model is where it was when the process last stopped. It listens on +this machine only, unless `everyone` is set. +-/ +def serve (host : Host m) (journal : System.FilePath) (port : UInt16) + (wallClock : Bool := true) (everyone : Bool := false) : IO Unit := do + let lines ← if ← journal.pathExists then IO.FS.lines journal else pure #[] + let world ← IO.mkRef (host.replay lines) + let r : Running m := { host, world, journal, wallClock } + IO.println s!"{m.name}: replayed {lines.size} journal entries, serving on http://127.0.0.1:{port}" + let lock ← Std.Mutex.new () + let handler := Server.Handler.ofFn fun request => do + let body : String ← request.body.readAll + let reply ← lock.atomically (liftM (r.handle (toString request.line.method) + (toString request.line.uri) body)) + let status : Status := match reply.status with + | 200 => .ok | 400 => .badRequest | 403 => .forbidden | 404 => .notFound + | 409 => .conflict | _ => .internalServerError + let response ← (Response.withStatus status |>.header! "content-type" reply.type).text reply.body + pure response + let task : Async Unit := do + let address : Std.Net.IPv4Addr := if everyone then .ofParts 0 0 0 0 else .ofParts 127 0 0 1 + let server ← Server.serve (.v4 ⟨address, port⟩) handler + server.waitShutdown + task.block + +end Host +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Html.lean b/packages/alchemy-lean/Alchemy/Html.lean new file mode 100644 index 00000000000..f5c55d89c3d --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Html.lean @@ -0,0 +1,75 @@ +/-! +Pages as values: a page is a function of the model, and what a visitor can do +on it is a form that sends a command. +-/ +namespace Alchemy + +inductive Html where + | text (content : String) + | element (tag : String) (attributes : List (String × String)) (children : List Html) + /-- Markup written out as it is. -/ + | raw (markup : String) + +namespace Html + +def escape (s : String) : String := + s.foldl (fun out c => + out ++ match c with + | '<' => "<" + | '>' => ">" + | '&' => "&" + | '"' => """ + | c => c.toString) "" + +partial def render : Html → String + | .text content => escape content + | .raw markup => markup + | .element tag attributes children => + let attrs := attributes.foldl (fun out (k, v) => out ++ s!" {k}=\"{escape v}\"") "" + s!"<{tag}{attrs}>" ++ String.join (children.map render) ++ s!"" + +def el (tag : String) (children : List Html) : Html := .element tag [] children +def h1 (s : String) : Html := el "h1" [.text s] +def h2 (s : String) : Html := el "h2" [.text s] +def p (children : List Html) : Html := el "p" children +def link (href label : String) : Html := .element "a" [("href", href)] [.text label] + +def table (headings : List String) (rows : List (List String)) : Html := + el "table" (el "tr" (headings.map fun h => el "th" [.text h]) :: + rows.map fun row => el "tr" (row.map fun cell => el "td" [.text cell])) + +/-- A form that posts its fields: the hidden ones as given, the others for the visitor to fill. -/ +def form (action : String) (hidden : List (String × String)) (inputs : List (String × String)) + (button : String) : Html := + .element "form" [("method", "post"), ("action", action)] + (hidden.map (fun (k, v) => .element "input" [("type", "hidden"), ("name", k), ("value", v)] []) + ++ inputs.map (fun (name, placeholder) => + .element "input" [("name", name), ("placeholder", placeholder), ("size", "10")] []) + ++ [el "button" [.text button]]) + +def page (title : String) (body : List Html) : String := + "" ++ escape title ++ "" + ++ "" + ++ String.join (body.map render) + +/-- +Keeps a page live: it asks the server how much has been recorded, and loads the +page again when that changes. +-/ +def live (versionPath : String) : Html := + .raw ("") + +/-- The fields of a posted form. -/ +def fields (body : String) : List (String × String) := + (body.splitOn "&").filterMap fun pair => + match pair.splitOn "=" with + | [k, v] => some (k, (v.replace "%3A" ":").replace "+" " ") + | _ => none + +end Html +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Model.lean b/packages/alchemy-lean/Alchemy/Model.lean new file mode 100644 index 00000000000..afdf63f5262 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Model.lean @@ -0,0 +1,549 @@ +import Alchemy.Program +import Alchemy.View + +/-! +A model, and everything a deployed one can do. + +`Step` is one thing that can happen: a caller sends a command, a decision +records on several instances, an event reaches the policies in any order or a +second time, a policy or a saga takes its next step, an outside system answers +anything it may, time passes, a scheduled command fires. A rule proved for every +`Reachable` world holds whatever order those happen in. +-/ +namespace Alchemy + +variable {g : Aggregates} {σ : Signature} + +/-- Replaces one value of a function. -/ +def update {α β : Type} [DecidableEq α] (f : α → β) (a : α) (b : β) : α → β := + fun x => if x = a then b else f x + +/-- The states with one instance's replaced. -/ +def States.set (state : States g) (n : g.Name) (id : (g.of n).Id) (s : (g.of n).State) : + States g := + fun n' id' => + if h : n = n' then + if h ▸ id = id' then h ▸ s else state n' id' + else state n' id' + +/-- Every instance's state, and every event recorded, in order. -/ +structure Recorded (g : Aggregates) where + state : States g + log : List (Emitted g) + +namespace Recorded + +/-- Before anything is recorded. -/ +def start (g : Aggregates) : Recorded g where + state := fun n _ => (g.of n).initial + log := [] + +/-- Records events on one instance. -/ +def record (r : Recorded g) (time : Time) (n : g.Name) (id : (g.of n).Id) + (es : List (g.of n).Event) : Recorded g where + state := r.state.set n id ((g.of n).apply (r.state n id) es time) + log := r.log ++ es.zipIdx.map fun (e, i) => ⟨n, id, e, r.log.length + i, time⟩ + +/-- What a command answers, as things stand. -/ +def outcome (r : Recorded g) (now : Time) (s : Send g) : Answer g s.to := + (g.of s.to).decide ⟨s.actor, now⟩ (r.state s.to ((g.of s.to).keyOf s.command)) s.command + +/-- Sends one command to its instance: records its events, or changes nothing. -/ +def dispatch (r : Recorded g) (now : Time) (s : Send g) : Recorded g := + match r.outcome now s with + | .ok es => r.record now s.to ((g.of s.to).keyOf s.command) es + | .error _ => r + +/-- The instances of one aggregate that recorded anything. -/ +def ids (r : Recorded g) (n : g.Name) : List (g.of n).Id := + (r.log.filterMap fun e => if h : e.source = n then some (h ▸ e.id) else none).eraseDups + +/-- The events one aggregate's instances recorded, in order. -/ +def eventsOf (r : Recorded g) (n : g.Name) : List (g.of n).Event := + r.log.filterMap fun e => if h : e.source = n then some (h ▸ e.event) else none + +def records (r : Recorded g) (time : Time) (rs : List (Record g)) : Recorded g := + rs.foldl (fun r x => r.record time x.to x.id [x.event]) r + +end Recorded + +namespace Recorded + +/-- The instance recorded on has the events applied. -/ +@[simp] theorem record_state_self (r : Recorded g) (time : Time) (n : g.Name) (id : (g.of n).Id) + (es : List (g.of n).Event) : + (r.record time n id es).state n id = (g.of n).apply (r.state n id) es time := by + simp [record, States.set] + +/-- Another instance of the same aggregate is left alone. -/ +theorem record_state_of_ne (r : Recorded g) (time : Time) (n : g.Name) (id id' : (g.of n).Id) + (es : List (g.of n).Event) (h : id ≠ id') : + (r.record time n id es).state n id' = r.state n id' := by + simp [record, States.set, h] + +/-- Another aggregate is left alone. -/ +theorem record_state_of_ne_name (r : Recorded g) (time : Time) (n n' : g.Name) (id : (g.of n).Id) + (id' : (g.of n').Id) (es : List (g.of n).Event) (h : n ≠ n') : + (r.record time n id es).state n' id' = r.state n' id' := by + simp [record, States.set, h] + +/-- A command leaves every other aggregate alone. -/ +theorem dispatch_state_of_ne_name (r : Recorded g) (now : Time) (s : Send g) (n : g.Name) + (id : (g.of n).Id) (h : s.to ≠ n) : (r.dispatch now s).state n id = r.state n id := by + unfold dispatch + split + · exact record_state_of_ne_name _ _ _ _ _ _ _ h + · rfl + +end Recorded + +namespace Recorded + +/-- Recording on an aggregate adds its events to that aggregate's, in order. -/ +theorem eventsOf_record_self (r : Recorded g) (time : Time) (n : g.Name) (id : (g.of n).Id) + (es : List (g.of n).Event) : (r.record time n id es).eventsOf n = r.eventsOf n ++ es := by + simp only [eventsOf, record, List.filterMap_append] + congr 1 + have pairs : ∀ pairs : List ((g.of n).Event × Nat), + (pairs.map fun (e, i) => (⟨n, id, e, r.log.length + i, time⟩ : Emitted g)).filterMap + (fun e => if h : e.source = n then some (h ▸ e.event) else none) = pairs.map Prod.fst := by + intro pairs + induction pairs with + | nil => rfl + | cons p ps ih => simp_all + rw [pairs] + simp + +/-- What recording adds to the log: the old entries, then one for each event, on that instance. -/ +theorem mem_record_log {r : Recorded g} {time : Time} {n : g.Name} {id : (g.of n).Id} + {es : List (g.of n).Event} {e : Emitted g} (h : e ∈ (r.record time n id es).log) : + e ∈ r.log ∨ ∃ x ∈ es, ∃ seq, e = ⟨n, id, x, seq, time⟩ := by + simp only [record, List.mem_append, List.mem_map] at h + rcases h with old | ⟨⟨x, i⟩, mem, rfl⟩ + · exact .inl old + · exact .inr ⟨x, (List.mem_zipIdx mem).1 |> fun _ => by + have := List.fst_mem_of_mem_zipIdx mem + exact this, _, rfl⟩ + +/-- Recording keeps what was in the log. -/ +theorem log_subset_record (r : Recorded g) (time : Time) (n : g.Name) (id : (g.of n).Id) + (es : List (g.of n).Event) : ∃ more, (r.record time n id es).log = r.log ++ more := + ⟨_, rfl⟩ + +/-- Each event recorded is among the entries the recording added. -/ +theorem mem_log_of_recorded (r : Recorded g) (time : Time) (n : g.Name) (id : (g.of n).Id) + (es : List (g.of n).Event) {x : (g.of n).Event} (h : x ∈ es) : + ∃ seq, (⟨n, id, x, seq, time⟩ : Emitted g) ∈ ((r.record time n id es).log).drop r.log.length := by + simp only [record, List.drop_left] + have general : ∀ (k : Nat) (es : List (g.of n).Event), x ∈ es → + ∃ seq, (⟨n, id, x, seq, time⟩ : Emitted g) ∈ + (es.zipIdx k).map fun (e, i) => (⟨n, id, e, r.log.length + i, time⟩ : Emitted g) := by + intro k es + induction es generalizing k with + | nil => intro h; cases h + | cons y ys ih => + intro h + rcases List.mem_cons.mp h with rfl | rest + · exact ⟨r.log.length + k, by simp only [List.zipIdx_cons, List.map_cons]; exact List.mem_cons_self⟩ + · obtain ⟨seq, mem⟩ := ih (k + 1) rest + exact ⟨seq, by simp only [List.zipIdx_cons, List.map_cons]; exact List.mem_cons_of_mem _ mem⟩ + exact general 0 es h + +/-- A command either changes nothing, or records the events it was answered with. -/ +theorem dispatch_cases (r : Recorded g) (now : Time) (s : Send g) : + r.dispatch now s = r ∨ + ∃ es, r.outcome now s = .ok es ∧ + r.dispatch now s = r.record now s.to ((g.of s.to).keyOf s.command) es := by + unfold dispatch + cases h : r.outcome now s with + | ok es => exact .inr ⟨es, rfl, rfl⟩ + | error _ => exact .inl rfl + +/-- Recording on one aggregate leaves another's events alone. -/ +theorem eventsOf_record_of_ne (r : Recorded g) (time : Time) (n n' : g.Name) (id : (g.of n).Id) + (es : List (g.of n).Event) (h : n ≠ n') : (r.record time n id es).eventsOf n' = r.eventsOf n' := by + simp [eventsOf, record, List.filterMap_append, h] + +end Recorded + +/-- +A command decided across several instances at once: it reads any of them, and +records on all of them or on none. +-/ +structure Decision (g : Aggregates) where + name : String + Command : Type + Rejection : Type + Actor : Type + decide : Context Actor → States g → Command → Except Rejection (List (Record g)) + [decEqRejection : DecidableEq Rejection] + +attribute [instance] Decision.decEqRejection + +/-- What a decision leaves. -/ +def Recorded.decide (r : Recorded g) (d : Decision g) (ctx : Context d.Actor) + (c : d.Command) : Recorded g := + match d.decide ctx r.state c with + | .ok rs => r.records ctx.now rs + | .error _ => r + +/-- "Whenever this is recorded, do that." It is given the events recorded before. -/ +structure Policy (σ : Signature) where + name : String + react : List (Emitted σ.aggregates) → Emitted σ.aggregates → Program σ Unit + +namespace Policy + +/-- A policy on one aggregate's events. -/ +def on (name : String) (n : σ.aggregates.Name) + (react : (σ.aggregates.of n).Id → (σ.aggregates.of n).Event → Program σ Unit) : Policy σ where + name := name + react := fun _ e => if h : n = e.source then react (h ▸ e.id) (h ▸ e.event) else .pure () + +/-- A policy on the events a view emits. -/ +def onView (name : String) (v : View σ.aggregates) + (react : v.Key → v.Event → Program σ Unit) : Policy σ where + name := name + react := fun history e => + (v.emittedBy history e).foldr (fun (k, x) rest => react k x >>= fun _ => rest) (.pure ()) + +end Policy + +structure Model where + name : String + signature : Signature + decisions : List (Decision signature.aggregates) := [] + views : List (View signature.aggregates) := [] + policies : List (Policy signature) := [] + projections : List (Projection signature.aggregates) := [] + streams : List (Stream signature.aggregates) := [] + queries : List (Query signature.aggregates) := [] + /-- What a saga's run does. -/ + saga : signature.Saga → signature.SagaInput → Program signature Unit := fun _ _ => .pure () + /-- The commands callers may send: all of them, unless the model says otherwise. -/ + offered : Send signature.aggregates → Prop := fun _ => True + +/-- Where a saga's run stands. -/ +inductive SagaStatus (σ : Signature) where + | notStarted + | running + | completed + | failed (failure : σ.Failure) +deriving DecidableEq + +/-- A program part-way through: a policy's reaction, or a saga's run. -/ +structure Fiber (σ : Signature) where + /-- The saga's run this is, if it is one. -/ + owner : Option σ.Saga + program : Program σ Unit + /-- The commands to send if it fails, newest first. -/ + undo : List (σ.Failure → Send σ.aggregates) + +/-- Everything about a running model. -/ +structure World (σ : Signature) extends Recorded σ.aggregates where + /-- The events not yet delivered to the policies. -/ + inbox : List (Emitted σ.aggregates) + fibers : List (Fiber σ) + sagas : σ.Saga → SagaStatus σ + /-- The signals each run has not yet taken. -/ + signals : σ.Saga → List σ.Signal + /-- The commands to send later, each with when. -/ + schedule : List (Time × Send σ.aggregates) + now : Time + +namespace World + +def start (σ : Signature) : World σ where + toRecorded := .start σ.aggregates + inbox := [] + fibers := [] + sagas := fun _ => .notStarted + signals := fun _ => [] + schedule := [] + now := 0 + +/-- Takes on what was recorded: the new events go to the inbox. -/ +def lift (w : World σ) (r : Recorded σ.aggregates) : World σ := + { w with toRecorded := r, inbox := w.inbox ++ r.log.drop w.log.length } + +def dispatch (w : World σ) (s : Send σ.aggregates) : World σ := + w.lift (w.toRecorded.dispatch w.now s) + +def decide (w : World σ) (d : Decision σ.aggregates) (actor : d.Actor) (c : d.Command) : + World σ := + w.lift (w.toRecorded.decide d ⟨actor, w.now⟩ c) + +/-- Ends a fiber: a saga's run takes the status. -/ +def finish (w : World σ) (owner : Option σ.Saga) (status : SagaStatus σ) : World σ := + match owner with + | none => w + | some saga => { w with sagas := update w.sagas saga status } + +/-- Nothing is left to react to, and nothing is part-way through. -/ +def Settled (w : World σ) : Prop := w.inbox = [] ∧ w.fibers = [] + +end World + +namespace Model + +variable (m : Model) + +/-- A fiber's next step: the world after it, and the fibers that replace it. -/ +def advance (w : World m.signature) (f : Fiber m.signature) : + Option (World m.signature × List (Fiber m.signature)) := + match f.program with + | .pure () => some (w.finish f.owner .completed, []) + | .fail failure => + match f.undo with + | [] => some (w.finish f.owner (.failed failure), []) + | u :: rest => some (w.dispatch (u failure), [{ f with undo := rest }]) + | .send s k => some (w.dispatch s, [{ f with program := k (w.toRecorded.outcome w.now s) }]) + | .call _ _ => none + | .await k => + match f.owner with + | none => none + | some saga => + match w.signals saga with + | [] => none + | signal :: rest => + some ({ w with signals := update w.signals saga rest }, [{ f with program := k signal }]) + | .compensate u k => some (w, [{ f with program := k, undo := u :: f.undo }]) + | .start saga input k => + match w.sagas saga with + | .notStarted => + some ({ w with sagas := update w.sagas saga .running }, + [{ f with program := k }, { owner := some saga, program := m.saga saga input, undo := [] }]) + | _ => some (w, [{ f with program := k }]) + | .signal saga signal k => + some ({ w with signals := update w.signals saga (w.signals saga ++ [signal]) }, + [{ f with program := k }]) + | .schedule after s k => + some ({ w with schedule := w.schedule ++ [(w.now + after, s)] }, [{ f with program := k }]) + +/-- The world with every policy's reaction to one event started. -/ +def react (w : World m.signature) (e : Emitted m.signature.aggregates) : World m.signature := + { w with + fibers := w.fibers ++ m.policies.map fun p => + { owner := none, program := p.react (w.log.take e.seq) e, undo := [] } } + +/-- One thing a deployed model can do. -/ +inductive Step : World m.signature → World m.signature → Prop where + /-- A caller sends a command the model offers. -/ + | send (w) (s : Send m.signature.aggregates) : m.offered s → Step w (w.dispatch s) + /-- A caller sends a command a decision answers. -/ + | decide (w) (d : Decision m.signature.aggregates) (actor : d.Actor) (c : d.Command) : + d ∈ m.decisions → Step w (w.decide d actor c) + /-- An undelivered event reaches the policies, whichever one it is. -/ + | deliver (w) (e) (before after : List (Emitted m.signature.aggregates)) : + w.inbox = before ++ e :: after → + Step w (m.react { w with inbox := before ++ after } e) + /-- An event reaches the policies a second time. -/ + | redeliver (w) (e) : e ∈ w.log → Step w (m.react w e) + /-- A policy or a saga takes its next step, whichever one it is. -/ + | advance (w) (f) (before after : List (Fiber m.signature)) (w') (fs) : + w.fibers = before ++ f :: after → + m.advance w f = some (w', fs) → + Step w { w' with fibers := before ++ fs ++ after } + /-- An outside system answers a call, with anything it may. -/ + | answer (w) (f) (before after : List (Fiber m.signature)) (c) (k) (reply : m.signature.Reply c) : + w.fibers = before ++ f :: after → + f.program = .call c k → + Step w { w with fibers := before ++ { f with program := k reply } :: after } + /-- Time passes. -/ + | tick (w) (time : Time) : w.now ≤ time → Step w { w with now := time } + /-- A scheduled command that is due is sent, whichever one it is. -/ + | fire (w) (due : Time) (s) (before after : List (Time × Send m.signature.aggregates)) : + w.schedule = before ++ (due, s) :: after → + due ≤ w.now → + Step w ({ w with schedule := before ++ after }.dispatch s) + +/-- The worlds a model can get to. -/ +inductive Reachable : World m.signature → Prop where + | start : Reachable (World.start m.signature) + | step {w w'} : Reachable w → Step m w w' → Reachable w' + +/-- What a rule about the record has to survive: a command, and each decision. -/ +structure Kept (rule : Recorded m.signature.aggregates → Prop) : Prop where + dispatch : ∀ r now s, rule r → rule (r.dispatch now s) + decide : ∀ d ∈ m.decisions, ∀ r (ctx : Context d.Actor) c, rule r → rule (r.decide d ctx c) + +theorem advance_recorded {w w' : World m.signature} {f fs} + (h : m.advance w f = some (w', fs)) : + w'.toRecorded = w.toRecorded ∨ ∃ s, w'.toRecorded = w.toRecorded.dispatch w.now s := by + unfold advance at h + split at h + · cases h; left; unfold World.finish; split <;> rfl + · split at h + · cases h; left; unfold World.finish; split <;> rfl + · cases h; right; exact ⟨_, rfl⟩ + · cases h; right; exact ⟨_, rfl⟩ + · cases h + · split at h + · cases h + · split at h + · cases h + · cases h; left; rfl + · cases h; left; rfl + · split at h <;> cases h <;> left <;> rfl + · cases h; left; rfl + · cases h; left; rfl + +/-- +A rule about the record that survives every command and every decision holds in +every world the model can reach: nothing else changes what is recorded. +-/ +theorem invariant {rule : Recorded m.signature.aggregates → Prop} + (initially : rule (.start m.signature.aggregates)) (kept : m.Kept rule) : + ∀ w, m.Reachable w → rule w.toRecorded := by + intro w reach + induction reach with + | start => exact initially + | step _ step ih => + cases step with + | send s _ => exact kept.dispatch _ _ s ih + | decide d actor c mem => exact kept.decide d mem _ _ c ih + | deliver e before after _ => exact ih + | redeliver e _ => exact ih + | advance f before after w' fs _ adv => + rcases m.advance_recorded adv with same | ⟨s, sent⟩ + · show rule w'.toRecorded + rw [same]; exact ih + · show rule w'.toRecorded + rw [sent]; exact kept.dispatch _ _ s ih + | answer f before after c k reply _ _ => exact ih + | tick time _ => exact ih + | fire due s before after _ _ => exact kept.dispatch _ _ s ih + +/-- +A rule about the whole world that every step keeps holds in every world the +model can reach. +-/ +theorem worldInvariant {rule : World m.signature → Prop} (initially : rule (World.start m.signature)) + (kept : ∀ w w', rule w → m.Step w w' → rule w') : ∀ w, m.Reachable w → rule w := by + intro w reach + induction reach with + | start => exact initially + | step _ step ih => exact kept _ _ ih step + +/-- A rule about each instance's state. -/ +abbrev Rule (g : Aggregates) := (n : g.Name) → (g.of n).State → Prop + +/-- Every instance satisfies the rule. -/ +def Holds (P : Rule g) (r : Recorded g) : Prop := + ∀ n id, P n (r.state n id) + +theorem record_holds {P : Rule g} (r : Recorded g) (time : Time) (n : g.Name) + (id : (g.of n).Id) (es : List (g.of n).Event) (h : Holds P r) + (after : P n ((g.of n).apply (r.state n id) es time)) : Holds P (r.record time n id es) := by + intro n' id' + simp only [Recorded.record, States.set] + split + · next same => + subst same + split + · next eq => subst eq; exact after + · exact h _ _ + · exact h _ _ + +theorem dispatch_holds {P : Rule g} (kept : ∀ n, (g.of n).Keeps (P n)) + (r : Recorded g) (now : Time) (s : Send g) (h : Holds P r) : Holds P (r.dispatch now s) := by + unfold Recorded.dispatch + split + · next es eq => exact record_holds r now _ _ es h (kept _ _ _ _ _ (h _ _) eq) + · exact h + +/-- Records keep a rule that each event recorded keeps. -/ +theorem records_holds {P : Rule g} (time : Time) (rs : List (Record g)) + (evolves : ∀ x ∈ rs, (g.of x.to).Evolves (P x.to)) : + ∀ r : Recorded g, Holds P r → Holds P (r.records time rs) := by + unfold Recorded.records + induction rs with + | nil => intro r h; exact h + | cons x rs ih => + intro r h + refine ih (fun y mem => evolves y (List.mem_cons_of_mem _ mem)) _ ?_ + exact record_holds r time _ _ _ h + ((evolves x List.mem_cons_self).apply _ _ _ (h _ _)) + +/-- +A rule each aggregate keeps, and each decision keeps, holds for every instance +in every world the model can reach. +-/ +theorem always {P : Rule m.signature.aggregates} + (initially : ∀ n, P n (m.signature.aggregates.of n).initial) + (kept : ∀ n, (m.signature.aggregates.of n).Keeps (P n)) + (decided : ∀ d ∈ m.decisions, ∀ r (ctx : Context d.Actor) c, + Holds P r → Holds P (r.decide d ctx c)) : + ∀ w, m.Reachable w → Holds P w.toRecorded := + m.invariant (fun n _ => initially n) + { dispatch := fun r now s h => dispatch_holds kept r now s h + decide := decided } + +end Model +end Alchemy + +namespace Alchemy +namespace Model + +/-- +A rule one aggregate keeps holds of every instance of it, in every world a +model with no decisions can reach. +-/ +theorem alwaysAt (m : Model) (noDecisions : m.decisions = []) (n : m.signature.aggregates.Name) + (P : (m.signature.aggregates.of n).State → Prop) + (initially : P (m.signature.aggregates.of n).initial) + (kept : (m.signature.aggregates.of n).Keeps P) + (w : World m.signature) (reach : m.Reachable w) (id : (m.signature.aggregates.of n).Id) : + P (w.state n id) := by + have all := m.always (P := fun n' s => ∀ h : n' = n, P (h ▸ s)) + (by intro n' h; subst h; exact initially) + (by intro n' ctx s c es holds eq h; subst h; exact kept ctx s c es (holds rfl) eq) + (by rw [noDecisions]; intro d mem; cases mem) w reach + exact all n id rfl + +end Model +end Alchemy + +namespace Alchemy +namespace Model + +/-- +A rule one aggregate keeps, and every decision keeps, holds of every instance +of it in every world the model can reach. +-/ +theorem alwaysAtWith (m : Model) (n : m.signature.aggregates.Name) + (P : (m.signature.aggregates.of n).State → Prop) + (initially : P (m.signature.aggregates.of n).initial) + (kept : (m.signature.aggregates.of n).Keeps P) + (decided : ∀ d ∈ m.decisions, ∀ (r : Recorded m.signature.aggregates) (ctx : Context d.Actor) c, + (∀ id, P (r.state n id)) → ∀ id, P ((r.decide d ctx c).state n id)) + (w : World m.signature) (reach : m.Reachable w) (id : (m.signature.aggregates.of n).Id) : + P (w.state n id) := by + have all := m.always (P := fun n' s => ∀ h : n' = n, P (h ▸ s)) + (by intro n' h; subst h; exact initially) + (by intro n' ctx s c es holds eq h; subst h; exact kept ctx s c es (holds rfl) eq) + (by + intro d mem r ctx c holds n' id' h + subst h + exact decided d mem r ctx c (fun id => holds _ id rfl) id') + w reach + exact all n id rfl + +end Model +end Alchemy + +namespace Alchemy +namespace Recorded + +variable {g : Aggregates} + +/-- What recording on one instance does to the states of its aggregate. -/ +theorem record_state (r : Recorded g) (time : Time) (n : g.Name) (id id' : (g.of n).Id) + (es : List (g.of n).Event) : + (r.record time n id es).state n id' + = if id = id' then (g.of n).apply (r.state n id) es time else r.state n id' := by + simp only [record, States.set] + split <;> simp_all + +end Recorded +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Program.lean b/packages/alchemy-lean/Alchemy/Program.lean new file mode 100644 index 00000000000..5d67d08aa7e --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Program.lean @@ -0,0 +1,85 @@ +import Alchemy.Signature + +/-! +What a policy or a saga does, as data: send a command, call an outside system, +wait for a signal, register how to undo a step. Because it is data, the model +can say exactly when each step runs, and a proof can follow it. +-/ +namespace Alchemy + +inductive Program (σ : Signature) (α : Type) where + | pure (a : α) + /-- Stop: the steps registered with `compensate` are undone, newest first. -/ + | fail (failure : σ.Failure) + /-- Send a command, and go on with its answer. -/ + | send (s : Send σ.aggregates) (k : Answer σ.aggregates s.to → Program σ α) + /-- Call an outside system, and go on with whatever it answers. -/ + | call (c : σ.Call) (k : σ.Reply c → Program σ α) + /-- Wait for the next signal sent to this run. -/ + | await (k : σ.Signal → Program σ α) + /-- Register a command to send if the program later fails, given how it failed. -/ + | compensate (undo : σ.Failure → Send σ.aggregates) (k : Program σ α) + /-- Start a saga's run. A run already started is left alone. -/ + | start (saga : σ.Saga) (input : σ.SagaInput) (k : Program σ α) + /-- Tell a saga's run something. -/ + | signal (saga : σ.Saga) (signal : σ.Signal) (k : Program σ α) + /-- Send a command later. -/ + | schedule (after : Time) (s : Send σ.aggregates) (k : Program σ α) + +namespace Program + +variable {σ : Signature} {α β : Type} + +def bind : Program σ α → (α → Program σ β) → Program σ β + | .pure a, f => f a + | .fail e, _ => .fail e + | .send s k, f => .send s fun r => (k r).bind f + | .call c k, f => .call c fun r => (k r).bind f + | .await k, f => .await fun r => (k r).bind f + | .compensate u k, f => .compensate u (k.bind f) + | .start s i k, f => .start s i (k.bind f) + | .signal s x k, f => .signal s x (k.bind f) + | .schedule t s k, f => .schedule t s (k.bind f) + +instance : Monad (Program σ) where + pure := .pure + bind := bind + +/-- Send a command and go on, whatever it answers. -/ +def tell (s : Send σ.aggregates) : Program σ Unit := + .send s fun _ => .pure () + +/-- Send a command; a rejection fails the program with what `explain` makes of it. -/ +def step (s : Send σ.aggregates) + (explain : (σ.aggregates.of s.to).Rejection → σ.Failure) : Program σ Unit := + .send s fun + | .ok _ => .pure () + | .error r => .fail (explain r) + +/-- Send a command and have its answer. -/ +def ask (s : Send σ.aggregates) : Program σ (Answer σ.aggregates s.to) := + .send s .pure + +/-- Call an outside system. -/ +def request (c : σ.Call) : Program σ (σ.Reply c) := + .call c .pure + +/-- Wait for the next signal. -/ +def awaitSignal : Program σ σ.Signal := + .await .pure + +/-- From here on, a failure sends `undo`, given how the program failed. -/ +def undoWith (undo : σ.Failure → Send σ.aggregates) : Program σ Unit := + .compensate undo (.pure ()) + +def startSaga (saga : σ.Saga) (input : σ.SagaInput) : Program σ Unit := + .start saga input (.pure ()) + +def signalSaga (saga : σ.Saga) (signal : σ.Signal) : Program σ Unit := + .signal saga signal (.pure ()) + +def later (after : Time) (s : Send σ.aggregates) : Program σ Unit := + .schedule after s (.pure ()) + +end Program +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Ranking.lean b/packages/alchemy-lean/Alchemy/Ranking.lean new file mode 100644 index 00000000000..43d7f0fa8cb --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Ranking.lean @@ -0,0 +1,372 @@ +import Lean +import Alchemy.Rest +import Alchemy.Behaviour + +/-! +# Coming to rest, found by the checker + +`comes_to_rest Bank` finds what each event, each command and each saga of a +model weighs, and proves with those weights that the model comes to rest. The +weights are searched for: nobody writes a table. +-/ + +namespace Alchemy + +open Lean Elab Tactic Meta + +/-- +The least number an attempt works for, given that nothing below `start` does: +stepped up from there until one works, then closed in on. +-/ +def leastWorking (what : String) (start : Nat) (attempt : Nat → TacticM Unit) (limit : Nat := 4096) : + TacticM Unit := do + let works (k : Nat) : TacticM Bool := do + let saved ← saveState + let ok ← try attempt k; pure true catch _ => pure false + saved.restore + pure ok + if ← works start then + attempt start + return + let mut low := start + let mut step := 1 + let mut high := start + 1 + while !(← works high) do + if high ≥ limit then + -- Run it once more, so the reason it fails is the error shown. + attempt high + throwError "no {what} up to {limit} is enough" + low := high + step := step * 2 + high := high + step + while low + 1 < high do + let middle := (low + high) / 2 + if ← works middle then high := middle else low := middle + attempt high + +/-- Closes a goal `{ n // P n }` with the least `n`, from the one given, the tactics prove `P n` for. -/ +syntax "least_such " "from " num tacticSeq : tactic + +elab_rules : tactic + | `(tactic| least_such from $start $tactics) => + leastWorking "number" start.getNat fun k => do + evalTactic (← `(tactic| (refine ⟨$(quote k), ?_⟩; ($tactics); done))) + +/-- +Gives a program the least rank it has: the goal's rank is left open and filled +in. The rank given is tried first. If it is not enough the program is measured: +walked once with more rank than it could need, to see how much is left over. +-/ +syntax "ranked_least " "from " num ident " [" term,* "]" : tactic + +elab_rules : tactic + | `(tactic| ranked_least from $start $ranking [$sagas,*]) => do + -- Open the program up once, so every `if` in it is in sight. + evalTactic (← `(tactic| try simp only [behaviour])) + let attempt (k : Nat) : TacticM Unit := do + evalTactic (← `(tactic| focus ( + refine Alchemy.Model.Ranked.mono (a := $(quote k)) ?_ (Nat.le_refl _) + ranked $ranking [$sagas,*] + done))) + let saved ← saveState + try + attempt start.getNat + catch _ => + saved.restore + let plenty := 1 <<< 40 + rankLeft.set plenty + attempt plenty + let left ← rankLeft.get + saved.restore + attempt (plenty - left + 1) + +/-- Ranks each reaction to one event, each with the least rank it has. -/ +syntax "reaction_ranks " ident " [" term,* "]" : tactic + +macro_rules + | `(tactic| reaction_ranks $ranking [$sagas,*]) => + `(tactic| focus ( + (repeat' first + | exact Alchemy.Model.Ranking.programs.nil + | (apply Alchemy.Model.Ranking.programs.cons + focus (ranked_least from 0 $ranking [$sagas,*]))) + done)) + +/-- Proves that an event outweighs the reactions to it: `reactions Bank.ranking [Bank.rank_Payout]`. -/ +syntax "reactions " ident " [" term,* "]" : tactic + +macro_rules + | `(tactic| reactions $ranking [$sagas,*]) => + `(tactic| ( + apply Alchemy.Model.Ranking.reacting + reaction_ranks $ranking [$sagas,*] + ranked_fits $ranking)) + +/-- The same, with each reaction's rank given. -/ +syntax "reactions_ranked " ident " [" term,* "]" " [" num,* "]" : tactic + +macro_rules + | `(tactic| reactions_ranked $ranking [$sagas,*] [$ranks,*]) => + `(tactic| ( + refine Alchemy.Model.Ranking.reacting _ (ranks := [$ranks,*]) ?_ ?_ + focus ( + (repeat' first + | exact Alchemy.Model.Ranking.programs.nil + | (apply Alchemy.Model.Ranking.programs.cons + focus (try simp only [behaviour] + ranked $ranking [$sagas,*] + done))) + done) + ranked_fits $ranking)) + +/-- Settles one accepted command: what it records weighs no more than the bound. -/ +syntax "records_fit " ident " [" ident,* "]" : tactic + +macro_rules + | `(tactic| records_fit $accepted [$unfold,*]) => + `(tactic| ( + simp only [$[$unfold:ident],*] at $accepted:ident <;> (repeat' split at $accepted:ident) <;> + first + | (cases $accepted:ident; first | decide | (simp; done) | (simp; omega)) + | (cases $accepted:ident; done))) + +open Command Term + +/-- The constructors of the type a term stands for, each with how many fields it takes. -/ +private def constructorsOf (type : Term) : CommandElabM (Array (Name × Nat)) := + liftTermElabM do + let e ← whnf (← elabType type) + let .const name _ := e.getAppFn + | throwError "{type} is not a type with cases" + let info ← getConstInfoInduct name + info.ctors.toArray.mapM fun c => do return (c, (← getConstInfoCtor c).numFields) + +/-- Names for a constructor's fields. -/ +private def fields (count : Nat) : Array Ident := + (Array.range count).map fun i => mkIdent (Name.mkSimple s!"x{i}") + +/-- Check some commands, run what needs them, and keep nothing. -/ +private def scratch {α : Type} (commands : Array Syntax) (go : CommandElabM α) : CommandElabM α := do + let saved ← get + try + for c in commands do elabCommand c + if (← get).messages.hasErrors then + let texts ← (← get).messages.toList.filterMapM fun m => + if m.severity == .error then some <$> m.data.toString else pure none + throwError "could not set up the search:\n{"\n".intercalate texts}" + go + finally + set saved + +/-- The number a search found: the first part of the pair the term builds. -/ +private def found (term : Term) : CommandElabM Nat := + liftTermElabM <| withoutErrToSorry do + let e ← elabTerm term none + synthesizeSyntheticMVarsNoPostponing + let e ← whnf (← instantiateMVars e) + let some value := e.getAppArgs[2]? + | throwError "the search did not end with a number" + let value ← instantiateMVars value + match ← (evalNat value).run with + | some n => return n + | none => + let .lit (.natVal n) ← whnf value | throwError "the search ended with {value}, not a number" + return n + +/-- +`comes_to_rest Bank` finds the weights and proves: + +* `Bank.ranking`: what each event, command and saga weighs; +* `Bank.reacts`: every event outweighs the reactions to it; +* `Bank.comesToRest`: from any world the model can reach, it stops. +-/ +syntax (name := comesToRest) "comes_to_rest " ident : command + +@[command_elab comesToRest] def elabComesToRest : CommandElab := fun stx => do + let `(comes_to_rest $model) := stx | throwUnsupportedSyntax + let m ← liftCoreM <| realizeGlobalConstNoOverloadWithInfo model + let at_ (n : Name) : Ident := mkIdent (`_root_ ++ m ++ n) + let M : Ident := mkIdent (`_root_ ++ m) + let ranking := at_ `ranking + let eventWeight := at_ `eventWeight + let sendWeight := at_ `sendWeight + let names ← constructorsOf (← `(($M).signature.aggregates.Name)) + -- Every event and every command of every aggregate. + let mut events : Array (Name × Name × Nat) := #[] + let mut commands : Array (Name × Name × Nat) := #[] + let mut decides : Array Ident := #[] + for (a, _) in names do + let A := mkIdent a + for (c, k) in ← constructorsOf (← `((($M).signature.aggregates.of $A).Event)) do + events := events.push (a, c, k) + if c.getPrefix.getPrefix ++ `decide ∉ decides.map (·.getId) then + decides := decides.push (mkIdent (c.getPrefix.getPrefix ++ `decide)) + for (c, k) in ← constructorsOf (← `((($M).signature.aggregates.of $A).Command)) do + commands := commands.push (a, c, k) + -- The sagas: several are named, one is the model's own. + let env ← getEnv + let sagas : Array (Option Name) := + match env.find? (m ++ `Sagas) with + | some (.inductInfo info) => info.ctors.toArray.map some + | _ => #[none] + let sagaRank (s : Option Name) : Ident := + match s with + | some s => at_ (Name.mkSimple s!"rank_{s.getString!}") + | none => at_ `rank_saga + let sagaRun (s : Option Name) : CommandElabM Term := + match s with + | some s => + `(($M).saga ($(mkIdent s), id) ($(mkIdent (m ++ `SagaInput ++ Name.mkSimple s.getString!)) input)) + | none => `(($M).saga id input) + let pattern (c : Name) (k : Nat) : CommandElabM Term := + if k = 0 then `($(mkIdent c)) else `($(mkIdent c) ..) + -- The tables, with the numbers so far. + let tables (E S : Array Nat) (proved : Bool) : CommandElabM (Array Syntax) := do + let eventAlts ← (events.zip E).mapM fun ((a, c, k), n) => do + `(Lean.Parser.Term.matchAltExpr| | $(mkIdent a), $(← pattern c k) => $(quote n)) + let sendAlts ← (commands.zip S).mapM fun ((a, c, k), n) => do + `(Lean.Parser.Term.matchAltExpr| | ⟨$(mkIdent a), _, $(← pattern c k)⟩ => $(quote n)) + let emits ← if proved then + `(by + intro n ctx state command es accepted + cases n <;> cases command <;> records_fit accepted [$decides,*]) + else `(sorry) -- while searching only: what is searched with is never kept + return #[ + ← `(/-- What each event weighs. -/ + @[simp] def $eventWeight : (n : ($M).signature.aggregates.Name) → + (($M).signature.aggregates.of n).Event → Nat + $[$(eventAlts.map fun alt => ⟨alt.raw⟩):matchAlt]*), + ← `(/-- What each command weighs: at least what it records. -/ + @[simp] def $sendWeight : Alchemy.Send ($M).signature.aggregates → Nat + $[$(sendAlts.map fun alt => ⟨alt.raw⟩):matchAlt]*), + ← `(/-- What each event and each command weighs. Found by `comes_to_rest`. -/ + def $ranking : Alchemy.Model.Ranking $M where + event := $eventWeight + send := $sendWeight + emits := $emits)] + -- While searching only: each saga's rank so far, assumed, and never kept. + let assumed (J : Array Nat) : CommandElabM (Array Syntax) := + (sagas.zip J).mapM fun (s, j) => do + `(theorem $(sagaRank s) (id) (input) : + Alchemy.Model.Ranked $ranking $(← sagaRun s) $(quote j) := sorry) + let earlier (i : Nat) : Array Term := (sagas.extract 0 i).map fun s => (sagaRank s : Term) + let all : Array Term := sagas.map fun s => (sagaRank s : Term) + let policies ← liftTermElabM do + let mut list ← whnfR (← elabTerm (← `(($M).policies)) none) + let mut found := #[] + while list.isAppOfArity ``List.cons 3 do + let .const p _ := (list.getArg! 1).getAppFn + | throwError "the policies of {model} are not written as a list of names" + found := found.push p + list ← whnfR (list.getArg! 2) + unless list.isAppOfArity ``List.nil 1 do + throwError "the policies of {model} are not written as a list" + pure found + let weigh (R : Array (Array Nat)) : Array Nat := R.map fun ranks => 1 + ranks.foldl (· + ·) 0 + -- Look for the least numbers that hold together, starting from nothing. Each + -- round starts from what the last one found: the numbers only go up. + let mut R : Array (Array Nat) := events.map fun _ => policies.map fun _ => 0 + let mut S := commands.map fun _ => 0 + let mut J := sagas.map fun _ => 0 + let mut settled := false + let mut growing : Array Name := #[] + for round in [0 : events.size + commands.size + sagas.size + 3] do + let E := weigh R + let S' ← scratch (← tables E S false) do + (commands.zip S).mapM fun ((a, c, k), n) => do + let xs := fields k + found (← `((by least_such from $(quote n) + (intros; rename_i accepted; records_fit accepted [$decides,*]) : + { n : Nat // ∀ ctx state $xs* es, + (($M).signature.aggregates.of $(mkIdent a)).decide ctx state ($(mkIdent c) $xs*) = .ok es → + (es.map ($eventWeight $(mkIdent a))).sum ≤ n }))) + -- What the sagas and reactions weigh follows from what the commands weigh: + -- if those have not moved since the last round, nothing else will. + if round > 0 && S' == S then + settled := true + break + let J' ← scratch ((← tables E S' false) ++ (← assumed J)) do + (Array.range sagas.size).mapM fun i => do + found (← `((⟨_, by intro id input; ranked_least from $(quote J[i]!) $ranking [$(earlier i),*]⟩ : + { j : Nat // ∀ id input, Alchemy.Model.Ranked $ranking $(← sagaRun sagas[i]!) j }))) + let R' ← scratch ((← tables E S' false) ++ (← assumed J')) do + (events.zip R).mapM fun ((a, c, k), ranks) => do + let xs := fields k + (policies.zip ranks).mapM fun (p, r) => do + found (← `((⟨_, by intros; ranked_least from $(quote r) $ranking [$all,*]⟩ : + { r : Nat // ∀ history id $xs* seq time, Alchemy.Model.Ranked $ranking + (($(mkIdent p)).react history ⟨$(mkIdent a), id, $(mkIdent c) $xs*, seq, time⟩) r }))) + growing := ((events.zip (weigh R')).zip E).filterMap fun (((_, c, _), now), before) => + if now != before then some c else none + R := R'; S := S'; J := J' + unless settled do + throwError "{model} may never come to rest: no weights hold together, because some reaction \ + leads back to the event it reacts to. These kept growing: {growing}" + let E := weigh R + -- The numbers hold together: state them, and prove everything with them. + for c in ← tables E S true do elabCommand c + for i in [0:sagas.size] do + elabCommand (← `( + /-- The saga's rank: it takes at most this many steps, whatever it is answered. -/ + theorem $(sagaRank sagas[i]!) (id) (input) : + Alchemy.Model.Ranked $ranking $(← sagaRun sagas[i]!) $(quote J[i]!) := by + try simp only [behaviour] + ranked $ranking [$(earlier i),*])) + -- Each event's case is proved with the ranks found for it. + let mut shapes : Array (Array Nat) := #[] + for ranks in R do + unless shapes.contains ranks do shapes := shapes.push ranks + let cases ← shapes.mapM fun ranks => + `(tactic| reactions_ranked $ranking [$all,*] [$(ranks.map fun r => (quote r : TSyntax `num)),*]) + elabCommand (← `( + /-- Every event weighs more than the reactions to it. -/ + theorem $(at_ `reacts) : Alchemy.Model.Ranking.Reacts $ranking := by + intro history e + obtain ⟨source, id, event, seq, time⟩ := e + cases source <;> cases event <;> first $[| $cases:tactic]*)) + elabCommand (← `( + /-- + The model comes to rest. From any world it can reach, after some number of + steps nothing can go on without a caller, an outside answer or the clock. + -/ + theorem $(at_ `comesToRest) (w : Alchemy.World ($M).signature) (reach : ($M).Reachable w) : + ∃ steps, ($M).AtRest (($M).settle steps w) := + Alchemy.Model.Ranking.comesToRest $ranking $(at_ `reacts) w reach)) + -- When every reaction is calm, the number of steps can be written down too. + let calmly ← `(∀ history e, + Alchemy.Model.AllCalm (m := $M) (($M).policies.map fun p => p.react history e)) + let proof ← `(by + intro history e + obtain ⟨source, id, event, seq, time⟩ := e + cases source <;> cases event <;> + (repeat' first + | exact Alchemy.Model.AllCalm.nil + | (apply Alchemy.Model.AllCalm.cons + focus (calm))) <;> done) + let calm ← liftTermElabM <| withoutErrToSorry do + let saved ← saveState + let messages ← Core.getMessageLog + Core.resetMessageLog + let ok ← try + discard <| elabTermEnsuringType (← `(($proof : $calmly))) none + synthesizeSyntheticMVarsNoPostponing + pure !(← Core.getMessageLog).hasErrors + catch _ => pure false + saved.restore + Core.setMessageLog messages + pure ok + if calm then + elabCommand (← `( + /-- Every reaction only calls outside, tells an aggregate, and ends. -/ + theorem $(at_ `calm) : $calmly := $proof)) + elabCommand (← `( + /-- + How many steps it takes. From any world the model can reach, it is at + rest after as many steps as that world weighs. + -/ + theorem $(at_ `comesToRestIn) (w : Alchemy.World ($M).signature) (reach : ($M).Reachable w) : + ($M).AtRest (($M).settle + ((Alchemy.Model.Ranking.weights $ranking $(at_ `reacts)).measure w) w) := + Alchemy.Model.Ranking.comesToRestIn $ranking $(at_ `reacts) $(at_ `calm) w reach)) + +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Reads.lean b/packages/alchemy-lean/Alchemy/Reads.lean new file mode 100644 index 00000000000..dbb35f722a8 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Reads.lean @@ -0,0 +1,111 @@ +import Alchemy.Refines + +/-! +# Views, kept as they are read + +A view in the model is a function of the whole log. Stored, it is its state +and nothing else: each delivered event changes it once. For a view that looks +at an event as it is, the two are the same, so what a store answers for a view +is what the model says the view is. +-/ +namespace Alchemy + +variable {g : Aggregates} + +/-- A view that looks at an event as it is: not where it sits in the log, nor what came before. -/ +def View.Local (v : View g) : Prop := ∀ history e, v.on history e = v.on [] e.unplaced + +/-- A table whose rows for an event depend on that event alone. -/ +def Projection.Local (p : Projection g) : Prop := + ∀ history e, p.write history e = p.write [] e.unplaced + +/-- A view as it is stored: its state at each key. -/ +def View.reads (v : View g) : ReadSide g where + State := v.Key → v.State + initial := fun _ => v.initial + apply := fun states e key => v.applyAt [] e key (states key) + +/-- A table as it is stored: its rows. -/ +def Projection.reads (p : Projection g) : ReadSide g where + State := List p.Row + initial := [] + apply := fun rows e => rows ++ p.write [] e + +/-- The stored view, after every event, is the view the model computes from the log. -/ +theorem View.reads_exact (v : View g) (plain : v.Local) (log : List (Emitted g)) (key : v.Key) : + ((log.map Emitted.unplaced).foldl v.reads.apply v.reads.initial) key = v.stateAt log key := by + suffices ∀ (rest history : List (Emitted g)) (states : v.reads.State), + ((rest.map Emitted.unplaced).foldl v.reads.apply states) key + = v.go key history rest (states key) from this log [] _ + intro rest + induction rest with + | nil => intro history states; rfl + | cons e rest ih => + intro history states + show (List.foldl v.reads.apply (v.reads.apply states e.unplaced) (rest.map Emitted.unplaced)) key + = v.go key (history ++ [e]) rest (v.applyAt history e key (states key)) + rw [ih (history ++ [e]) (v.reads.apply states e.unplaced)] + show v.go key _ rest (v.applyAt [] e.unplaced key (states key)) = _ + simp only [View.applyAt, plain history e] + +/-- The stored table, after every event, is the table the model computes from the log. -/ +theorem Projection.reads_exact (p : Projection g) (plain : p.Local) (log : List (Emitted g)) : + (log.map Emitted.unplaced).foldl p.reads.apply p.reads.initial = p.table log := by + suffices ∀ (rest history : List (Emitted g)) (rows : p.reads.State), + (rest.map Emitted.unplaced).foldl p.reads.apply rows + = List.append (α := p.Row) rows (p.go history rest) from + (this log [] p.reads.initial).trans (List.nil_append _) + intro rest + induction rest with + | nil => intro history rows; exact (List.append_nil (as := (rows : List p.Row))).symm + | cons e rest ih => + intro history rows + show List.foldl p.reads.apply (p.reads.apply rows e.unplaced) (rest.map Emitted.unplaced) + = List.append (α := p.Row) rows (p.write history e ++ p.go (history ++ [e]) rest) + rw [ih (history ++ [e]) (p.reads.apply rows e.unplaced)] + show List.append (α := p.Row) (List.append (α := p.Row) rows (p.write [] e.unplaced)) _ = _ + rw [plain history e] + exact List.append_assoc _ _ _ + +namespace ReadSide + +/-- Two things read from one model, each kept up on its own. -/ +def both (a b : ReadSide g) : ReadSide g where + State := a.State × b.State + initial := (a.initial, b.initial) + apply := fun s e => (a.apply s.1 e, b.apply s.2 e) + +theorem both_fold (a b : ReadSide g) (events : List (Emitted g)) : + events.foldl (both a b).apply (both a b).initial + = (events.foldl a.apply a.initial, events.foldl b.apply b.initial) := by + suffices ∀ s : a.State × b.State, + events.foldl (both a b).apply s = (events.foldl a.apply s.1, events.foldl b.apply s.2) from + this _ + induction events with + | nil => intro s; rfl + | cons e rest ih => intro s; exact ih _ + +end ReadSide + +/-- What a store answers for something read, once nothing is waiting to be delivered. -/ +theorem Agrees.read_settled {σ : Signature} {reads : ReadSide σ.aggregates} {h : Held σ reads} + {P : Process σ} {w : World σ} (agrees : Agrees h P w) (settled : h.pending = []) : + h.read = (w.log.map Emitted.unplaced).foldl reads.apply reads.initial := by + have empty : w.inbox = [] := by + have := agrees.pending + rw [settled] at this + exact List.map_eq_nil_iff.mp this.symm + rw [agrees.read, World.delivered, empty, List.length_nil, Nat.sub_zero, List.take_length] + +/-- +With nothing waiting to be delivered, what is stored to be read is what the +model computes from everything recorded, in a world the model can reach. +-/ +theorem Model.Stands.read {m : Model} {reads : ReadSide m.signature.aggregates} + {h : Held m.signature reads} (stands : m.Stands h) (settled : h.pending = []) : + ∃ w, m.Reachable w ∧ h.state = w.state ∧ + h.read = (w.log.map Emitted.unplaced).foldl reads.apply reads.initial := by + obtain ⟨w, reach, agrees⟩ := stands + exact ⟨w, reach, agrees.state, agrees.read_settled settled⟩ + +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Refines.lean b/packages/alchemy-lean/Alchemy/Refines.lean new file mode 100644 index 00000000000..be0d2075673 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Refines.lean @@ -0,0 +1,678 @@ +import Alchemy.Stored + +/-! +# The stored engine does only what the model can + +`Agrees` says a store stands for a world: the same states, the same events +waiting, the same things part-way through, the same time. Each thing the +stored engine does, on lawful services, leaves a store that agrees with the +world the model's own engine would reach. So a store the engine has run on +always stands for a world the model can reach, and every rule proved of the +model holds of what is stored. +-/ +namespace Alchemy + +variable {σ : Signature} + +/-- The events delivered so far: all that were recorded but those still waiting. -/ +def World.delivered (w : World σ) : List (Emitted σ.aggregates) := + w.log.take (w.log.length - w.inbox.length) + +/-- A store stands for a world, with this much part-way through in the request at hand. -/ +structure Agrees {reads : ReadSide σ.aggregates} (h : Held σ reads) (P : Process σ) (w : World σ) : + Prop where + state : h.state = w.state + pending : h.pending = w.inbox.map Emitted.unplaced + process : P = w.process + now : h.now = w.now + /-- What is read has taken in every event delivered, in order. -/ + read : h.read = (w.delivered.map Emitted.unplaced).foldl reads.apply reads.initial + /-- The events waiting are the newest recorded, oldest first. -/ + ordered : w.inbox = w.log.drop (w.log.length - w.inbox.length) + +/-- Recording more leaves what was delivered as it was, and the new events wait in order. -/ +theorem World.grown {w w' : World σ} {new : List (Emitted σ.aggregates)} + (ordered : w.inbox = w.log.drop (w.log.length - w.inbox.length)) + (log : w'.log = w.log ++ new) (inbox : w'.inbox = w.inbox ++ new) : + w'.delivered = w.delivered ∧ w'.inbox = w'.log.drop (w'.log.length - w'.inbox.length) := by + have le : w.log.length - w.inbox.length ≤ w.log.length := Nat.sub_le _ _ + have same : w'.log.length - w'.inbox.length = w.log.length - w.inbox.length := by + rw [log, inbox, List.length_append, List.length_append, Nat.add_sub_add_right] + refine ⟨?_, ?_⟩ + · rw [World.delivered, same, log, List.take_append_of_le_length le]; rfl + · rw [same, log, List.drop_append_of_le_length le, ← ordered, inbox] + +/-- Delivering the oldest waiting event adds it to what was delivered. -/ +theorem World.popped {w w' : World σ} {event : Emitted σ.aggregates} + {rest : List (Emitted σ.aggregates)} + (ordered : w.inbox = w.log.drop (w.log.length - w.inbox.length)) + (first : w.inbox = event :: rest) (log : w'.log = w.log) (inbox : w'.inbox = rest) : + w'.delivered = w.delivered ++ [event] ∧ + w'.inbox = w'.log.drop (w'.log.length - w'.inbox.length) := by + have length : w.inbox.length = rest.length + 1 := by rw [first]; rfl + have fits : w.inbox.length ≤ w.log.length := by + have := congrArg List.length ordered + rw [List.length_drop] at this + omega + have next : w'.log.length - w'.inbox.length = (w.log.length - w.inbox.length) + 1 := by + rw [log, inbox]; omega + have head : w.log[w.log.length - w.inbox.length]? = some event := by + rw [← List.head?_drop, ← ordered, first]; rfl + refine ⟨?_, ?_⟩ + · rw [World.delivered, next, log, List.take_add_one, head]; rfl + · rw [next, log, ← List.tail_drop, ← ordered, first, inbox]; rfl + +/-- +Every policy reacts to an event as it is, not to where it sits in the log or +what was recorded before it. A policy on an aggregate's events always does. +-/ +def Model.Local (m : Model) : Prop := + ∀ p ∈ m.policies, ∀ history e, p.react history e = p.react [] e.unplaced + +theorem Policy.on_local (name : String) (n : σ.aggregates.Name) + (react : (σ.aggregates.of n).Id → (σ.aggregates.of n).Event → Program σ Unit) + (history : List (Emitted σ.aggregates)) (e : Emitted σ.aggregates) : + (Policy.on name n react).react history e = (Policy.on name n react).react [] e.unplaced := rfl + +namespace Recorded + +variable {g : Aggregates} + +/-- What recording adds to the log, as a store hands it on. -/ +theorem record_new (r : Recorded g) (time : Time) (n : g.Name) (id : (g.of n).Id) + (es : List (g.of n).Event) : + ((r.record time n id es).log.drop r.log.length).map Emitted.unplaced + = es.map fun e => ⟨n, id, e, 0, time⟩ := by + simp only [record, List.drop_left] + suffices ∀ k, ((es.zipIdx k).map fun (e, i) => (⟨n, id, e, r.log.length + i, time⟩ : Emitted g)).map + Emitted.unplaced = es.map fun e => ⟨n, id, e, 0, time⟩ from this 0 + induction es with + | nil => intro k; rfl + | cons e es ih => intro k; simp only [List.zipIdx_cons, List.map_cons, ih (k + 1)]; rfl + +end Recorded + +namespace World + +/-- A rejected command leaves the world as it was. -/ +theorem dispatch_rejected (w : World σ) (s : Send σ.aggregates) + {rejection : (σ.aggregates.of s.to).Rejection} + (h : w.toRecorded.outcome w.now s = .error rejection) : w.dispatch s = w := by + cases w + simp_all [World.dispatch, Recorded.dispatch, World.lift] + +/-- An accepted command sets its instance's state, and its events wait to be delivered. -/ +theorem dispatch_accepted (w : World σ) (s : Send σ.aggregates) + {events : List (σ.aggregates.of s.to).Event} + (h : w.toRecorded.outcome w.now s = .ok events) : + (w.dispatch s).state = w.state.set s.to ((σ.aggregates.of s.to).keyOf s.command) + ((σ.aggregates.of s.to).apply (w.state s.to ((σ.aggregates.of s.to).keyOf s.command)) + events w.now) ∧ + (w.dispatch s).inbox.map Emitted.unplaced = w.inbox.map Emitted.unplaced ++ + events.map (fun e => ⟨s.to, (σ.aggregates.of s.to).keyOf s.command, e, 0, w.now⟩) ∧ + (w.dispatch s).process = w.process ∧ (w.dispatch s).now = w.now ∧ + ∃ new, (w.dispatch s).log = w.log ++ new ∧ (w.dispatch s).inbox = w.inbox ++ new := by + obtain ⟨more, grew⟩ := w.toRecorded.log_subset_record w.now s.to + ((σ.aggregates.of s.to).keyOf s.command) events + refine ⟨?_, ?_, ?_, ?_, more, ?_, ?_⟩ + · simp [World.dispatch, Recorded.dispatch, h, World.lift, Recorded.record] + · simp only [World.dispatch, Recorded.dispatch, h, World.lift, List.map_append] + rw [Recorded.record_new] + · simp [World.dispatch, Recorded.dispatch, h, World.lift, World.process] + · simp [World.dispatch, Recorded.dispatch, h, World.lift] + · simp only [World.dispatch, Recorded.dispatch, h, World.lift]; exact grew + · simp only [World.dispatch, Recorded.dispatch, h, World.lift] + rw [grew, List.drop_left] + +end World + +namespace Engine + +variable {μ : Type → Type} [Monad μ] {S : Type} {acts : Acts μ S} {m : Model} + {reads : ReadSide m.signature.aggregates} {held : S → Held m.signature reads} {sound : S → Prop} + {e : Engine μ m reads} + +/-- +Sending a command through the stores answers what the model answers, and +leaves a store that agrees with the world the command leaves. +-/ +theorem record_spec (lawful : e.services.Lawful acts held sound) + (s : Send m.signature.aggregates) {st : S} {P : Process m.signature} + {w : World m.signature} (ok : sound st) (agrees : Agrees (held st) P w) : + (acts.eval (e.record s) st).1 = w.toRecorded.outcome w.now s ∧ + Agrees (held (acts.eval (e.record s) st).2) P (w.dispatch s) ∧ + sound (acts.eval (e.record s) st).2 := by + obtain ⟨nowIs, nowHeld, nowSound⟩ := lawful.clock.now st ok + obtain ⟨loadIs, loadHeld, loadSound⟩ := + lawful.store.load s.to ((m.signature.aggregates.of s.to).keyOf s.command) _ nowSound + have time : (acts.eval e.services.clock.now st).1 = w.now := nowIs.trans agrees.now + have loaded : (acts.eval (e.services.store.load s.to + ((m.signature.aggregates.of s.to).keyOf s.command)) (acts.eval e.services.clock.now st).2).1 + = w.state s.to ((m.signature.aggregates.of s.to).keyOf s.command) := by + rw [loadIs, nowHeld]; dsimp only; rw [agrees.state] + simp only [Engine.record, acts.eval_bind] + rw [time, loaded] + cases decided : w.toRecorded.outcome w.now s with + | error rejection => + have same : (m.signature.aggregates.of s.to).decide ⟨s.actor, w.now⟩ + (w.state s.to ((m.signature.aggregates.of s.to).keyOf s.command)) s.command + = .error rejection := decided + simp only [same, acts.eval_pure] + rw [w.dispatch_rejected s decided] + exact ⟨trivial, by rw [loadHeld, nowHeld]; exact agrees, loadSound⟩ + | ok events => + have same : (m.signature.aggregates.of s.to).decide ⟨s.actor, w.now⟩ + (w.state s.to ((m.signature.aggregates.of s.to).keyOf s.command)) s.command + = .ok events := decided + obtain ⟨commitHeld, commitSound⟩ := lawful.store.commit s.to + ((m.signature.aggregates.of s.to).keyOf s.command) + ((m.signature.aggregates.of s.to).apply + (w.state s.to ((m.signature.aggregates.of s.to).keyOf s.command)) events w.now) + events w.now _ loadSound + obtain ⟨state, inbox, process, now, new, log, waiting⟩ := w.dispatch_accepted s decided + obtain ⟨delivered, ordered⟩ := World.grown agrees.ordered log waiting + simp only [same, acts.eval_bind, acts.eval_pure] + refine ⟨trivial, ⟨?_, ?_, ?_, ?_, ?_, ordered⟩, commitSound⟩ + · rw [commitHeld, loadHeld, nowHeld, state]; dsimp only; rw [agrees.state] + · rw [commitHeld, loadHeld, nowHeld, inbox]; dsimp only; rw [agrees.pending] + · rw [process]; exact agrees.process + · rw [commitHeld, loadHeld, nowHeld, now]; exact agrees.now + · rw [commitHeld, loadHeld, nowHeld, delivered]; exact agrees.read + +/-- A change to what is part-way through, with nothing recorded, agrees with the same change to the world. -/ +theorem _root_.Alchemy.Agrees.change {reads : ReadSide σ.aggregates} {h : Held σ reads} + {P P' : Process σ} {w w' : World σ} + (agrees : Agrees h P w) (recorded : w'.toRecorded = w.toRecorded) (inbox : w'.inbox = w.inbox) + (now : w'.now = w.now) (process : P' = w'.process) : Agrees h P' w' := + ⟨by rw [agrees.state, ← recorded], by rw [agrees.pending, inbox], process, by rw [agrees.now, now], + by rw [agrees.read, World.delivered, World.delivered, inbox, recorded], + by rw [inbox, recorded]; exact agrees.ordered⟩ + +/-- The same store, seen through what it holds: agreeing is about what is held. -/ +theorem _root_.Alchemy.Agrees.of_held {reads : ReadSide σ.aggregates} {h h' : Held σ reads} + {P : Process σ} {w : World σ} (agrees : Agrees h P w) (state : h'.state = h.state) + (pending : h'.pending = h.pending) (now : h'.now = h.now) (read : h'.read = h.read) : + Agrees h' P w := + ⟨state ▸ agrees.state, pending ▸ agrees.pending, agrees.process, now ▸ agrees.now, + read ▸ agrees.read, agrees.ordered⟩ + +/-- +A fiber's next step through the stores is its next step in the model: the same +fibers replace it, and the store agrees with the world it leaves. +-/ +theorem advance_spec (lawful : e.services.Lawful acts held sound) (f : Fiber m.signature) + {st : S} {P : Process m.signature} {w : World m.signature} (ok : sound st) + (agrees : Agrees (held st) P w) : + sound (acts.eval (e.advance P f) st).2 ∧ + match m.advance w f with + | none => (acts.eval (e.advance P f) st).1 = none ∧ + Agrees (held (acts.eval (e.advance P f) st).2) P w + | some (w', fs) => ∃ P', (acts.eval (e.advance P f) st).1 = some (P', fs) ∧ + Agrees (held (acts.eval (e.advance P f) st).2) P' w' := by + have process := agrees.process + subst process + unfold Model.advance Engine.advance + cases program : f.program with + | pure a => + cases a + simp only [acts.eval_pure] + refine ⟨ok, _, rfl, agrees.change ?_ ?_ ?_ ?_⟩ <;> cases f.owner <;> rfl + | fail failure => + cases undo : f.undo with + | nil => + simp only [acts.eval_pure] + refine ⟨ok, _, rfl, agrees.change ?_ ?_ ?_ ?_⟩ <;> cases f.owner <;> rfl + | cons u rest => + obtain ⟨_, after, stillSound⟩ := record_spec lawful (u failure) ok agrees + simp only [acts.eval_bind, acts.eval_pure] + exact ⟨stillSound, _, rfl, after⟩ + | send s k => + obtain ⟨answer, after, stillSound⟩ := record_spec lawful s ok agrees + simp only [acts.eval_bind, acts.eval_pure] + rw [answer] + exact ⟨stillSound, _, rfl, after⟩ + | call c k => + simp only [acts.eval_pure] + exact ⟨ok, trivial, agrees⟩ + | await k => + simp only [acts.eval_pure] + cases owner : f.owner with + | none => exact ⟨ok, rfl, agrees⟩ + | some saga => + dsimp only [World.process] + cases signals : w.signals saga with + | nil => + refine ⟨ok, ?_⟩ + first | exact ⟨rfl, agrees⟩ | exact ⟨trivial, agrees⟩ + | cons signal rest => exact ⟨ok, _, rfl, agrees.change rfl rfl rfl rfl⟩ + | compensate u k => + simp only [acts.eval_pure] + exact ⟨ok, _, rfl, agrees⟩ + | start saga input k => + simp only [acts.eval_pure] + dsimp only [World.process] + cases status : w.sagas saga <;> + first + | exact ⟨ok, _, rfl, agrees.change rfl rfl rfl rfl⟩ + | exact ⟨ok, _, rfl, agrees⟩ + | signal saga signal k => + simp only [acts.eval_pure] + exact ⟨ok, _, rfl, agrees.change rfl rfl rfl rfl⟩ + | schedule after s k => + obtain ⟨nowIs, nowHeld, nowSound⟩ := lawful.clock.now st ok + simp only [acts.eval_bind, acts.eval_pure] + rw [nowIs] + dsimp only + rw [agrees.now] + refine ⟨nowSound, _, rfl, ?_⟩ + rw [nowHeld] + exact agrees.change rfl rfl rfl rfl + +/-- The first fiber that can go on through the stores is the first that can in the model. -/ +theorem tryFibers_spec (lawful : e.services.Lawful acts held sound) : + ∀ (after before : List (Fiber m.signature)) {st : S} {P : Process m.signature} + {w : World m.signature}, sound st → Agrees (held st) P w → + sound (acts.eval (e.tryFibers P before after) st).2 ∧ + match m.tryFibers w before after with + | none => (acts.eval (e.tryFibers P before after) st).1 = none ∧ + Agrees (held (acts.eval (e.tryFibers P before after) st).2) P w + | some w' => ∃ P', (acts.eval (e.tryFibers P before after) st).1 = some P' ∧ + Agrees (held (acts.eval (e.tryFibers P before after) st).2) P' w' := by + intro after + induction after with + | nil => + intro before st P w ok agrees + simp only [Engine.tryFibers, Model.tryFibers, acts.eval_pure] + exact ⟨ok, trivial, agrees⟩ + | cons f after ih => + intro before st P w ok agrees + have spec := advance_spec lawful f ok agrees + simp only [Engine.tryFibers, Model.tryFibers, acts.eval_bind] + cases stepped : m.advance w f with + | none => + simp only [stepped] at spec + obtain ⟨stillSound, nothing, same⟩ := spec + simp only [nothing] + exact ih (before ++ [f]) stillSound same + | some next => + obtain ⟨w', fs⟩ := next + simp only [stepped] at spec + obtain ⟨stillSound, P', went, after'⟩ := spec + simp only [went, acts.eval_pure] + exact ⟨stillSound, _, rfl, after'.change rfl rfl rfl (by rw [after'.process]; rfl)⟩ + +/-- One step through the stores is the model's own next step. -/ +theorem stepOnce_spec (lawful : e.services.Lawful acts held sound) (plain : m.Local) + {st : S} {P : Process m.signature} {w : World m.signature} (ok : sound st) + (agrees : Agrees (held st) P w) : + sound (acts.eval (e.stepOnce P) st).2 ∧ + match m.stepOnce w with + | none => (acts.eval (e.stepOnce P) st).1 = none ∧ + Agrees (held (acts.eval (e.stepOnce P) st).2) P w + | some w' => ∃ P', (acts.eval (e.stepOnce P) st).1 = some P' ∧ + Agrees (held (acts.eval (e.stepOnce P) st).2) P' w' := by + obtain ⟨nextIs, nextHeld, nextSound⟩ := lawful.delivery.next st ok + simp only [Engine.stepOnce, Model.stepOnce, acts.eval_bind] + rw [nextIs, agrees.pending] + cases inbox : w.inbox with + | nil => + have same : Agrees (held (acts.eval e.services.delivery.next st).2) P w := by + rw [nextHeld] + exact agrees.of_held rfl (by dsimp only; rw [agrees.pending, inbox]; rfl) rfl rfl + have fibers : P.fibers = w.fibers := by rw [agrees.process]; rfl + simp only [List.map_nil, List.head?_nil] + rw [fibers] + exact tryFibers_spec lawful w.fibers [] nextSound same + | cons event rest => + obtain ⟨projectHeld, projectSound⟩ := lawful.project event.unplaced _ nextSound + obtain ⟨delivered, ordered⟩ := World.popped (w' := m.react { w with inbox := rest } event) + agrees.ordered inbox rfl rfl + simp only [List.map_cons, List.head?_cons, acts.eval_bind, acts.eval_pure] + refine ⟨projectSound, _, rfl, ?_, ?_, ?_, ?_, ?_, ordered⟩ + · rw [projectHeld, nextHeld]; exact agrees.state + · rw [projectHeld, nextHeld]; dsimp only; rw [agrees.pending, inbox]; rfl + · rw [agrees.process] + simp only [World.process, Model.react] + congr 2 + exact List.map_congr_left fun p mem => by rw [plain p mem (w.log.take event.seq) event] + · rw [projectHeld, nextHeld]; exact agrees.now + · rw [projectHeld, nextHeld, delivered] + dsimp only + rw [agrees.read, List.map_append, List.foldl_append] + rfl + +/-- Settling through the stores is the model's own settling. -/ +theorem settle_spec (lawful : e.services.Lawful acts held sound) (plain : m.Local) : + ∀ (fuel : Nat) {st : S} {P : Process m.signature} {w : World m.signature}, sound st → + Agrees (held st) P w → + sound (acts.eval (e.settle fuel P) st).2 ∧ + Agrees (held (acts.eval (e.settle fuel P) st).2) (acts.eval (e.settle fuel P) st).1 + (m.settle fuel w) := by + intro fuel + induction fuel with + | zero => + intro st P w ok agrees + simp only [Engine.settle, Model.settle, acts.eval_pure] + exact ⟨ok, agrees⟩ + | succ fuel ih => + intro st P w ok agrees + have spec := stepOnce_spec lawful plain ok agrees + simp only [Engine.settle, Model.settle, acts.eval_bind] + cases stepped : m.stepOnce w with + | none => + simp only [stepped] at spec + obtain ⟨stillSound, nothing, same⟩ := spec + simp only [nothing, acts.eval_pure] + exact ⟨stillSound, same⟩ + | some w' => + simp only [stepped] at spec + obtain ⟨stillSound, P', went, after⟩ := spec + simp only [went] + exact ih stillSound after + +/-- Answering the calls the model waits on is steps the model can take. -/ +theorem answerCalls_spec (lawful : e.services.Lawful acts held sound) (plain : m.Local) : + ∀ (calls : Nat) {st : S} {P : Process m.signature} {w : World m.signature}, sound st → + Agrees (held st) P w → + ∃ w', m.Runs w w' ∧ sound (acts.eval (e.answerCalls calls P) st).2 ∧ + Agrees (held (acts.eval (e.answerCalls calls P) st).2) + (acts.eval (e.answerCalls calls P) st).1 w' := by + intro calls + induction calls with + | zero => + intro st P w ok agrees + simp only [Engine.answerCalls, acts.eval_pure] + exact ⟨w, .refl w, ok, agrees⟩ + | succ calls ih => + intro st P w ok agrees + unfold Engine.answerCalls + cases waiting : P.waiting with + | nil => + simp only [acts.eval_pure] + exact ⟨w, .refl w, ok, agrees⟩ + | cons c rest => + obtain ⟨callHeld, callSound⟩ := lawful.call c st ok + simp only [acts.eval_bind] + have fibers : P.fibers = w.fibers := by rw [agrees.process]; rfl + cases answered : m.answerGo c (acts.eval (e.services.call c) st).1 P.fibers with + | none => + simp only [acts.eval_pure] + exact ⟨w, .refl w, callSound, by rw [callHeld]; exact agrees⟩ + | some fibers' => + simp only [acts.eval_bind] + have step : m.Step w { w with fibers := fibers' } := + m.answer_step w _ c (acts.eval (e.services.call c) st).1 + (by rw [Model.answer, ← fibers, answered]; rfl) + have same : Agrees (held (acts.eval (e.services.call c) st).2) { P with fibers := fibers' } + { w with fibers := fibers' } := by + rw [callHeld] + exact agrees.change rfl rfl rfl (by rw [agrees.process]; rfl) + obtain ⟨settledSound, settled⟩ := settle_spec lawful plain e.fuel callSound same + obtain ⟨w', runs, endSound, ends⟩ := ih settledSound settled + exact ⟨w', Model.Runs.trans (Model.Runs.trans (.step (.refl w) step) (m.settle_runs _ _)) runs, + endSound, ends⟩ + +/-- Firing what is due through the stores is steps the model can take. -/ +theorem fireDue_spec (lawful : e.services.Lawful acts held sound) (plain : m.Local) : + ∀ (count : Nat) {st : S} {P : Process m.signature} {w : World m.signature}, sound st → + Agrees (held st) P w → + ∃ w', m.Runs w w' ∧ sound (acts.eval (e.fireDue count P) st).2 ∧ + Agrees (held (acts.eval (e.fireDue count P) st).2) + (acts.eval (e.fireDue count P) st).1 w' := by + intro count + induction count with + | zero => + intro st P w ok agrees + simp only [Engine.fireDue, acts.eval_pure] + exact ⟨w, .refl w, ok, agrees⟩ + | succ count ih => + intro st P w ok agrees + obtain ⟨nowIs, nowHeld, nowSound⟩ := lawful.clock.now st ok + have same : Agrees (held (acts.eval e.services.clock.now st).2) P w := by + rw [nowHeld]; exact agrees + have schedule : P.schedule = w.schedule := by rw [agrees.process]; rfl + simp only [Engine.fireDue, acts.eval_bind] + rw [nowIs] + dsimp only + rw [agrees.now, schedule] + cases found : m.nextDue w.now w.schedule with + | none => + simp only [acts.eval_pure] + exact ⟨w, .refl w, nowSound, same⟩ + | some next => + obtain ⟨before, x, after⟩ := next + obtain ⟨split, due⟩ := m.nextDue_spec w.now _ _ _ _ found + have taken : Agrees (held (acts.eval e.services.clock.now st).2) + { P with schedule := before ++ after } { w with schedule := before ++ after } := + same.change rfl rfl rfl (by rw [agrees.process]; rfl) + obtain ⟨_, sent, sentSound⟩ := record_spec lawful x.2 nowSound taken + have sent' : Agrees _ { P with schedule := before ++ after } + ({ w with schedule := before ++ after }.dispatch x.2) := sent + obtain ⟨settledSound, settled⟩ := settle_spec lawful plain e.fuel sentSound sent' + obtain ⟨w', runs, endSound, ends⟩ := ih settledSound settled + simp only [acts.eval_bind] + exact ⟨w', Model.Runs.trans + (Model.Runs.trans (.step (.refl w) (.fire w x.1 x.2 before after split due)) + (m.settle_runs _ _)) runs, + endSound, ends⟩ + +/-- +Sending a command through the stores is steps the model can take: the caller +is answered what the model answers, and the store agrees with where the model ends. +-/ +theorem send_spec (lawful : e.services.Lawful acts held sound) (plain : m.Local) + (s : Send m.signature.aggregates) (offered : m.offered s) {st : S} {w : World m.signature} + (ok : sound st) (agrees : Agrees (held st) (held st).process w) : + ∃ w', m.Runs w w' ∧ sound (acts.eval (e.send s) st).2 ∧ + Agrees (held (acts.eval (e.send s) st).2) (held (acts.eval (e.send s) st).2).process w' ∧ + (acts.eval (e.send s) st).1 = w.toRecorded.outcome w.now s := by + obtain ⟨readIs, readHeld, readSound⟩ := lawful.processes.read st ok + have read : Agrees (held (acts.eval e.services.processes.read st).2) + (acts.eval e.services.processes.read st).1 w := by rw [readHeld, readIs]; exact agrees + obtain ⟨answer, sent, sentSound⟩ := record_spec lawful s readSound read + obtain ⟨settledSound, settled⟩ := settle_spec lawful plain e.fuel sentSound sent + obtain ⟨w', runs, answeredSound, answered⟩ := answerCalls_spec lawful plain e.calls settledSound settled + obtain ⟨keptHeld, keptSound⟩ := lawful.processes.keep _ _ answeredSound + simp only [Engine.send, acts.eval_bind, acts.eval_pure] + refine ⟨w', Model.Runs.trans (Model.Runs.trans (.step (.refl w) (.send w s offered)) + (m.settle_runs _ _)) runs, keptSound, ?_, answer⟩ + rw [keptHeld] + exact answered.of_held rfl rfl rfl rfl + +/-- Waking through the stores is steps the model can take. -/ +theorem wake_spec (lawful : e.services.Lawful acts held sound) (plain : m.Local) {st : S} + {w : World m.signature} (ok : sound st) (agrees : Agrees (held st) (held st).process w) : + ∃ w', m.Runs w w' ∧ sound (acts.eval e.wake st).2 ∧ + Agrees (held (acts.eval e.wake st).2) (held (acts.eval e.wake st).2).process w' := by + obtain ⟨readIs, readHeld, readSound⟩ := lawful.processes.read st ok + have read : Agrees (held (acts.eval e.services.processes.read st).2) + (acts.eval e.services.processes.read st).1 w := by rw [readHeld, readIs]; exact agrees + obtain ⟨w₁, fired, firedSound, firedAgrees⟩ := fireDue_spec lawful plain e.fuel readSound read + obtain ⟨w', runs, answeredSound, answered⟩ := answerCalls_spec lawful plain e.calls firedSound firedAgrees + obtain ⟨keptHeld, keptSound⟩ := lawful.processes.keep _ _ answeredSound + simp only [Engine.wake, acts.eval_bind] + refine ⟨w', Model.Runs.trans fired runs, keptSound, ?_⟩ + rw [keptHeld] + exact answered.of_held rfl rfl rfl rfl + +end Engine + +/-! ## What is stored stands for a world the model can reach -/ + +namespace Model + +variable (m : Model) {reads : ReadSide m.signature.aggregates} + +/-- What the stores hold stands for a world the model can reach. -/ +def Stands (h : Held m.signature reads) : Prop := + ∃ w, m.Reachable w ∧ Agrees h h.process w + +/-- Stores with nothing in them stand for the model before anything happened. -/ +theorem Stands.start : m.Stands (Held.start m.signature reads) := + ⟨World.start m.signature, .start, rfl, rfl, rfl, rfl, rfl, rfl⟩ + +variable {m} + +/-- Time passing leaves the stores standing for a world the model can reach. -/ +theorem Stands.tick {h : Held m.signature reads} (stands : m.Stands h) (time : Time) (later : h.now ≤ time) : + m.Stands { h with now := time } := by + obtain ⟨w, reach, agrees⟩ := stands + exact ⟨{ w with now := time }, .step reach (.tick w time (agrees.now ▸ later)), + agrees.state, agrees.pending, agrees.process, rfl, agrees.read, agrees.ordered⟩ + +/-- +A rule each aggregate keeps holds of every instance the stores hold: of the +state as it is stored, not of a history replayed. +-/ +theorem Stands.always {h : Held m.signature reads} (stands : m.Stands h) + {P : Rule m.signature.aggregates} + (initially : ∀ n, P n (m.signature.aggregates.of n).initial) + (kept : ∀ n, (m.signature.aggregates.of n).Keeps (P n)) + (decided : ∀ d ∈ m.decisions, ∀ r (ctx : Context d.Actor) c, + Holds P r → Holds P (r.decide d ctx c)) + (n : m.signature.aggregates.Name) (id : (m.signature.aggregates.of n).Id) : + P n (h.state n id) := by + obtain ⟨w, reach, agrees⟩ := stands + rw [agrees.state] + exact m.always initially kept decided w reach n id + +/-- A rule one aggregate keeps holds of every instance of it the stores hold. -/ +theorem Stands.alwaysAt {h : Held m.signature reads} (stands : m.Stands h) (noDecisions : m.decisions = []) + (n : m.signature.aggregates.Name) (P : (m.signature.aggregates.of n).State → Prop) + (initially : P (m.signature.aggregates.of n).initial) + (kept : (m.signature.aggregates.of n).Keeps P) (id : (m.signature.aggregates.of n).Id) : + P (h.state n id) := by + obtain ⟨w, reach, agrees⟩ := stands + rw [agrees.state] + exact m.alwaysAt noDecisions n P initially kept w reach id + +end Model + +namespace Engine + +variable {μ : Type → Type} [Monad μ] {S : Type} {acts : Acts μ S} {m : Model} + {reads : ReadSide m.signature.aggregates} {held : S → Held m.signature reads} {sound : S → Prop} + {e : Engine μ m reads} + +/-- +Whatever command is sent, the stores go on standing for a world the model can +reach, and the caller is answered what the aggregate, as stored, decides. +-/ +theorem send_stands (lawful : e.services.Lawful acts held sound) (plain : m.Local) + (s : Send m.signature.aggregates) (offered : m.offered s) {st : S} (ok : sound st) + (stands : m.Stands (held st)) : + m.Stands (held (acts.eval (e.send s) st).2) ∧ sound (acts.eval (e.send s) st).2 ∧ + (acts.eval (e.send s) st).1 = (m.signature.aggregates.of s.to).decide ⟨s.actor, (held st).now⟩ + ((held st).state s.to ((m.signature.aggregates.of s.to).keyOf s.command)) s.command := by + obtain ⟨w, reach, agrees⟩ := stands + obtain ⟨w', runs, stillSound, after, answer⟩ := send_spec lawful plain s offered ok agrees + refine ⟨⟨w', runs.reachable reach, after⟩, stillSound, ?_⟩ + rw [answer, agrees.now, agrees.state] + rfl + +/-- Waking leaves the stores standing for a world the model can reach. -/ +theorem wake_stands (lawful : e.services.Lawful acts held sound) (plain : m.Local) {st : S} + (ok : sound st) (stands : m.Stands (held st)) : + m.Stands (held (acts.eval e.wake st).2) ∧ sound (acts.eval e.wake st).2 := by + obtain ⟨w, reach, agrees⟩ := stands + obtain ⟨w', runs, stillSound, after⟩ := wake_spec lawful plain ok agrees + exact ⟨⟨w', runs.reachable reach, after⟩, stillSound⟩ + +end Engine + +/-! ## Everything a host does -/ + +namespace Engine + +variable {μ : Type → Type} [Monad μ] {S : Type} {m : Model} + {reads : ReadSide m.signature.aggregates} + +/-- From one state of the stores to another, by what a host does with the engine. -/ +inductive Runs (e : Engine μ m reads) (acts : Acts μ S) : S → S → Prop where + | refl (st) : Runs e acts st st + /-- A caller sends a command the model offers. -/ + | send {st st'} (s : Send m.signature.aggregates) : m.offered s → Runs e acts st st' → + Runs e acts st (acts.eval (e.send s) st').2 + /-- The host wakes the model. -/ + | wake {st st'} : Runs e acts st st' → Runs e acts st (acts.eval e.wake st').2 + +variable {acts : Acts μ S} {held : S → Held m.signature reads} {sound : S → Prop} + {e : Engine μ m reads} + +/-- +Whatever a host does with the engine, on services that keep their laws, the +stores go on standing for a world the model can reach. +-/ +theorem Runs.stands (lawful : e.services.Lawful acts held sound) (plain : m.Local) {st st' : S} + (runs : e.Runs acts st st') (ok : sound st) (stands : m.Stands (held st)) : + m.Stands (held st') ∧ sound st' := by + induction runs with + | refl => exact ⟨stands, ok⟩ + | send s offered _ ih => + obtain ⟨after, stillSound, _⟩ := send_stands lawful plain s offered ih.2 ih.1 + exact ⟨after, stillSound⟩ + | wake _ ih => exact wake_stands lawful plain ih.2 ih.1 + +end Engine + +namespace Model + +variable {m : Model} {reads : ReadSide m.signature.aggregates} + +/-- What is true of the states of every world the model can reach is true of what is stored. -/ +theorem Stands.holds {h : Held m.signature reads} (stands : m.Stands h) + {Q : States m.signature.aggregates → Prop} (always : ∀ w, m.Reachable w → Q w.state) : + Q h.state := by + obtain ⟨w, reach, agrees⟩ := stands + rw [agrees.state] + exact always w reach + +end Model + +/-! ## Stores held in memory -/ + +namespace InMemory + +/-- Code that changes a value held in memory. -/ +def acts (S : Type) : Acts (StateM S) S where + eval x s := x.run s + eval_pure _ _ := rfl + eval_bind _ _ _ := rfl + +/-- Every service, on one value in memory. Outside systems answer as `call` says. -/ +def services (σ : Signature) (reads : ReadSide σ.aggregates) (call : (c : σ.Call) → σ.Reply c) : + Services (StateM (Held σ reads)) σ reads where + store := + { load := fun n id => return (← get).state n id + commit := fun n id state events time => modify fun h => + { h with + state := h.state.set n id state + pending := h.pending ++ events.map fun e => ⟨n, id, e, 0, time⟩ } } + delivery := + { next := modifyGet fun h => (h.pending.head?, { h with pending := h.pending.tail }) } + processes := + { read := return (← get).process + keep := fun P => modify fun h => { h with process := P } } + clock := { now := return (← get).now } + call := fun c => pure (call c) + project := fun e => modify fun h => { h with read := reads.apply h.read e } + look := return (← get).read + +/-- They keep every law. -/ +theorem lawful (σ : Signature) (reads : ReadSide σ.aggregates) (call : (c : σ.Call) → σ.Reply c) : + (services σ reads call).Lawful (acts (Held σ reads)) id (fun _ => True) where + store := + { load := fun _ _ _ _ => ⟨rfl, rfl, trivial⟩ + commit := fun _ _ _ _ _ _ _ => ⟨rfl, trivial⟩ } + delivery := { next := fun _ _ => ⟨rfl, rfl, trivial⟩ } + processes := + { read := fun _ _ => ⟨rfl, rfl, trivial⟩ + keep := fun _ _ _ => ⟨rfl, trivial⟩ } + clock := { now := fun _ _ => ⟨rfl, rfl, trivial⟩ } + call := fun _ _ _ => ⟨rfl, trivial⟩ + project := fun _ _ _ => ⟨rfl, trivial⟩ + look := fun _ _ => ⟨rfl, rfl, trivial⟩ + +end InMemory + +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Rest.lean b/packages/alchemy-lean/Alchemy/Rest.lean new file mode 100644 index 00000000000..51af8608b3f --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Rest.lean @@ -0,0 +1,812 @@ +import Lean +import Alchemy.Engine +import Alchemy.Attr + +/-! +# Coming to rest, for models with policies + +A policy that only calls outside and tells aggregates is *calm*: each step it +takes either ends it or sends one command. For a model whose policies are calm, +every running reaction is calm in every world it can reach. That pins down what +one step of the engine can do, which is what a measure needs to be shown to fall. +-/ + +namespace Alchemy + +variable {σ : Signature} + +/-- A reaction that only calls outside, tells aggregates, and ends. -/ +inductive Calm : Program σ Unit → Prop where + | done : Calm (.pure ()) + | tell (s : Send σ.aggregates) : Calm (.send s fun _ => .pure ()) + | call (c : σ.Call) (k : σ.Reply c → Program σ Unit) : (∀ reply, Calm (k reply)) → Calm (.call c k) + +/-- Every reaction part-way through is calm. -/ +def World.Calm (w : World σ) : Prop := ∀ f ∈ w.fibers, Alchemy.Calm f.program + +theorem Calm.answered {c : σ.Call} {k : σ.Reply c → Program σ Unit} (calm : Calm (.call c k)) + (reply : σ.Reply c) : Calm (k reply) := by + cases calm with + | call _ _ each => exact each reply + +namespace Model + +variable (m : Model) + +/-- One step of a calm reaction: it ends, or it sends one command and then ends. -/ +theorem advance_calm {w w' : World m.signature} {f : Fiber m.signature} {fs : List (Fiber m.signature)} + (calm : Calm f.program) (advanced : m.advance w f = some (w', fs)) : + (f.program = .pure () ∧ fs = [] ∧ w'.inbox = w.inbox ∧ w'.fibers = w.fibers) ∨ + ∃ s, f.program = (.send s fun _ => .pure ()) ∧ w' = w.dispatch s ∧ + fs = [{ f with program := .pure () }] := by + unfold advance at advanced + cases calm' : f.program with + | pure u => + rw [calm'] at advanced + cases u + simp only at advanced + cases advanced + refine .inl ⟨rfl, rfl, ?_, ?_⟩ <;> (unfold World.finish; split <;> rfl) + | send s k => + rw [calm'] at calm advanced + cases calm with + | tell _ => + simp only at advanced + cases advanced + exact .inr ⟨s, rfl, rfl, rfl⟩ + | call c k => rw [calm'] at advanced; simp at advanced + | fail _ => rw [calm'] at calm; cases calm + | await _ => rw [calm'] at calm; cases calm + | compensate _ _ => rw [calm'] at calm; cases calm + | start _ _ _ => rw [calm'] at calm; cases calm + | signal _ _ _ => rw [calm'] at calm; cases calm + | schedule _ _ _ => rw [calm'] at calm; cases calm + +/-- What the engine's fiber step is: one fiber, somewhere in the list, takes its step. -/ +theorem tryFibers_split (w w' : World m.signature) : + ∀ after before, m.tryFibers w before after = some w' → + ∃ skipped f rest w'' fs, after = skipped ++ f :: rest ∧ m.advance w f = some (w'', fs) ∧ + w' = { w'' with fibers := before ++ skipped ++ fs ++ rest } := by + intro after + induction after with + | nil => intro before h; simp [tryFibers] at h + | cons f after ih => + intro before h + unfold tryFibers at h + split at h + · next w'' fs adv => + cases h + exact ⟨[], f, after, w'', fs, rfl, adv, by simp⟩ + · obtain ⟨skipped, g, rest, w'', fs, rfl, adv, rfl⟩ := ih (before ++ [f]) h + exact ⟨f :: skipped, g, rest, w'', fs, rfl, adv, by simp⟩ + +theorem dispatch_fibers (w : World m.signature) (s : Send m.signature.aggregates) : + (w.dispatch s).fibers = w.fibers := rfl + +/-- If every policy is calm, one step of the engine keeps every reaction calm. -/ +theorem stepOnce_calm (policies : ∀ p ∈ m.policies, ∀ history e, Calm (p.react history e)) + {w w' : World m.signature} (calm : w.Calm) (step : m.stepOnce w = some w') : w'.Calm := by + unfold stepOnce at step + split at step + · next e rest _ => + cases step + intro f mem + simp only [react, List.mem_append, List.mem_map] at mem + rcases mem with old | ⟨p, mem, rfl⟩ + · exact calm f old + · exact policies p mem _ _ + · obtain ⟨skipped, f, rest, w'', fs, split, adv, rfl⟩ := m.tryFibers_split w w' _ _ step + have fCalm : Calm f.program := calm f (by rw [split]; simp) + intro g mem + simp only [List.nil_append, List.mem_append] at mem + rcases m.advance_calm fCalm adv with ⟨_, rfl, _, _⟩ | ⟨s, _, _, rfl⟩ + · rcases mem with (old | none) | old + · exact calm g (by rw [split]; simp [old]) + · cases none + · exact calm g (by rw [split]; simp [old]) + · rcases mem with (old | new) | old + · exact calm g (by rw [split]; simp [old]) + · simp only [List.mem_singleton] at new; subst new; exact .done + · exact calm g (by rw [split]; simp [old]) + +/-- If every policy is calm and nothing starts a saga, every reachable world is calm. -/ +theorem reachable_calm (policies : ∀ p ∈ m.policies, ∀ history e, Calm (p.react history e)) + (w : World m.signature) (reach : m.Reachable w) : w.Calm := by + induction reach with + | start => intro f mem; cases mem + | step _ step ih => + cases step with + | send s _ => exact ih + | decide d actor c _ => exact ih + | deliver e before after inbox => + intro f mem + simp only [react, List.mem_append, List.mem_map] at mem + rcases mem with old | ⟨p, mem, rfl⟩ + · exact ih f old + · exact policies p mem _ _ + | redeliver e _ => + intro f mem + simp only [react, List.mem_append, List.mem_map] at mem + rcases mem with old | ⟨p, mem, rfl⟩ + · exact ih f old + · exact policies p mem _ _ + | advance f before after w' fs split adv => + have fCalm : Calm f.program := ih f (by rw [split]; simp) + intro g mem + simp only [List.mem_append] at mem + rcases m.advance_calm fCalm adv with ⟨_, rfl, _, _⟩ | ⟨s, _, _, rfl⟩ + · rcases mem with (old | none) | old + · exact ih g (by rw [split]; simp [old]) + · cases none + · exact ih g (by rw [split]; simp [old]) + · rcases mem with (old | new) | old + · exact ih g (by rw [split]; simp [old]) + · simp only [List.mem_singleton] at new; subst new; exact .done + · exact ih g (by rw [split]; simp [old]) + | answer f before after c k reply split program => + have fCalm : Calm f.program := ih f (by rw [split]; simp) + intro g mem + simp only [List.mem_append, List.mem_cons] at mem + rcases mem with old | rfl | old + · exact ih g (by rw [split]; simp [old]) + · rw [program] at fCalm; exact fCalm.answered reply + · exact ih g (by rw [split]; simp [old]) + | tick time _ => exact ih + | fire due s before after _ _ => exact ih + +/-! ## A measure that falls + +Give each event a weight: at least one more than what the policies' reactions +to it weigh. Give each command a weight: at least what the events it records +weigh. Then every step of the engine lowers the total, so the model comes to rest. +-/ + +/-- What a reaction still has to do, given what each command weighs. -/ +def weigh (send : Send m.signature.aggregates → Nat) : Program m.signature Unit → Nat + | .pure _ => 1 + | .send s _ => 2 + send s + | _ => 0 + +/-- Weights for a model's events and commands, with what makes them a measure. -/ +structure Weights where + event : (n : m.signature.aggregates.Name) → (m.signature.aggregates.of n).Event → Nat + send : Send m.signature.aggregates → Nat + /-- An event weighs more than the reactions to it. -/ + reacts : ∀ history (e : Emitted m.signature.aggregates), + 1 + (m.policies.map fun p => m.weigh send (p.react history e)).sum ≤ event e.source e.event + /-- A command weighs at least what it records. -/ + emits : ∀ (n : m.signature.aggregates.Name) (ctx : Context (m.signature.aggregates.of n).Actor) + (state : (m.signature.aggregates.of n).State) (command : (m.signature.aggregates.of n).Command) + (es : List (m.signature.aggregates.of n).Event), + (m.signature.aggregates.of n).decide ctx state command = .ok es → + (es.map (event n)).sum ≤ send ⟨n, ctx.actor, command⟩ + +variable {m} + +/-- What is left to do in a world: the events to deliver and the reactions under way. -/ +def Weights.measure (weights : m.Weights) (w : World m.signature) : Nat := + (w.inbox.map fun e => weights.event e.source e.event).sum + + (w.fibers.map fun f => m.weigh weights.send f.program).sum + +theorem zipIdx_weight {α β : Type} (weight : α → Nat) (make : α × Nat → β) (value : β → Nat) + (same : ∀ a i, value (make (a, i)) = weight a) (es : List α) (start : Nat) : + (((es.zipIdx start).map make).map value).sum = (es.map weight).sum := by + induction es generalizing start with + | nil => rfl + | cons e es ih => + have rest := ih (start + 1) + simp only [List.zipIdx_cons, List.map_cons, List.sum_cons, same] + omega + +/-- Sending a command adds to the inbox no more than the command weighs. -/ +theorem Weights.dispatch_inbox (weights : m.Weights) (w : World m.signature) + (s : Send m.signature.aggregates) : + ((w.dispatch s).inbox.map fun e => weights.event e.source e.event).sum + ≤ (w.inbox.map fun e => weights.event e.source e.event).sum + weights.send s := by + simp only [World.dispatch, World.lift, Recorded.dispatch] + cases outcome : w.toRecorded.outcome w.now s with + | error _ => simp + | ok es => + simp only [Recorded.record, List.drop_left, List.map_append, List.sum_append] + have bound : (es.map (weights.event s.to)).sum ≤ weights.send s := + weights.emits s.to ⟨s.actor, w.now⟩ _ s.command es outcome + rw [zipIdx_weight (weights.event s.to) _ _ (fun _ _ => rfl)] + omega + +/-- Every step of the engine lowers the measure, in a world whose reactions are calm. -/ +theorem Weights.lowers (weights : m.Weights) {w w' : World m.signature} (calm : w.Calm) + (step : m.stepOnce w = some w') : weights.measure w' < weights.measure w := by + unfold stepOnce at step + split at step + · next e rest inbox => + cases step + have bound := weights.reacts (w.log.take e.seq) e + simp only [Weights.measure, react, inbox, List.map_cons, List.sum_cons, List.map_append, + List.sum_append, List.map_map] + have same : ((m.policies.map fun p => m.weigh weights.send (p.react (w.log.take e.seq) e)).sum) + = (List.map ((fun f => m.weigh weights.send f.program) ∘ fun p => + ({ owner := none, program := p.react (List.take e.seq w.log) e, undo := [] } : + Fiber m.signature)) m.policies).sum := rfl + omega + · obtain ⟨skipped, f, rest, w'', fs, split, adv, rfl⟩ := m.tryFibers_split w w' _ _ step + have fCalm : Calm f.program := calm f (by rw [split]; simp) + rcases m.advance_calm fCalm adv with ⟨program, rfl, inbox, _⟩ | ⟨s, program, rfl, rfl⟩ + · simp only [Weights.measure, split, inbox, List.nil_append, List.append_nil, List.map_append, + List.sum_append, List.map_cons, List.sum_cons, program, weigh] + omega + · have bound := weights.dispatch_inbox w s + simp only [Weights.measure, split, List.nil_append, List.map_append, List.sum_append, + List.map_cons, List.sum_cons, List.map_nil, List.sum_nil, program, weigh] at bound ⊢ + omega + +/-- +A model with calm policies and such weights comes to rest: from any world it +can reach, within as many steps as the measure, nothing can go on. +-/ +theorem Weights.comesToRest (weights : m.Weights) + (policies : ∀ p ∈ m.policies, ∀ history e, Calm (p.react history e)) + (w : World m.signature) (reach : m.Reachable w) : + m.AtRest (m.settle (weights.measure w) w) := + m.comesToRestWithin World.Calm weights.measure + (fun _ _ calm step => m.stepOnce_calm policies calm step) + (fun _ _ calm step => weights.lowers calm step) + _ w (m.reachable_calm policies w reach) (Nat.le_refl _) + +/-- So what holds of every reachable world at rest holds eventually, from any reachable world. -/ +theorem Weights.eventually (weights : m.Weights) + (policies : ∀ p ∈ m.policies, ∀ history e, Calm (p.react history e)) + {P : World m.signature → Prop} (atRest : ∀ w, m.Reachable w → m.AtRest w → P w) + (w : World m.signature) (reach : m.Reachable w) : m.Eventually w P := + ⟨weights.measure w, weights.comesToRest policies w reach, + atRest _ (m.settle_reachable _ w reach) (weights.comesToRest policies w reach)⟩ + +/-! ## With sagas + +A saga registers undos, starts runs, waits for signals and may fail. Its +programs branch on what it is answered, so a rank cannot be computed from one: +instead `Ranked p n` says the program can be shown to have rank at most `n`, +whatever it is answered. The same argument then goes through. +-/ + +variable (m) + +/-- Weights for events and commands, as before, for a model whose reactions may do anything. -/ +structure Ranking where + event : (n : m.signature.aggregates.Name) → (m.signature.aggregates.of n).Event → Nat + send : Send m.signature.aggregates → Nat + /-- A command weighs at least what it records. -/ + emits : ∀ (n : m.signature.aggregates.Name) (ctx : Context (m.signature.aggregates.of n).Actor) + (state : (m.signature.aggregates.of n).State) (command : (m.signature.aggregates.of n).Command) + (es : List (m.signature.aggregates.of n).Event), + (m.signature.aggregates.of n).decide ctx state command = .ok es → + (es.map (event n)).sum ≤ send ⟨n, ctx.actor, command⟩ + +variable {m} + +/-- The program has rank at most `t`: it takes at most that many steps, whatever it is answered. -/ +inductive Ranked (ranking : m.Ranking) : Program m.signature Unit → Nat → Prop where + | pure {t} : 1 ≤ t → Ranked ranking (.pure ()) t + | fail {t} (failure) : 1 ≤ t → Ranked ranking (.fail failure) t + | send {t n} (s) (k) : (∀ r, Ranked ranking (k r) n) → 2 + ranking.send s + n ≤ t → + Ranked ranking (.send s k) t + | call {t n} (c) (k) : (∀ r, Ranked ranking (k r) n) → n ≤ t → Ranked ranking (.call c k) t + | await {t n} (k) : (∀ signal, Ranked ranking (k signal) n) → 1 + n ≤ t → + Ranked ranking (.await k) t + | compensate {t n b} (undo) (k) : (∀ failure, ranking.send (undo failure) ≤ b) → + Ranked ranking k n → 3 + b + n ≤ t → Ranked ranking (.compensate undo k) t + | start {t n j} (saga) (input) (k) : Ranked ranking k n → + Ranked ranking (m.saga saga input) j → 1 + n + j ≤ t → Ranked ranking (.start saga input k) t + | signal {t n} (saga) (told) (k) : Ranked ranking k n → 1 + n ≤ t → + Ranked ranking (.signal saga told k) t + | schedule {t n} (after) (s) (k) : Ranked ranking k n → 1 + n ≤ t → + Ranked ranking (.schedule after s k) t + +/-- What the undos a reaction has registered weigh. -/ +inductive Undoing (ranking : m.Ranking) : List (m.signature.Failure → Send m.signature.aggregates) → Nat → Prop where + | nil {t} : Undoing ranking [] t + | cons {t n b} (undo) (rest) : (∀ failure, ranking.send (undo failure) ≤ b) → + Undoing ranking rest n → 2 + b + n ≤ t → Undoing ranking (undo :: rest) t + +/-- A reaction under way has rank at most `r`: its program and its undos together. -/ +def Ranking.fiber (ranking : m.Ranking) (f : Fiber m.signature) (r : Nat) : Prop := + ∃ p u, Ranked ranking f.program p ∧ Undoing ranking f.undo u ∧ p + u ≤ r + +/-- The reactions under way, each with a rank. -/ +inductive Ranking.fibers (ranking : m.Ranking) : List (Fiber m.signature) → Nat → Prop where + | nil : Ranking.fibers ranking [] 0 + | cons {f r fs n} : ranking.fiber f r → Ranking.fibers ranking fs n → + Ranking.fibers ranking (f :: fs) (r + n) + +theorem Ranking.fibers_append (ranking : m.Ranking) {a b : List (Fiber m.signature)} {x y : Nat} + (ha : ranking.fibers a x) (hb : ranking.fibers b y) : ranking.fibers (a ++ b) (x + y) := by + induction ha with + | nil => simpa using hb + | cons hf _ ih => rw [List.cons_append, Nat.add_assoc]; exact .cons hf ih + +theorem Ranking.fibers_split (ranking : m.Ranking) {a : List (Fiber m.signature)} + {f : Fiber m.signature} {b : List (Fiber m.signature)} {n : Nat} + (h : ranking.fibers (a ++ f :: b) n) : + ∃ x r y, ranking.fibers a x ∧ ranking.fiber f r ∧ ranking.fibers b y ∧ n = x + r + y := by + induction a generalizing n with + | nil => + cases h with + | cons hf hb => exact ⟨0, _, _, .nil, hf, hb, by omega⟩ + | cons g a ih => + cases h with + | cons hg rest => + obtain ⟨x, r, y, ha, hf, hb, rfl⟩ := ih rest + exact ⟨_, r, y, .cons hg ha, hf, hb, by omega⟩ + +theorem Ranking.single (ranking : m.Ranking) {f : Fiber m.signature} {r : Nat} + (ranked : ranking.fiber f r) : ranking.fibers [f] r := by + simpa using Ranking.fibers.cons ranked .nil + +/-- What is left to do in a world is at most `n`. -/ +def Ranking.bounds (ranking : m.Ranking) (w : World m.signature) (n : Nat) : Prop := + ∃ fibers, ranking.fibers w.fibers fibers ∧ + (w.inbox.map fun e => ranking.event e.source e.event).sum + fibers ≤ n + +theorem Ranking.dispatch_inbox (ranking : m.Ranking) (w : World m.signature) + (s : Send m.signature.aggregates) : + ((w.dispatch s).inbox.map fun e => ranking.event e.source e.event).sum + ≤ (w.inbox.map fun e => ranking.event e.source e.event).sum + ranking.send s := by + simp only [World.dispatch, World.lift, Recorded.dispatch] + cases outcome : w.toRecorded.outcome w.now s with + | error _ => simp + | ok es => + simp only [Recorded.record, List.drop_left, List.map_append, List.sum_append] + have bound : (es.map (ranking.event s.to)).sum ≤ ranking.send s := + ranking.emits s.to ⟨s.actor, w.now⟩ _ s.command es outcome + rw [zipIdx_weight (ranking.event s.to) _ _ (fun _ _ => rfl)] + omega + +/-- One step of one reaction lowers what is left: its own rank and the inbox, against what replaces it. -/ +theorem Ranking.advance (ranking : m.Ranking) {w w' : World m.signature} {f : Fiber m.signature} + {fs : List (Fiber m.signature)} {r : Nat} (ranked : ranking.fiber f r) + (advanced : m.advance w f = some (w', fs)) : + ∃ after, ranking.fibers fs after ∧ + (w'.inbox.map fun e => ranking.event e.source e.event).sum + after + < (w.inbox.map fun e => ranking.event e.source e.event).sum + r := by + obtain ⟨p, u, program, undos, total⟩ := ranked + have finished : ∀ owner status, (w.finish owner status).inbox = w.inbox := by + intro owner status; unfold World.finish; split <;> rfl + unfold Model.advance at advanced + cases shape : f.program with + | pure x => + rw [shape] at program advanced + cases x + cases program with + | pure one => + simp only at advanced + cases advanced + exact ⟨0, .nil, by rw [finished]; omega⟩ + | fail failure => + rw [shape] at program advanced + cases program with + | fail _ one => + simp only at advanced + cases undoList : f.undo with + | nil => + rw [undoList] at advanced + cases advanced + exact ⟨0, .nil, by rw [finished]; omega⟩ + | cons undo rest => + rw [undoList] at advanced undos + cases advanced + cases undos with + | cons _ _ small restUndos fits => + have grown := ranking.dispatch_inbox w (undo failure) + have := small failure + refine ⟨p + _, ranking.single (f := { f with program := .fail failure, undo := rest }) + ⟨p, _, .fail failure one, restUndos, Nat.le_refl _⟩, ?_⟩ + omega + | send s k => + rw [shape] at program advanced + cases program with + | send _ _ each fits => + simp only at advanced + cases advanced + have grown := ranking.dispatch_inbox w s + refine ⟨_ + u, ranking.single (f := { f with program := k (w.toRecorded.outcome w.now s) }) ⟨_, u, each _, undos, Nat.le_refl _⟩, ?_⟩ + omega + | call c k => rw [shape] at advanced; simp at advanced + | await k => + rw [shape] at program advanced + cases program with + | await _ each fits => + simp only at advanced + cases owner : f.owner with + | none => rw [owner] at advanced; simp at advanced + | some saga => + rw [owner] at advanced + simp only at advanced + cases signals : w.signals saga with + | nil => rw [signals] at advanced; simp at advanced + | cons told rest => + rw [signals] at advanced + cases advanced + refine ⟨_ + u, ranking.single (f := { f with owner := some saga, program := k told }) + ⟨_, u, each told, undos, Nat.le_refl _⟩, ?_⟩ + simp only + omega + | compensate undo k => + rw [shape] at program advanced + cases program with + | compensate _ _ small rest fits => + simp only at advanced + cases advanced + refine ⟨_ + (2 + _ + u), ranking.single (f := { f with program := k, undo := undo :: f.undo }) ⟨_, 2 + _ + u, rest, .cons undo f.undo small undos (Nat.le_refl _), Nat.le_refl _⟩, ?_⟩ + omega + | start saga input k => + rw [shape] at program advanced + cases program with + | start _ _ _ rest run fits => + simp only at advanced + cases status : w.sagas saga with + | notStarted => + rw [status] at advanced + cases advanced + refine ⟨(_ + u) + (_ + 0), .cons (f := { f with program := k }) + ⟨_, u, rest, undos, Nat.le_refl _⟩ (.cons + (f := { owner := some saga, program := m.saga saga input, undo := [] }) + ⟨_, 0, run, .nil, Nat.le_refl _⟩ .nil), ?_⟩ + simp only + omega + | running | completed | failed _ => + rw [status] at advanced + cases advanced + refine ⟨_ + u, ranking.single (f := { f with program := k }) ⟨_, u, rest, undos, Nat.le_refl _⟩, ?_⟩ + omega + | signal saga told k => + rw [shape] at program advanced + cases program with + | signal _ _ _ rest fits => + simp only at advanced + cases advanced + refine ⟨_ + u, ranking.single (f := { f with program := k }) ⟨_, u, rest, undos, Nat.le_refl _⟩, ?_⟩ + simp only + omega + | schedule after s k => + rw [shape] at program advanced + cases program with + | schedule _ _ _ rest fits => + simp only at advanced + cases advanced + refine ⟨_ + u, ranking.single (f := { f with program := k }) ⟨_, u, rest, undos, Nat.le_refl _⟩, ?_⟩ + simp only + omega + +/-- An event weighs more than the reactions to it, each of which has a rank. -/ +def Ranking.Reacts (ranking : m.Ranking) : Prop := + ∀ history (e : Emitted m.signature.aggregates), ∃ total, + ranking.fibers (m.policies.map fun p => { owner := none, program := p.react history e, undo := [] }) + total ∧ 1 + total ≤ ranking.event e.source e.event + +theorem Ranking.bounds_mono (ranking : m.Ranking) {w : World m.signature} {n n' : Nat} + (bound : ranking.bounds w n) (le : n ≤ n') : ranking.bounds w n' := by + obtain ⟨fibers, ranked, fits⟩ := bound + exact ⟨fibers, ranked, by omega⟩ + +/-- Every step of the engine lowers what is left to do. -/ +theorem Ranking.lowers (ranking : m.Ranking) (reacts : ranking.Reacts) {w w' : World m.signature} + {n : Nat} (bound : ranking.bounds w n) (step : m.stepOnce w = some w') : + ∃ n', n' < n ∧ ranking.bounds w' n' := by + obtain ⟨total, ranked, fits⟩ := bound + unfold stepOnce at step + split at step + · next e rest inbox => + cases step + obtain ⟨added, reactions, less⟩ := reacts (w.log.take e.seq) e + refine ⟨n - 1, ?_, total + added, ranking.fibers_append ranked reactions, ?_⟩ + · simp only [inbox, List.map_cons, List.sum_cons] at fits; omega + · simp only [react, inbox, List.map_cons, List.sum_cons] at fits ⊢ + omega + · obtain ⟨skipped, f, rest, w'', fs, split, adv, rfl⟩ := m.tryFibers_split w w' _ _ step + rw [split] at ranked + obtain ⟨x, r, y, before, fiber, after, rfl⟩ := ranking.fibers_split ranked + obtain ⟨replaced, new, less⟩ := ranking.advance fiber adv + refine ⟨n - 1, by omega, x + replaced + y, ?_, ?_⟩ + · simpa [List.append_assoc] using + ranking.fibers_append (ranking.fibers_append before new) after + · simp only; omega + +/-- So within as many steps as are left to do, nothing can go on. -/ +theorem Ranking.rest (ranking : m.Ranking) (reacts : ranking.Reacts) : + ∀ n (w : World m.signature), ranking.bounds w n → m.AtRest (m.settle n w) := by + intro n + induction n with + | zero => + intro w bound + show m.stepOnce w = none + cases step : m.stepOnce w with + | none => rfl + | some w' => obtain ⟨n', less, _⟩ := ranking.lowers reacts bound step; omega + | succ n ih => + intro w bound + unfold settle + cases step : m.stepOnce w with + | none => exact step + | some w' => + obtain ⟨n', less, bound'⟩ := ranking.lowers reacts bound step + exact ih w' (ranking.bounds_mono bound' (by omega)) + +theorem Ranked.answered {ranking : m.Ranking} {c : m.signature.Call} + {k : m.signature.Reply c → Program m.signature Unit} {t : Nat} + (ranked : Ranked ranking (.call c k) t) (reply : m.signature.Reply c) : + Ranked ranking (k reply) t := by + cases ranked with + | call _ _ each fits => + have : ∀ {p : Program m.signature Unit} {a b : Nat}, Ranked ranking p a → a ≤ b → + Ranked ranking p b := by + intro p a b h le + induction h generalizing b with + | pure one => exact .pure (by omega) + | fail failure one => exact .fail failure (by omega) + | send s k each fits _ => exact .send s k each (by omega) + | call c k each fits _ => exact .call c k each (by omega) + | await k each fits _ => exact .await k each (by omega) + | compensate undo k small rest fits _ => exact .compensate undo k small rest (by omega) + | start saga input k rest run fits _ _ => exact .start saga input k rest run (by omega) + | signal saga told k rest fits _ => exact .signal saga told k rest (by omega) + | schedule after s k rest fits _ => exact .schedule after s k rest (by omega) + exact this (each reply) fits + +/-- In every world the model can reach, every reaction under way has a rank. -/ +theorem Ranking.reachable (ranking : m.Ranking) (reacts : ranking.Reacts) + (w : World m.signature) (reach : m.Reachable w) : ∃ n, ranking.fibers w.fibers n := by + induction reach with + | start => exact ⟨0, .nil⟩ + | step _ step ih => + obtain ⟨n, ranked⟩ := ih + cases step with + | send s _ => exact ⟨n, ranked⟩ + | decide d actor c _ => exact ⟨n, ranked⟩ + | deliver e before after inbox => + obtain ⟨added, reactions, _⟩ := reacts (_ : List _) e + exact ⟨_, ranking.fibers_append ranked reactions⟩ + | redeliver e _ => + obtain ⟨added, reactions, _⟩ := reacts (_ : List _) e + exact ⟨_, ranking.fibers_append ranked reactions⟩ + | advance f before after w' fs split adv => + rw [split] at ranked + obtain ⟨x, r, y, hb, fiber, ha, rfl⟩ := ranking.fibers_split ranked + obtain ⟨replaced, new, _⟩ := ranking.advance fiber adv + exact ⟨_, ranking.fibers_append (ranking.fibers_append hb new) ha⟩ + | answer f before after c k reply split program => + rw [split] at ranked + obtain ⟨x, r, y, hb, ⟨p, u, prog, undos, total⟩, ha, rfl⟩ := ranking.fibers_split ranked + rw [program] at prog + exact ⟨_, ranking.fibers_append hb + (.cons (f := { f with program := k reply }) ⟨p, u, prog.answered reply, undos, total⟩ ha)⟩ + | tick time _ => exact ⟨n, ranked⟩ + | fire due s before after _ _ => exact ⟨n, ranked⟩ + +/-- +A model with such a ranking comes to rest. From any world it can reach, with +policies, sagas, undos and signals, after some number of steps nothing can go on. +-/ +theorem Ranking.comesToRest (ranking : m.Ranking) (reacts : ranking.Reacts) + (w : World m.signature) (reach : m.Reachable w) : ∃ steps, m.AtRest (m.settle steps w) := by + obtain ⟨n, ranked⟩ := ranking.reachable reacts w reach + exact ⟨_, ranking.rest reacts _ w ⟨n, ranked, Nat.le_refl _⟩⟩ + +/-- So what holds of every reachable world at rest holds eventually, from any reachable world. -/ +theorem Ranking.eventually (ranking : m.Ranking) (reacts : ranking.Reacts) + {P : World m.signature → Prop} (atRest : ∀ w, m.Reachable w → m.AtRest w → P w) + (w : World m.signature) (reach : m.Reachable w) : m.Eventually w P := by + obtain ⟨steps, rest⟩ := ranking.comesToRest reacts w reach + exact ⟨steps, rest, atRest _ (m.settle_reachable _ w reach) rest⟩ + +/-! ## Ranks, found by the checker + +The same rules with the rank of what follows worked out from the rank given, so +a proof never has to name one: `ranked` walks a program and spends its rank as +it goes. +-/ + +theorem Ranked.mono {ranking : m.Ranking} {p : Program m.signature Unit} {a b : Nat} + (h : Ranked ranking p a) (le : a ≤ b) : Ranked ranking p b := by + induction h generalizing b with + | pure one => exact .pure (by omega) + | fail failure one => exact .fail failure (by omega) + | send s k each fits _ => exact .send s k each (by omega) + | call c k each fits _ => exact .call c k each (by omega) + | await k each fits _ => exact .await k each (by omega) + | compensate undo k small rest fits _ => exact .compensate undo k small rest (by omega) + | start saga input k rest run fits _ _ => exact .start saga input k rest run (by omega) + | signal saga told k rest fits _ => exact .signal saga told k rest (by omega) + | schedule after s k rest fits _ => exact .schedule after s k rest (by omega) + +variable {ranking : m.Ranking} {t : Nat} + +theorem Ranked.send' (s : Send m.signature.aggregates) (k) + (each : ∀ r, Ranked ranking (k r) (t - (2 + ranking.send s))) (fits : 2 + ranking.send s + 1 ≤ t) : + Ranked ranking (.send s k) t := .send s k each (by omega) + +theorem Ranked.call' (c : m.signature.Call) (k) (each : ∀ r, Ranked ranking (k r) t) : + Ranked ranking (.call c k) t := .call c k each (Nat.le_refl _) + +theorem Ranked.await' (k : m.signature.Signal → Program m.signature Unit) + (each : ∀ signal, Ranked ranking (k signal) (t - 1)) (fits : 2 ≤ t) : + Ranked ranking (.await k) t := .await k each (by omega) + +theorem Ranked.compensate' (undo : m.signature.Failure → Send m.signature.aggregates) (k) + (s : Send m.signature.aggregates) (same : ∀ failure, undo failure = s) + (rest : Ranked ranking k (t - (3 + ranking.send s))) (fits : 3 + ranking.send s + 1 ≤ t) : + Ranked ranking (.compensate undo k) t := + .compensate undo k (b := ranking.send s) (fun failure => by rw [same]; exact Nat.le_refl _) rest + (by omega) + +theorem Ranked.start' {j : Nat} (saga) (input) (k) + (run : Ranked ranking (m.saga saga input) j) (rest : Ranked ranking k (t - (1 + j))) + (fits : 1 + j + 1 ≤ t) : Ranked ranking (.start saga input k) t := + .start saga input k rest run (by omega) + +theorem Ranked.signal' (saga) (told) (k) (rest : Ranked ranking k (t - 1)) (fits : 2 ≤ t) : + Ranked ranking (.signal saga told k) t := .signal saga told k rest (by omega) + +theorem Ranked.schedule' (after) (s) (k) (rest : Ranked ranking k (t - 1)) (fits : 2 ≤ t) : + Ranked ranking (.schedule after s k) t := .schedule after s k rest (by omega) + +/-- A reaction with no undos registered, at its program's rank. -/ +theorem Ranking.plain (ranking : m.Ranking) {program : Program m.signature Unit} {rank : Nat} + (ranked : Ranked ranking program rank) : + ranking.fiber { owner := none, program, undo := [] } rank := + ⟨rank, 0, ranked, .nil, Nat.le_refl _⟩ + +/-- The reactions to one event, each a program with a rank. -/ +inductive Ranking.programs (ranking : m.Ranking) : List (Program m.signature Unit) → List Nat → Prop where + | nil : Ranking.programs ranking [] [] + | cons {p r ps rs} : Ranked ranking p r → Ranking.programs ranking ps rs → + Ranking.programs ranking (p :: ps) (r :: rs) + +theorem Ranking.programs_fibers (ranking : m.Ranking) {ps : List (Program m.signature Unit)} + {rs : List Nat} (h : ranking.programs ps rs) : + ranking.fibers (ps.map fun program => { owner := none, program, undo := [] }) rs.sum := by + induction h with + | nil => exact .nil + | cons ranked _ ih => rw [List.sum_cons]; exact .cons (ranking.plain ranked) ih + +/-- An event outweighs the reactions to it, once each reaction has a rank. -/ +theorem Ranking.reacting (ranking : m.Ranking) {history} {e : Emitted m.signature.aggregates} + {ranks : List Nat} (ranked : ranking.programs (m.policies.map fun p => p.react history e) ranks) + (fits : 1 + ranks.sum ≤ ranking.event e.source e.event) : + ∃ total, ranking.fibers + (m.policies.map fun p => { owner := none, program := p.react history e, undo := [] }) total + ∧ 1 + total ≤ ranking.event e.source e.event := by + refine ⟨ranks.sum, ?_, fits⟩ + simpa [List.map_map, Function.comp_def] using ranking.programs_fibers ranked + +/-! ## How many steps + +When every reaction is calm, a ranking is also a measure of a world, so the +number of steps to rest can be written down. +-/ + +theorem Ranked.weighs {ranking : m.Ranking} {p : Program m.signature Unit} {t : Nat} + (h : Ranked ranking p t) : m.weigh ranking.send p ≤ t := by + cases h <;> simp only [Model.weigh] <;> omega + +theorem Ranking.fibers_weigh (ranking : m.Ranking) {fs : List (Fiber m.signature)} {n : Nat} + (h : ranking.fibers fs n) : (fs.map fun f => m.weigh ranking.send f.program).sum ≤ n := by + induction h with + | nil => simp + | cons one _ ih => + obtain ⟨p, u, ranked, _, fits⟩ := one + have := ranked.weighs + simp only [List.map_cons, List.sum_cons] + omega + +/-- The ranking's weights, as a measure of a world. -/ +def Ranking.weights (ranking : m.Ranking) (reacts : ranking.Reacts) : m.Weights where + event := ranking.event + send := ranking.send + emits := ranking.emits + reacts := by + intro history e + obtain ⟨total, ranked, fits⟩ := reacts history e + have := ranking.fibers_weigh ranked + simp only [List.map_map, Function.comp_def] at this + omega + +/-- The reactions to one event are all calm. -/ +inductive AllCalm : List (Program m.signature Unit) → Prop where + | nil : AllCalm [] + | cons {p ps} : Calm p → AllCalm ps → AllCalm (p :: ps) + +theorem AllCalm.each {ps : List (Program m.signature Unit)} (h : AllCalm (m := m) ps) : + ∀ p ∈ ps, Calm p := by + induction h with + | nil => intro p mem; cases mem + | cons one _ ih => + intro p mem + cases mem with + | head => exact one + | tail _ rest => exact ih p rest + +/-- With calm reactions, the model is at rest after as many steps as the world weighs. -/ +theorem Ranking.comesToRestIn (ranking : m.Ranking) (reacts : ranking.Reacts) + (calm : ∀ history e, AllCalm (m := m) (m.policies.map fun p => p.react history e)) + (w : World m.signature) (reach : m.Reachable w) : + m.AtRest (m.settle ((ranking.weights reacts).measure w) w) := + (ranking.weights reacts).comesToRest + (fun p mem history e => (calm history e).each _ (List.mem_map.mpr ⟨p, mem, rfl⟩)) w reach + +end Model + +/-- The least rank left over at the end of a program, while a program is being measured. -/ +initialize rankLeft : IO.Ref Nat ← IO.mkRef 0 + +open Lean Elab Tactic Meta in +/-- At the end of a program, notes how much of the rank given is left. It proves nothing. -/ +elab "ranked_note" : tactic => withMainContext do + let goal ← whnfR (← getMainTarget) + let args := goal.getAppArgs + if args.size < 2 then return + let program ← whnf args[args.size - 2]! + unless program.isAppOf ``Alchemy.Program.pure || program.isAppOf ``Alchemy.Program.fail do return + let left ← whnf args[args.size - 1]! + let left ← match left with + | .lit (.natVal n) => pure n + | _ => match ← (evalNat (← reduce left)).run with + | some n => pure n + | none => return + rankLeft.modify (min · left) + +/-- Settles an inequality between a rank and what a step costs. -/ +syntax "ranked_fits " ident : tactic + +macro_rules + | `(tactic| ranked_fits $ranking) => + `(tactic| first + | decide + | (simp [$ranking:ident]; done) + | (simp [$ranking:ident]; omega) + | omega) + +/-- +Proves that a program has the rank given: `ranked Bank.ranking [Bank.Payout.ranked]`. +It walks the program, spending the rank as it goes; the list is the ranks of +the sagas it may start. +-/ +syntax "ranked " ident " [" term,* "]" : tactic + +macro_rules + | `(tactic| ranked $ranking [$sagas,*]) => do + let again ← `(tactic| ranked $ranking [$sagas,*]) + let starts ← sagas.getElems.mapM fun saga => + `(tactic| (refine Alchemy.Model.Ranked.start' _ _ _ ($saga _ _) ?_ (by ranked_fits $ranking) + $again:tactic)) + let start ← if starts.isEmpty then `(tactic| fail "no saga's rank was given") + else `(tactic| first $[| $starts:tactic]*) + `(tactic| first + | (ranked_note; exact Alchemy.Model.Ranked.pure (by ranked_fits $ranking)) + | (ranked_note; exact Alchemy.Model.Ranked.fail _ (by ranked_fits $ranking)) + | (refine Alchemy.Model.Ranked.send' _ _ (fun r => ?_) (by ranked_fits $ranking) + first | $again:tactic | (cases r <;> $again:tactic)) + | (refine Alchemy.Model.Ranked.call' _ _ (fun r => ?_) + first | $again:tactic | (cases r <;> $again:tactic)) + | (refine Alchemy.Model.Ranked.await' _ (fun r => ?_) (by ranked_fits $ranking) + first | $again:tactic | (cases r <;> $again:tactic)) + | (refine Alchemy.Model.Ranked.compensate' _ _ _ (fun _ => rfl) ?_ (by ranked_fits $ranking) + $again:tactic) + | $start:tactic + | (refine Alchemy.Model.Ranked.signal' _ _ _ ?_ (by ranked_fits $ranking) + $again:tactic) + | (refine Alchemy.Model.Ranked.schedule' _ _ _ ?_ (by ranked_fits $ranking) + $again:tactic) + | (split <;> $again:tactic)) + +/-- Proves that a reaction only calls outside, tells an aggregate, and ends. -/ +syntax "calm" : tactic + +macro_rules + | `(tactic| calm) => + `(tactic| first + | exact Alchemy.Calm.done + | exact Alchemy.Calm.tell _ + | (refine Alchemy.Calm.call _ _ (fun r => ?_) + first | calm | (cases r <;> calm)) + | (split <;> calm)) + +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Signature.lean b/packages/alchemy-lean/Alchemy/Signature.lean new file mode 100644 index 00000000000..37171e02179 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Signature.lean @@ -0,0 +1,64 @@ +import Alchemy.Aggregate + +/-! +What a model is made of, before anything is implemented: its aggregates, the +outside systems it calls, and its sagas. +-/ +namespace Alchemy + +/-- The aggregates of a model, by name. -/ +structure Aggregates where + Name : Type + of : Name → Aggregate + [decEqName : DecidableEq Name] + +attribute [instance] Aggregates.decEqName + +/-- A command for one of the aggregates, and who sends it. -/ +structure Send (g : Aggregates) where + to : g.Name + actor : (g.of to).Actor + command : (g.of to).Command + +/-- An event to record on one instance. -/ +structure Record (g : Aggregates) where + to : g.Name + id : (g.of to).Id + event : (g.of to).Event + +/-- An event one instance recorded: where it sits in the log, and when. -/ +structure Emitted (g : Aggregates) where + source : g.Name + id : (g.of source).Id + event : (g.of source).Event + seq : Nat + time : Time + +/-- Every instance's state. -/ +abbrev States (g : Aggregates) := (n : g.Name) → (g.of n).Id → (g.of n).State + +/-- What a command sent to an aggregate answers. -/ +abbrev Answer (g : Aggregates) (n : g.Name) := + Except (g.of n).Rejection (List (g.of n).Event) + +structure Signature where + aggregates : Aggregates + /-- A call to a system outside the model, with its arguments. -/ + Call : Type + /-- What a call may answer. -/ + Reply : Call → Type + /-- A saga's run, by what it is about. -/ + Saga : Type + /-- What a run is started with. -/ + SagaInput : Type + /-- What a run can be told while it waits. -/ + Signal : Type + /-- How a run or a reaction can fail. -/ + Failure : Type + [decEqCall : DecidableEq Call] + [decEqSaga : DecidableEq Saga] + [decEqFailure : DecidableEq Failure] + +attribute [instance] Signature.decEqCall Signature.decEqSaga Signature.decEqFailure + +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Stored.lean b/packages/alchemy-lean/Alchemy/Stored.lean new file mode 100644 index 00000000000..7c415c15f48 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Stored.lean @@ -0,0 +1,332 @@ +import Alchemy.Engine + +/-! +# A model, kept in stores + +The engine in `Alchemy.Engine` is a function on a `World` held in one piece. +This is the same engine with each part of the world behind a service: the +aggregates' states in a `Store`, the events not yet delivered in a `Delivery`, +what is part-way through in `Processes`, and the time in a `Clock`. It loads +one instance, decides, and commits the state the events leave: it never replays +a history. + +Each service has a law, stated against what a store holds. The engine is +written once, for any services, and one theorem carries every proof across: +on lawful services, whatever the engine does is steps the model can take. So a +rule proved of the model holds of the model as it is stored, wherever that is. +-/ +namespace Alchemy + +/-- How code acts on what it runs against: what it answers, and what it leaves. -/ +structure Acts (μ : Type → Type) [Monad μ] (S : Type) where + eval : {α : Type} → μ α → S → α × S + eval_pure : ∀ {α : Type} (a : α) (s : S), eval (pure a) s = (a, s) + eval_bind : ∀ {α β : Type} (x : μ α) (f : α → μ β) (s : S), + eval (x >>= f) s = eval (f (eval x s).1) (eval x s).2 + +variable {σ : Signature} + +/-- What is part-way through: reactions and runs, where each saga stands, and what is scheduled. -/ +structure Process (σ : Signature) where + fibers : List (Fiber σ) + sagas : σ.Saga → SagaStatus σ + signals : σ.Saga → List σ.Signal + schedule : List (Time × Send σ.aggregates) + +namespace Process + +/-- Before anything has run. -/ +def start (σ : Signature) : Process σ where + fibers := [] + sagas := fun _ => .notStarted + signals := fun _ => [] + schedule := [] + +/-- Ends a fiber: a saga's run takes the status. -/ +def finish (P : Process σ) (owner : Option σ.Saga) (status : SagaStatus σ) : Process σ := + match owner with + | none => P + | some saga => { P with sagas := update P.sagas saga status } + +/-- The calls waiting for an outside system's answer, oldest first. -/ +def waiting (P : Process σ) : List σ.Call := + P.fibers.filterMap fun f => + match f.program with + | .call c _ => some c + | _ => none + +end Process + +/-- The part of a world that is part-way through. -/ +def World.process (w : World σ) : Process σ := ⟨w.fibers, w.sagas, w.signals, w.schedule⟩ + +/-- An event as a store hands it on: without its place in a log nobody keeps. -/ +def Emitted.unplaced {g : Aggregates} (e : Emitted g) : Emitted g := { e with seq := 0 } + +/-- +What is read from a model, kept up as events are delivered: views, tables, +whatever a reader asks for. It is a state and how one event changes it. +-/ +structure ReadSide (g : Aggregates) where + State : Type + initial : State + apply : State → Emitted g → State + +/-- A model nothing is read from. -/ +def ReadSide.none (g : Aggregates) : ReadSide g := ⟨Unit, (), fun _ _ => ()⟩ + +/-- What the stores hold, as the model sees it. -/ +structure Held (σ : Signature) (reads : ReadSide σ.aggregates) where + /-- Every instance's state. -/ + state : States σ.aggregates + /-- The events committed and not yet delivered, oldest first. -/ + pending : List (Emitted σ.aggregates) + process : Process σ + now : Time + /-- What is read, after every event delivered so far. -/ + read : reads.State + +/-- Before anything is stored. -/ +def Held.start (σ : Signature) (reads : ReadSide σ.aggregates) : Held σ reads where + state := fun n _ => (σ.aggregates.of n).initial + pending := [] + process := .start σ + now := 0 + read := reads.initial + +/-! ## The services -/ + +/-- Where each instance's state is kept. -/ +structure Store (μ : Type → Type) (g : Aggregates) where + load : (n : g.Name) → (g.of n).Id → μ (g.of n).State + /-- Keeps the state a command left, and hands its events to delivery, together. -/ + commit : (n : g.Name) → (g.of n).Id → (g.of n).State → List (g.of n).Event → Time → μ Unit + +/-- How committed events reach the policies. -/ +structure Delivery (μ : Type → Type) (g : Aggregates) where + /-- Takes the oldest event not yet delivered, if there is one. -/ + next : μ (Option (Emitted g)) + +/-- Where what is part-way through is kept between requests. -/ +structure Processes (μ : Type → Type) (σ : Signature) where + read : μ (Process σ) + keep : Process σ → μ Unit + +/-- What time it is. -/ +structure Clock (μ : Type → Type) where + now : μ Time + +/-- Everything a model asks of its host. -/ +structure Services (μ : Type → Type) (σ : Signature) (reads : ReadSide σ.aggregates) where + store : Store μ σ.aggregates + delivery : Delivery μ σ.aggregates + processes : Processes μ σ + clock : Clock μ + /-- Each outside system the model calls. -/ + call : (c : σ.Call) → μ (σ.Reply c) + /-- Hands a delivered event to whatever is read from the model. -/ + project : Emitted σ.aggregates → μ Unit + /-- What is read from the model, as it stands. -/ + look : μ reads.State + +/-! ## Their laws -/ + +section Laws + +variable {μ : Type → Type} [Monad μ] {S : Type} (acts : Acts μ S) + {reads : ReadSide σ.aggregates} (held : S → Held σ reads) (sound : S → Prop) + +/-- Code that answers something about what is held, and changes none of it. -/ +def Reads {α : Type} (x : μ α) (answer : Held σ reads → α) : Prop := + ∀ s, sound s → + (acts.eval x s).1 = answer (held s) ∧ held (acts.eval x s).2 = held s ∧ sound (acts.eval x s).2 + +/-- Code that changes what is held in exactly this way. -/ +def Writes {α : Type} (x : μ α) (change : Held σ reads → Held σ reads) : Prop := + ∀ s, sound s → held (acts.eval x s).2 = change (held s) ∧ sound (acts.eval x s).2 + +/-- A store answers the state it holds, and a commit changes one instance and adds its events. -/ +structure Store.Lawful (store : Store μ σ.aggregates) : Prop where + load : ∀ n id, Reads acts held sound (store.load n id) fun h => h.state n id + commit : ∀ n id state events time, + Writes acts held sound (store.commit n id state events time) fun h => + { h with + state := h.state.set n id state + pending := h.pending ++ events.map fun e => ⟨n, id, e, 0, time⟩ } + +/-- Delivery hands on the oldest pending event, once. -/ +structure Delivery.Lawful (delivery : Delivery μ σ.aggregates) : Prop where + next : ∀ s, sound s → + (acts.eval delivery.next s).1 = (held s).pending.head? ∧ + held (acts.eval delivery.next s).2 = { held s with pending := (held s).pending.tail } ∧ + sound (acts.eval delivery.next s).2 + +/-- What is kept reads back. -/ +structure Processes.Lawful (processes : Processes μ σ) : Prop where + read : Reads acts held sound processes.read fun h => h.process + keep : ∀ P, Writes acts held sound (processes.keep P) fun h => { h with process := P } + +/-- The clock answers the time. -/ +structure Clock.Lawful (clock : Clock μ) : Prop where + now : Reads acts held sound clock.now fun h => h.now + +/-- Every service keeps its law, and calling outside changes nothing the model holds. -/ +structure Services.Lawful (services : Services μ σ reads) : Prop where + store : services.store.Lawful acts held sound + delivery : services.delivery.Lawful acts held sound + processes : services.processes.Lawful acts held sound + clock : services.clock.Lawful acts held sound + call : ∀ c, Writes acts held sound (services.call c) fun h => h + /-- A delivered event changes what is read, and nothing else. -/ + project : ∀ e, Writes acts held sound (services.project e) fun h => + { h with read := reads.apply h.read e } + look : Reads acts held sound services.look fun h => h.read + +end Laws + +/-! ## The engine -/ + +/-- A model run on services. -/ +structure Engine (μ : Type → Type) (m : Model) (reads : ReadSide m.signature.aggregates) where + services : Services μ m.signature reads + /-- How many steps one request may set off. -/ + fuel : Nat := 1000 + /-- How many outside calls one request may make. -/ + calls : Nat := 100 + +namespace Engine + +variable {μ : Type → Type} [Monad μ] {m : Model} {reads : ReadSide m.signature.aggregates} + (e : Engine μ m reads) + +/-- Sends one command to its instance: load, decide, and commit what the events leave. -/ +def record (s : Send m.signature.aggregates) : μ (Answer m.signature.aggregates s.to) := + e.services.clock.now >>= fun now => + e.services.store.load s.to ((m.signature.aggregates.of s.to).keyOf s.command) >>= fun state => + match (m.signature.aggregates.of s.to).decide ⟨s.actor, now⟩ state s.command with + | .ok events => + e.services.store.commit s.to ((m.signature.aggregates.of s.to).keyOf s.command) + ((m.signature.aggregates.of s.to).apply state events now) events now >>= fun _ => + pure (.ok events) + | .error rejection => pure (.error rejection) + +/-- A fiber's next step: what is part-way through after it, and the fibers that replace it. -/ +def advance (P : Process m.signature) (f : Fiber m.signature) : + μ (Option (Process m.signature × List (Fiber m.signature))) := + match f.program with + | .pure () => pure (some (P.finish f.owner .completed, [])) + | .fail failure => + match f.undo with + | [] => pure (some (P.finish f.owner (.failed failure), [])) + | u :: rest => e.record (u failure) >>= fun _ => pure (some (P, [{ f with undo := rest }])) + | .send s k => e.record s >>= fun answer => pure (some (P, [{ f with program := k answer }])) + | .call _ _ => pure none + | .await k => + pure (match f.owner with + | none => none + | some saga => + match P.signals saga with + | [] => none + | signal :: rest => + some ({ P with signals := update P.signals saga rest }, [{ f with program := k signal }])) + | .compensate u k => pure (some (P, [{ f with program := k, undo := u :: f.undo }])) + | .start saga input k => + pure (match P.sagas saga with + | .notStarted => + some ({ P with sagas := update P.sagas saga .running }, + [{ f with program := k }, { owner := some saga, program := m.saga saga input, undo := [] }]) + | _ => some (P, [{ f with program := k }])) + | .signal saga signal k => + pure (some ({ P with signals := update P.signals saga (P.signals saga ++ [signal]) }, + [{ f with program := k }])) + | .schedule after s k => + e.services.clock.now >>= fun now => + pure (some ({ P with schedule := P.schedule ++ [(now + after, s)] }, [{ f with program := k }])) + +/-- The first fiber that can take a step takes it. -/ +def tryFibers (P : Process m.signature) : + List (Fiber m.signature) → List (Fiber m.signature) → μ (Option (Process m.signature)) + | _, [] => pure none + | before, f :: after => + e.advance P f >>= fun + | some (P', fs) => pure (some { P' with fibers := before ++ fs ++ after }) + | none => tryFibers P (before ++ [f]) after + +/-- One step: the oldest pending event reaches the policies, or else a fiber goes on. -/ +def stepOnce (P : Process m.signature) : μ (Option (Process m.signature)) := + e.services.delivery.next >>= fun + | some event => + e.services.project event >>= fun _ => + pure (some { P with + fibers := P.fibers ++ m.policies.map fun p => + { owner := none, program := p.react [] event, undo := [] } }) + | none => e.tryFibers P [] P.fibers + +/-- Runs until nothing can go on, or the fuel runs out. -/ +def settle : Nat → Process m.signature → μ (Process m.signature) + | 0, P => pure P + | fuel + 1, P => + e.stepOnce P >>= fun + | none => pure P + | some P' => settle fuel P' + +/-- Calls the outside systems the model is waiting on, until none is left. -/ +def answerCalls : Nat → Process m.signature → μ (Process m.signature) + | 0, P => pure P + | calls + 1, P => + match P.waiting with + | [] => pure P + | c :: _ => + e.services.call c >>= fun reply => + match m.answerGo c reply P.fibers with + | some fibers => e.settle e.fuel { P with fibers } >>= answerCalls calls + | none => pure P + +/-- +Send the model a command. Answers what the aggregate answered, once every +policy that reacts has run and every outside call was made. +-/ +def send (s : Send m.signature.aggregates) : μ (Answer m.signature.aggregates s.to) := + e.services.processes.read >>= fun P => + e.record s >>= fun answer => + e.settle e.fuel P >>= fun P => + e.answerCalls e.calls P >>= fun P => + e.services.processes.keep P >>= fun _ => + pure answer + +/-- Sends the scheduled commands that are due, one at a time, letting each settle. -/ +def fireDue : Nat → Process m.signature → μ (Process m.signature) + | 0, P => pure P + | count + 1, P => + e.services.clock.now >>= fun now => + match m.nextDue now P.schedule with + | none => pure P + | some (before, x, after) => + e.record x.2 >>= fun _ => + e.settle e.fuel { P with schedule := before ++ after } >>= fireDue count + +/-- The clock has moved: send what is now due, and everything that follows. -/ +def wake : μ Unit := + e.services.processes.read >>= fun P => + e.fireDue e.fuel P >>= fun P => + e.answerCalls e.calls P >>= fun P => + e.services.processes.keep P + +/-- One instance's state. -/ +def state (n : m.signature.aggregates.Name) (id : (m.signature.aggregates.of n).Id) : + μ (m.signature.aggregates.of n).State := + e.services.store.load n id + +/-- What is read from the model, as it stands. -/ +def look : μ reads.State := e.services.look + +/-- Send a command, and answer its caller: a rejection, or the aggregate's reply. -/ +def ask (s : Send m.signature.aggregates) : + μ (Except (m.signature.aggregates.of s.to).Rejection (m.signature.aggregates.of s.to).Reply) := + e.send s >>= fun answer => + e.services.store.load s.to ((m.signature.aggregates.of s.to).keyOf s.command) >>= fun state => + pure (answer.map fun _ => (m.signature.aggregates.of s.to).reply state s.command) + +end Engine + +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Story.lean b/packages/alchemy-lean/Alchemy/Story.lean new file mode 100644 index 00000000000..9a9a8a43daa --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Story.lean @@ -0,0 +1,258 @@ +import Alchemy.Engine + +/-! +A story: an example of what a model does, checked when the file compiles. +Every outcome has to be accounted for: each event recorded, each rejection, and +each call to an outside system must be asserted before the story ends. +-/ +namespace Alchemy + +/-! ## One aggregate -/ + +inductive Story.Step (a : Aggregate) where + /-- History: events already recorded. -/ + | given (events : List a.Event) + /-- The commands that follow are sent by this actor. -/ + | as (actor : a.Actor) + /-- The commands that follow are sent at this time. -/ + | clock (time : Time) + /-- Send a command. -/ + | when (command : a.Command) + /-- The last command recorded exactly these events. -/ + | recorded (events : List a.Event) + /-- The last command was rejected with this. -/ + | rejected (rejection : a.Rejection) + /-- The state is this. -/ + | state (state : a.State) + +namespace Story + +variable {a : Aggregate} + +/-- Runs the steps. `pending` is the last command's answer, until a step asserts it. -/ +def run (ctx : Context a.Actor) (s : a.State) + (pending : Option (Except a.Rejection (List a.Event))) : List (Step a) → Bool + | [] => pending.isNone + | .given es :: rest => pending.isNone && run ctx (a.apply s es ctx.now) none rest + | .as actor :: rest => run { ctx with actor } s pending rest + | .clock time :: rest => run { ctx with now := time } s pending rest + | .when c :: rest => + pending.isNone && + match a.decide ctx s c with + | .ok es => run ctx (a.apply s es ctx.now) (some (.ok es)) rest + | .error r => run ctx s (some (.error r)) rest + | .recorded es :: rest => + match pending with + | some (.ok actual) => decide (actual = es) && run ctx s none rest + | _ => false + | .rejected r :: rest => + match pending with + | some (.error actual) => decide (actual = r) && run ctx s none rest + | _ => false + | .state expected :: rest => decide (s = expected) && run ctx s pending rest + +end Story + +/-- A story passes when every step holds and no outcome is left unasserted. -/ +def Aggregate.story (a : Aggregate) (actor : a.Actor) (steps : List (Story.Step a)) : Bool := + Story.run ⟨actor, 0⟩ a.initial none steps + +/-! ## A model -/ + +inductive Story.ModelStep (m : Model) where + /-- History: events already recorded. Policies do not react to them. -/ + | given (n : m.signature.aggregates.Name) (id : (m.signature.aggregates.of n).Id) + (events : List (m.signature.aggregates.of n).Event) + /-- Send a command, then let everything that follows from it run. -/ + | when (s : Send m.signature.aggregates) + /-- Send a command a decision answers. `rejected` is the rejection it must give, if any. -/ + | decide (d : Decision m.signature.aggregates) (actor : d.Actor) (c : d.Command) + (rejected : Option d.Rejection := none) + /-- The events recorded on this instance since it was last asserted are exactly these. -/ + | recorded (n : m.signature.aggregates.Name) (id : (m.signature.aggregates.of n).Id) + (events : List (m.signature.aggregates.of n).Event) + /-- The last command sent was rejected with this. -/ + | rejected (n : m.signature.aggregates.Name) (rejection : (m.signature.aggregates.of n).Rejection) + /-- This command, sent now, would be answered with this reply. -/ + | replies (s : Send m.signature.aggregates) (reply : (m.signature.aggregates.of s.to).Reply) + /-- An instance's state is this. -/ + | state (n : m.signature.aggregates.Name) (id : (m.signature.aggregates.of n).Id) + (state : (m.signature.aggregates.of n).State) + /-- A view's state at a key is this. -/ + | view (v : View m.signature.aggregates) (key : v.Key) (state : v.State) + /-- A view emitted exactly these events at a key. -/ + | emitted (v : View m.signature.aggregates) (key : v.Key) (events : List v.Event) + /-- This call to an outside system is waiting for an answer. -/ + | call (c : m.signature.Call) + /-- The outside system answers the call. -/ + | answer (c : m.signature.Call) (reply : m.signature.Reply c) + /-- A saga's run stands here. -/ + | saga (saga : m.signature.Saga) (status : SagaStatus m.signature) + /-- Time passes: scheduled commands that are due are sent. -/ + | pass (duration : Time) + /-- Anything else about the world. -/ + | holds (what : String) (check : World m.signature → Bool) + /-- The next moves of the scenario the story follows happen: one, unless said otherwise. -/ + | next (moves : Nat := 1) + +namespace Story + +variable {m : Model} + +structure Progress (m : Model) where + world : World m.signature + /-- The log entries a step has asserted, by where they sit in the log. -/ + asserted : List Nat + /-- The last command's rejection, until a step asserts it. -/ + pending : Option ((n : m.signature.aggregates.Name) × (m.signature.aggregates.of n).Rejection) + +/-- The events on one instance that no step has asserted yet. -/ +def unasserted (log : List (Emitted m.signature.aggregates)) (asserted : List Nat) + (n : m.signature.aggregates.Name) (id : (m.signature.aggregates.of n).Id) : + List (Nat × (m.signature.aggregates.of n).Event) := + log.filterMap fun e => + if h : e.source = n then + if h ▸ e.id = id ∧ e.seq ∉ asserted then some (e.seq, h ▸ e.event) else none + else none + +def fuel : Nat := 1000 + +def stepModel (p : Progress m) : ModelStep m → Except String (Progress m) + | .given n id events => + let recorded := p.world.toRecorded.record p.world.now n id events + let seqs := (recorded.log.drop p.world.log.length).map (·.seq) + .ok { p with world := { p.world with toRecorded := recorded }, asserted := p.asserted ++ seqs } + | .when s => + if p.pending.isSome then .error "a rejection was not asserted before the next command" + else + let pending := + match p.world.toRecorded.outcome p.world.now s with + | .ok _ => none + | .error r => some ⟨s.to, r⟩ + .ok { p with world := m.play fuel p.world (.send s), pending } + | .decide d actor c rejected => + if p.pending.isSome then .error "a rejection was not asserted before the next command" + else + match d.decide ⟨actor, p.world.now⟩ p.world.state c, rejected with + | .ok _, none => .ok { p with world := m.play fuel p.world (.decide d actor c) } + | .error actual, some expected => + if actual = expected then .ok p else .error s!"{d.name} gave another rejection" + | .ok _, some _ => .error s!"{d.name} was not rejected" + | .error _, none => .error s!"{d.name} was rejected" + | .recorded n id events => + let found := unasserted p.world.log p.asserted n id + if found.map (·.2) = events then .ok { p with asserted := p.asserted ++ found.map (·.1) } + else .error "the events recorded are not the ones expected" + | .rejected n rejection => + match p.pending with + | some ⟨n', actual⟩ => + if h : n' = n then + if h ▸ actual = rejection then .ok { p with pending := none } + else .error "the command gave another rejection" + else .error "the command was rejected by another aggregate" + | none => .error "the command was not rejected" + | .replies s reply => + let a := m.signature.aggregates.of s.to + let id := a.keyOf s.command + match p.world.toRecorded.outcome p.world.now s with + | .error _ => .error "the command would be rejected" + | .ok es => + if a.reply (a.apply (p.world.state s.to id) es p.world.now) s.command = reply then .ok p + else .error "the reply is not the one expected" + | .state n id state => + if p.world.state n id = state then .ok p else .error "the state is not the one expected" + | .view v key state => + if v.stateAt p.world.log key = state then .ok p + else .error s!"{v.name} is not in the state expected" + | .emitted v key events => + if v.emittedAt p.world.log key = events then .ok p + else .error s!"{v.name} did not emit the events expected" + | .call c => + if c ∈ m.waiting p.world then .ok p else .error "no such call is waiting" + | .answer c reply => + match m.answer p.world c reply with + | some w => .ok { p with world := m.settle fuel w } + | none => .error "no such call is waiting to be answered" + | .saga saga status => + if p.world.sagas saga = status then .ok p else .error "the saga does not stand where expected" + | .pass duration => .ok { p with world := m.pass fuel p.world duration } + | .holds what check => if check p.world then .ok p else .error s!"does not hold: {what}" + | .next _ => .error "this story follows no scenario" + +def runModel (p : Progress m) : List (ModelStep m) → Nat → Except String Unit + | [], _ => + if p.pending.isSome then .error "a rejection was never asserted" + else if (m.waiting p.world).length ≠ 0 then .error "a call was never answered" + else if p.world.log.any (fun e => e.seq ∉ p.asserted) then + .error "an event was recorded that no step asserts" + else .ok () + | step :: rest, index => + match stepModel p step with + | .ok p' => runModel p' rest (index + 1) + | .error why => .error s!"step {index + 1}: {why}" + +/-- A move of a scenario, as the story step that makes it. -/ +def stepOf : Model.Move m → Option (ModelStep m) + | .send s => some (.when s) + | .decide d actor c => some (.decide d actor c) + | .answer c reply => some (.answer c reply) + | .pass duration => some (.pass duration) + | .redeliver _ => none + +/-- Makes the next moves of a scenario. -/ +def advance (p : Progress m) : Nat → List (Model.Move m) → + Except String (Progress m × List (Model.Move m)) + | 0, scenario => .ok (p, scenario) + | _ + 1, [] => .error "the scenario has no more moves" + | moves + 1, move :: rest => + match stepOf move with + | none => advance { p with world := m.play fuel p.world move } moves rest + | some step => + match stepModel p step with + | .ok p' => advance p' moves rest + | .error why => .error why + +def followModel (p : Progress m) (scenario : List (Model.Move m)) : + List (ModelStep m) → Nat → Except String Unit + | [], index => + if scenario.length ≠ 0 then .error "the story ends before the scenario does" + else runModel p [] index + | .next moves :: rest, index => + match advance p moves scenario with + | .ok (p', scenario') => followModel p' scenario' rest (index + 1) + | .error why => .error s!"step {index + 1}: {why}" + | step :: rest, index => + match stepModel p step with + | .ok p' => followModel p' scenario rest (index + 1) + | .error why => .error s!"step {index + 1}: {why}" + +end Story + +/-- +Runs a story that follows a scenario: `.next` makes the scenario's next move, +and the steps between say what must be true there. The moves are the +scenario's own, so a theorem about the scenario is about this story. +-/ +def Model.following (m : Model) (scenario : List (Model.Move m)) + (steps : List (Story.ModelStep m)) : Except String Unit := + Story.followModel { world := World.start m.signature, asserted := [], pending := none } + scenario steps 0 + +/-- Whether a story that follows a scenario passes. -/ +def Model.follows (m : Model) (scenario : List (Model.Move m)) + (steps : List (Story.ModelStep m)) : Bool := + match m.following scenario steps with + | .ok _ => true + | .error _ => false + +/-- Runs a story on the model, in memory. `.ok ()` when every step holds. -/ +def Model.story (m : Model) (steps : List (Story.ModelStep m)) : Except String Unit := + Story.runModel { world := World.start m.signature, asserted := [], pending := none } steps 0 + +/-- Whether a story passes. `m.story` says why one does not. -/ +def Model.passes (m : Model) (steps : List (Story.ModelStep m)) : Bool := + match m.story steps with + | .ok _ => true + | .error _ => false + +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/Syntax.lean b/packages/alchemy-lean/Alchemy/Syntax.lean new file mode 100644 index 00000000000..cf0fc8081ea --- /dev/null +++ b/packages/alchemy-lean/Alchemy/Syntax.lean @@ -0,0 +1,878 @@ +import Lean +import Alchemy.Attr +import Alchemy.Model +import Alchemy.History +import Alchemy.Caused +import Alchemy.Reads +import Alchemy.Cloud.Hosted +import Alchemy.Codec + +/-! +# `model … where` + +One declaration for a whole domain model: its aggregates, the outside systems +it calls, its policies, its views and its projections. It writes the +definitions a model is made of, and the theorems that come for free. + +An aggregate is named after a namespace that holds its `Command`, `Event`, +`Rejection` and `State` types and its `key`, `decide` and `evolve` functions. +-/ + +namespace Alchemy + +open Lean Parser + +declare_syntax_cat modelItem (behavior := both) + +syntax callBinder := "(" ident+ " : " term ")" + +/-- One case: `| pattern, pattern => result`. -/ +syntax modelAlt := ppLine "| " term,+ " => " term + +declare_syntax_cat aggregateItem (behavior := both) + +/-- One case of a command, an event or a rejection: a name and its fields. -/ +syntax caseOf := ppLine "| " rawIdent callBinder* +/-- One thing the state remembers, and what it starts as. -/ +syntax fieldOf := atomic(ident " : ") term " := " term + +/-- +One command: its name and fields, then the events it may record and the +rejections it may answer. Both lists are checked against `decide`. +-/ +syntax commandOf := ppLine "| " rawIdent callBinder* + (&" records " rawIdent,+)? (&" rejects " rawIdent,+)? + +/-- What the aggregate can be asked. The first field of each is the instance it is for. -/ +syntax &"command" commandOf+ : aggregateItem +/-- What it records. -/ +syntax &"event" caseOf+ : aggregateItem +/-- Why it refuses. -/ +syntax &"rejection" caseOf+ : aggregateItem +/-- What it remembers. -/ +syntax &"state" many1Indent(fieldOf) : aggregateItem +/-- The events a command records, or why it is refused: `| state, command => …`. -/ +syntax &"decide" modelAlt+ : aggregateItem +/-- What an event does to the state: `| state, event => …`. -/ +syntax &"evolve" modelAlt+ : aggregateItem +/-- What an accepted command answers its caller, from the state it left: `| state, command => …`. -/ +syntax &"reply" " : " term modelAlt+ : aggregateItem +/-- What names an instance, if not a string. Each command's first field is of this type. -/ +syntax &"id" " : " term : aggregateItem +/-- +Who sends its commands. With it, `decide` is given the actor first: +`| actor, state, command => …`. A policy sends as the type's default. +-/ +syntax &"actor" " : " term : aggregateItem + +/-- +An aggregate: its commands, events, rejections and state, and how it decides, +evolves and replies. It writes a namespace of that name holding plain types and +plain functions, which is what a `model` and every theorem refer to. +-/ +syntax (name := aggregateCommand) (docComment)? "aggregate " ident " where" many1Indent(aggregateItem) : command + +/-- A command, allowed alternatives that can never match. -/ +private def lenient (command : Command) : MacroM Command := + `(command| set_option match.ignoreUnusedAlts true in $command:command) + +/-- The cases as constructors of the type named `self`. -/ +private def casesOf (self : Ident) (cases : Array (TSyntax ``caseOf)) : + MacroM (Array (TSyntax ``Command.ctor) × Array Ident) := do + let mut ctors := #[] + let mut names := #[] + for case in cases do + match case with + | `(caseOf| | $name:ident $binders*) => + let mut types : Array Term := #[] + for binder in binders do + match binder with + | `(callBinder| ($ids* : $type)) => types := types ++ ids.map fun _ => type + | _ => Macro.throwUnsupported + let type ← types.foldrM (fun type rest => `($type → $rest)) (← `($self)) + ctors := ctors.push (← `(Command.ctor| | $name:ident : $type)) + names := names.push name + | _ => Macro.throwUnsupported + return (ctors, names) + +private def altsOf (alts : Array (TSyntax ``modelAlt)) : MacroM (Array (TSyntax ``Term.matchAlt)) := do + let alts ← alts.mapM fun alt => + match alt with + | `(modelAlt| | $patterns,* => $result) => `(Term.matchAltExpr| | $patterns,* => $result) + | _ => Macro.throwUnsupported + return alts.map fun alt => ⟨alt.raw⟩ + +macro_rules + | `($[$doc:docComment]? aggregate $a:ident where $items*) => do + let n (name : Name) : Ident := mkIdentFrom a name + let mut commands : Array Command := #[← `(command| namespace $a)] + let mut hasReply := false + let mut checks : Array Command := #[] + -- Who sends the commands, if the aggregate says. + let mut actor : Option Term := none + for item in items do + if let `(aggregateItem| actor : $type:term) := item then actor := some type + let mut idType : Term ← `(String) + for item in items do + if let `(aggregateItem| id : $type:term) := item then idType := type + commands := commands.push (← `(command| abbrev $(n `Id) : Type := $idType)) + let actorType : Term ← match actor with + | some type => pure type + | none => `(Unit) + commands := commands.push (← `(command| abbrev $(n `Actor) : Type := $actorType)) + -- `decide` takes the actor first when there is one. + let decideCall : Term ← match actor with + | some _ => `($(n `decide) actor) + | none => `($(n `decide)) + for item in items do + match item with + | `(aggregateItem| actor : $_) => pure () + | `(aggregateItem| id : $_) => pure () + | `(aggregateItem| command $cases*) => + let mut plain : Array (TSyntax ``caseOf) := #[] + for case in cases do + match case with + | `(commandOf| | $name:ident $binders* $[records $events,*]? $[rejects $rejections,*]?) => + plain := plain.push (← `(caseOf| | $name:ident $binders*)) + let mut arguments : Array Ident := #[] + let mut bracketed := #[] + for binder in binders do + match binder with + | `(callBinder| ($ids* : $type)) => + arguments := arguments ++ ids + bracketed := bracketed.push (← `(bracketedBinder| ($ids* : $type))) + | _ => Macro.throwUnsupported + let sent ← `($(mkIdentFrom name (`Command ++ name.getId)):ident $arguments*) + if let some events := events then + let allowed ← events.getElems.mapM fun event => + `(Term.matchAltExpr| | $(mkIdentFrom event (`Event ++ event.getId)):ident .. => True) + let allowed : Array (TSyntax ``Term.matchAlt) := + (allowed.push (← `(Term.matchAltExpr| | _ => False))).map fun alt => ⟨alt.raw⟩ + checks := checks.push (← withRef name <| do lenient (← `(command| + /-- The command records only the events it says it records. -/ + theorem $(mkIdentFrom name (`records ++ name.getId)):ident + (actor : $(n `Actor)) (state : $(n `State)) $bracketed* (events : List $(n `Event)) + (accepted : $decideCall state $sent = .ok events) : + ∀ event ∈ events, (match event with $allowed:matchAlt*) := by + simp only [$(n `decide):ident] at accepted + (repeat' split at accepted) <;> + first | (simp_all; done) | (cases accepted <;> simp_all; done) | (cases accepted <;> simp; done) | grind | fail "this command can record an event that its records line does not list"))) + if let some rejections := rejections then + let allowed ← rejections.getElems.mapM fun rejection => + `(Term.matchAltExpr| + | $(mkIdentFrom rejection (`Rejection ++ rejection.getId)):ident .. => True) + let allowed : Array (TSyntax ``Term.matchAlt) := + (allowed.push (← `(Term.matchAltExpr| | _ => False))).map fun alt => ⟨alt.raw⟩ + checks := checks.push (← withRef name <| do lenient (← `(command| + /-- The command answers only the rejections it says it answers. -/ + theorem $(mkIdentFrom name (`rejects ++ name.getId)):ident + (actor : $(n `Actor)) (state : $(n `State)) $bracketed* (rejection : $(n `Rejection)) + (rejected : $decideCall state $sent = .error rejection) : + (match rejection with $allowed:matchAlt*) := by + simp only [$(n `decide):ident] at rejected + (repeat' split at rejected) <;> + first | (simp_all; done) | (cases rejected <;> simp_all; done) | (cases rejected <;> simp; done) | grind | fail "this command can be refused with a rejection that its rejects line does not list"))) + | _ => Macro.throwUnsupported + let (ctors, names) ← casesOf (n `Command) plain + commands := commands.push (← `(command| + inductive $(n `Command) where $ctors* + deriving DecidableEq, Repr, Lean.ToJson, Lean.FromJson)) + commands := commands.push (← `(command| derive_tokens $(n `Command))) + let keyAlts ← names.mapM fun name => do + let ctorName := mkIdentFrom name (`Command ++ name.getId) + `(Term.matchAltExpr| | $ctorName:ident id .. => id) + let keyAlts : Array (TSyntax ``Term.matchAlt) := keyAlts.map fun alt => ⟨alt.raw⟩ + commands := commands.push (← `(command| + /-- The instance a command is for: its first field. -/ + def $(n `key) (command : $(n `Command)) : $(n `Id) := match command with $keyAlts:matchAlt*)) + | `(aggregateItem| event $cases*) => + let (ctors, _) ← casesOf (n `Event) cases + commands := commands.push (← `(command| + inductive $(n `Event) where $ctors* deriving DecidableEq, Repr)) + | `(aggregateItem| rejection $cases*) => + let (ctors, _) ← casesOf (n `Rejection) cases + commands := commands.push (← `(command| + inductive $(n `Rejection) where $ctors* deriving DecidableEq, Repr)) + | `(aggregateItem| state $fields*) => + let mut ids : Array Ident := #[] + let mut types : Array Term := #[] + let mut starts : Array Term := #[] + for field in fields do + match field with + | `(fieldOf| $id:ident : $type := $start) => + ids := ids.push id; types := types.push type; starts := starts.push start + | _ => Macro.throwUnsupported + commands := commands.push (← `(command| + structure $(n `State) where + $[$ids:ident : $types := $starts]* + deriving DecidableEq, Repr)) + | `(aggregateItem| decide $alts:modelAlt*) => + let alts ← altsOf alts + match actor with + | some _ => + commands := commands.push (← `(command| + /-- The events a command records, or why it is refused, given who sends it. -/ + def $(n `decide) (actor : $(n `Actor)) (state : $(n `State)) (command : $(n `Command)) : + Except $(n `Rejection) (List $(n `Event)) := + match actor, state, command with $alts:matchAlt*)) + | none => + commands := commands.push (← `(command| + /-- The events a command records, or why it is refused. -/ + def $(n `decide) (state : $(n `State)) (command : $(n `Command)) : + Except $(n `Rejection) (List $(n `Event)) := + match state, command with $alts:matchAlt*)) + | `(aggregateItem| evolve $alts:modelAlt*) => + let alts ← altsOf alts + commands := commands.push (← `(command| + /-- What an event does to the state. -/ + def $(n `evolve) (state : $(n `State)) (event : $(n `Event)) : $(n `State) := + match state, event with $alts:matchAlt*)) + | `(aggregateItem| reply : $type:term $alts:modelAlt*) => + hasReply := true + let alts ← altsOf alts + commands := commands.push (← `(command| abbrev $(n `Reply) : Type := $type)) + commands := commands.push (← `(command| + /-- What an accepted command answers its caller, from the state it left. -/ + def $(n `reply) (state : $(n `State)) (command : $(n `Command)) : $(n `Reply) := + match state, command with $alts:matchAlt*)) + | _ => Macro.throwUnsupported + unless hasReply do + commands := commands.push (← `(command| abbrev $(n `Reply) : Type := Unit)) + commands := commands.push (← `(command| + def $(n `reply) (_ : $(n `State)) (_ : $(n `Command)) : $(n `Reply) := ())) + commands := commands ++ checks + let decideField : Term ← match actor with + | some _ => `(fun ctx state command => $(mkIdentFrom a (`_root_ ++ a.getId ++ `decide)) ctx.actor state command) + | none => `(fun _ state command => $(mkIdentFrom a (`_root_ ++ a.getId ++ `decide)) state command) + let r (name : Name) : Ident := mkIdentFrom a (`_root_ ++ a.getId ++ name) + commands := commands.push (← `(command| end $a)) + commands := commands.push (← `(command| + $[$doc:docComment]? abbrev $a:ident : Alchemy.Aggregate where + name := $(Syntax.mkStrLit (toString a.getId)) + Id := $(r `Id) + State := $(r `State) + Command := $(r `Command) + Event := $(r `Event) + Rejection := $(r `Rejection) + Actor := $(r `Actor) + initial := {} + keyOf := $(r `key) + decide := $decideField + evolve := fun state event _ => $(r `evolve) state event + Reply := $(r `Reply) + reply := $(r `reply))) + return mkNullNode commands + +/-- An aggregate, by the namespace that defines it. -/ +syntax &"aggregate " ident : modelItem +/-- +An aggregate callers cannot command: only the model's own policies and sagas +send it commands. +-/ +syntax &"internal " &"aggregate " ident : modelItem +/-- A call to a system outside the model, and what it answers. -/ +syntax &"call " ident callBinder* " : " term : modelItem +/-- What to do whenever an aggregate records an event: `| id, event => …`. -/ +syntax &"policy " ident &" on " ident modelAlt+ : modelItem +/-- A value folded over an aggregate's events: `| value, event => …`. -/ +syntax &"view " ident &" on " ident " : " term " := " term modelAlt+ : modelItem +/-- A value for each instance of an aggregate, folded over that instance's events. -/ +syntax &"view " ident &" on " ident &" by " &"id" " : " term " := " term modelAlt+ : modelItem +/-- Rows written for an aggregate's events: `| id, event => […]`. -/ +syntax &"projection " ident &" on " ident " : " term modelAlt+ : modelItem + +/-- An ordered log for each instance of an aggregate, that readers follow: `| id, event => […]`. -/ +syntax &"stream " ident &" on " ident " : " term modelAlt+ : modelItem +/-- A question answered from everything recorded: `| log, input => rows`. -/ +syntax &"query " ident "(" term ")" " : " term modelAlt+ : modelItem +/-- +A command decided across several instances at once: `| states, command => …` +answers the events to record on each, or a rejection. +-/ +syntax &"decision " ident "(" term ")" " : " term modelAlt+ : modelItem +/-- +A process with several steps, started by a policy: `| id, input => …`. It is +given what it is started with, may be told a signal while it waits, and may fail. +-/ +syntax &"saga " ident "(" term ")" "(" term ")" " : " term modelAlt+ : modelItem + +syntax (name := modelCommand) (docComment)? "model " ident " where" many1Indent(modelItem) : command + +private def under (parent : Ident) (child : Name) : Ident := + mkIdentFrom parent (parent.getId ++ child) + +private def rooted (name : Ident) (child : Name := .anonymous) : Ident := + mkIdentFrom name (`_root_ ++ name.getId ++ child) + +private def text (name : Ident) : StrLit := Syntax.mkStrLit (toString name.getId) + +/-- The cases of a block as `match` alternatives, with one more at the end for everything else. -/ +private def withFallback (alts : Array (TSyntax ``modelAlt)) (fallback : TSyntax ``Term.matchAltExpr) : + MacroM (Array (TSyntax ``Term.matchAlt)) := do + let alts ← alts.mapM fun alt => + match alt with + | `(modelAlt| | $patterns,* => $result) => `(Term.matchAltExpr| | $patterns,* => $result) + | _ => Macro.throwUnsupported + return (alts.push fallback).map fun alt => ⟨alt.raw⟩ + +/-- The cases of a block as `match` alternatives, as written. -/ +private def exactly (alts : Array (TSyntax ``modelAlt)) : MacroM (Array (TSyntax ``Term.matchAlt)) := do + let alts ← alts.mapM fun alt => + match alt with + | `(modelAlt| | $patterns,* => $result) => `(Term.matchAltExpr| | $patterns,* => $result) + | _ => Macro.throwUnsupported + return alts.map fun alt => ⟨alt.raw⟩ + +macro_rules + | `($[$doc:docComment]? model $m:ident where $items*) => do + let mut aggregates : Array Ident := #[] + let mut callCtors := #[] + let mut replyAlts := #[] + let mut callDefs : Array Command := #[] + let mut callNames : Array Ident := #[] + let mut later : Array Command := #[] + let mut policies : Array Ident := #[] + let mut views : Array Ident := #[] + let mut projections : Array Ident := #[] + let mut decisions : Array Ident := #[] + let mut internals : Array Ident := #[] + let mut streams : Array Ident := #[] + let mut queries : Array Ident := #[] + let mut decisionCommands : Array Term := #[] + -- Each saga: its name, what a run is started with, what it can be told, and how it can fail. + let mut sagas : Array (Ident × Term × Term × Term) := #[] + let name := mkIdent `Name + let signature := mkIdent `Signature + let aggregatesId := mkIdent `Aggregates + let callId := mkIdent `Call + for item in items do + match item with + | `(modelItem| aggregate $a:ident) => aggregates := aggregates.push a + | `(modelItem| internal aggregate $a:ident) => + aggregates := aggregates.push a + internals := internals.push a + | `(modelItem| call $c:ident $binders* : $reply:term) => + let mut ctorBinders := #[] + let mut arguments : Array Ident := #[] + let mut types : Array Term := #[] + for binder in binders do + match binder with + | `(callBinder| ($ids* : $type)) => + ctorBinders := ctorBinders.push (← `(bracketedBinder| ($ids* : $type))) + arguments := arguments ++ ids + types := types ++ ids.map fun _ => type + | _ => Macro.throwUnsupported + let ctorType ← types.foldrM (fun type rest => `($type → $rest)) (← `($callId)) + callNames := callNames.push c + callCtors := callCtors.push (← `(Command.ctor| | $c:ident : $ctorType)) + let ctor := under callId c.getId + replyAlts := replyAlts.push (← `(Term.matchAltExpr| | $ctor:ident .. => $reply)) + callDefs := callDefs.push (← `(command| + def $c:ident $ctorBinders* : Alchemy.Program $signature $reply := + Alchemy.Program.request (σ := $signature) ($ctor:ident $arguments*))) + | `(modelItem| policy $p:ident on $a:ident $alts:modelAlt*) => + policies := policies.push p + let alts ← withFallback alts (← `(Term.matchAltExpr| | _, _ => pure ())) + later := later.push (← lenient <| ← `(command| + def $p:ident : Alchemy.Policy $signature := + Alchemy.Policy.on $(text p) $(under name a.getId) + fun (id : $(rooted a `Id)) (event : $(rooted a `Event)) => + match id, event with $alts:matchAlt*)) + | `(modelItem| view $v:ident on $a:ident : $type := $initial:term $alts:modelAlt*) => + views := views.push v + let step := under v `step + let alts ← withFallback alts (← `(Term.matchAltExpr| | state, _ => state)) + later := later.push (← lenient <| ← `(command| + def $step:ident (state : $type) : Alchemy.Emitted $aggregatesId → $type + | ⟨$(under name a.getId), _, event, _, _⟩ => + match state, (event : $(rooted a `Event)) with $alts:matchAlt* + | _ => state)) + later := later.push (← `(command| + abbrev $v:ident : Alchemy.View $aggregatesId := + Alchemy.View.fold $(text v) $initial $step)) + later := later.push (← `(command| + /-- The view is exactly its step folded over the log, whatever was recorded. -/ + theorem $(under v `exact):ident (log : List (Alchemy.Emitted $aggregatesId)) : + Alchemy.View.stateAt $v log () = log.foldl $step $initial := + Alchemy.View.fold_exact _ _ _ log)) + | `(modelItem| view $v:ident on $a:ident by id : $type := $initial:term $alts:modelAlt*) => + views := views.push v + let step := under v `step + let keyOf := under v `key + let alts ← withFallback alts (← `(Term.matchAltExpr| | state, _ => state)) + later := later.push (← lenient <| ← `(command| + def $step:ident (state : $type) : Alchemy.Emitted $aggregatesId → $type + | ⟨$(under name a.getId), _, event, _, _⟩ => + match state, (event : $(rooted a `Event)) with $alts:matchAlt* + | _ => state)) + later := later.push (← lenient <| ← `(command| + /-- The instance an event is about, if it is one of this aggregate's. -/ + def $keyOf:ident : Alchemy.Emitted $aggregatesId → Option $(rooted a `Id) + | ⟨$(under name a.getId), id, _, _, _⟩ => some id + | _ => none)) + later := later.push (← `(command| + abbrev $v:ident : Alchemy.View $aggregatesId := + Alchemy.View.keyed $(text v) $initial $keyOf $step)) + later := later.push (← `(command| + /-- The view at an instance is exactly its step folded over that instance's events. -/ + theorem $(under v `exact):ident (log : List (Alchemy.Emitted $aggregatesId)) + (id : $(rooted a `Id)) : + Alchemy.View.stateAt $v log id + = log.foldl (fun state event => if $keyOf event = some id then $step state event + else state) $initial := + Alchemy.View.keyed_exact _ _ _ _ log id)) + | `(modelItem| projection $p:ident on $a:ident : $row:term $alts:modelAlt*) => + projections := projections.push p + let rows := under p `rows + let alts ← withFallback alts (← `(Term.matchAltExpr| | _, _ => [])) + later := later.push (← lenient <| ← `(command| + def $rows:ident : Alchemy.Emitted $aggregatesId → List $row + | ⟨$(under name a.getId), id, event, _, _⟩ => + match (id : $(rooted a `Id)), (event : $(rooted a `Event)) with $alts:matchAlt* + | _ => [])) + later := later.push (← `(command| + abbrev $p:ident : Alchemy.Projection $aggregatesId := + Alchemy.Projection.each $(text p) $rows)) + later := later.push (← `(command| + /-- The projection is given exactly each event's rows: none missed, none twice. -/ + theorem $(under p `exact):ident (log : List (Alchemy.Emitted $aggregatesId)) : + Alchemy.Projection.table $p log = log.flatMap $rows := + Alchemy.Projection.each_exact _ _ log)) + | `(modelItem| stream $v:ident on $a:ident : $entry:term $alts:modelAlt*) => + streams := streams.push v + let entries := under v `appended + let alts ← withFallback alts (← `(Term.matchAltExpr| | _, _ => [])) + later := later.push (← lenient <| ← `(command| + def $entries:ident : Alchemy.Emitted $aggregatesId → List ($(rooted a `Id) × $entry) + | ⟨$(under name a.getId), id, event, _, _⟩ => + (match (id : $(rooted a `Id)), (event : $(rooted a `Event)) with $alts:matchAlt*).map + fun entry => (id, entry) + | _ => [])) + later := later.push (← `(command| + abbrev $v:ident : Alchemy.Stream $aggregatesId := Alchemy.Stream.each $(text v) $entries)) + later := later.push (← `(command| + /-- The stream at an instance holds exactly the entries its events gave it, in order. -/ + theorem $(under v `exact):ident (log : List (Alchemy.Emitted $aggregatesId)) + (id : $(rooted a `Id)) : + Alchemy.Stream.entries $v log id + = (log.flatMap $entries).filterMap fun (k, entry) => if k = id then some entry else none := + Alchemy.Stream.each_exact _ _ log id)) + | `(modelItem| query $v:ident ($input:term) : $row:term $alts:modelAlt*) => + queries := queries.push v + let rows := under v `rows + let alts ← exactly alts + later := later.push (← `(command| + def $rows:ident (log : List (Alchemy.Emitted $aggregatesId)) (input : $input) : List $row := + match log, input with $alts:matchAlt*)) + later := later.push (← `(command| + abbrev $v:ident : Alchemy.Query $aggregatesId where + name := $(text v) + Input := $input + Row := $row + Actor := Unit + Rejection := Empty + handle := fun _ log input => .ok ($rows log input))) + | `(modelItem| decision $d:ident ($command:term) : $rejection:term $alts:modelAlt*) => + decisions := decisions.push d + decisionCommands := decisionCommands.push command + let run := under d `decide + let alts ← exactly alts + later := later.push (← `(command| + def $run:ident (states : Alchemy.States $aggregatesId) (command : $command) : + Except $rejection (List (Alchemy.Record $aggregatesId)) := + match states, command with $alts:matchAlt*)) + later := later.push (← `(command| + abbrev $d:ident : Alchemy.Decision $aggregatesId where + name := $(text d) + Command := $command + Rejection := $rejection + Actor := Unit + decide := fun _ states command => $run states command)) + | `(modelItem| saga $g:ident ($input:term) ($signal:term) : $failure:term $alts:modelAlt*) => + sagas := sagas.push (g, input, signal, failure) + let alts ← exactly alts + later := later.push (← `(command| + /-- The saga's steps, for one run. -/ + def $(under g `run):ident (id : String) (input : $input) : + Alchemy.Program $signature Unit := + match id, input with $alts:matchAlt*)) + | _ => Macro.throwUnsupported + let mut commands : Array Command := #[] + commands := commands.push (← `(command| namespace $m)) + let nameCtors ← aggregates.mapM fun a => `(Command.ctor| | $a:ident) + commands := commands.push (← `(command| + /-- The aggregates of the model. -/ + inductive $name where $nameCtors* deriving DecidableEq, Repr)) + let ofAlts ← aggregates.mapM fun a => + `(Term.matchAltExpr| | $(under name a.getId):ident => $(rooted a)) + commands := commands.push (← `(command| + abbrev $aggregatesId : Alchemy.Aggregates where + Name := $name + of := fun name => match name with $ofAlts:matchAlt*)) + commands := commands.push (← `(command| + /-- The calls the model makes to systems outside it. -/ + inductive $callId where $callCtors* deriving DecidableEq, Repr)) + if replyAlts.isEmpty then + commands := commands.push (← `(command| + abbrev $(mkIdent `Reply) : $callId → Type := fun c => nomatch c)) + else + commands := commands.push (← `(command| + abbrev $(mkIdent `Reply) : $callId → Type := fun c => match c with $replyAlts:matchAlt*)) + -- One saga: its own types. Several: a run is named by its saga, and each type is one of theirs. + let several := sagas.size > 1 + let sagaNames := mkIdent `Sagas + let sumInput := mkIdent `SagaInput + let sumSignal := mkIdent `SagaSignal + let sumFailure := mkIdent `SagaFailure + let mut sagaKey : Term ← `(String) + let mut sagaInput : Term ← `(Unit) + let mut sagaSignal : Term ← `(Unit) + let mut sagaFailure : Term ← `(Unit) + if several then + let names ← sagas.mapM fun (g, _, _, _) => `(Command.ctor| | $g:ident) + let inputs ← sagas.mapM fun (g, input, _, _) => `(Command.ctor| | $g:ident (input : $input)) + let signals ← sagas.mapM fun (g, _, signal, _) => `(Command.ctor| | $g:ident (signal : $signal)) + let failures ← sagas.mapM fun (g, _, _, failure) => `(Command.ctor| | $g:ident (failure : $failure)) + commands := commands.push (← `(command| + /-- The sagas of the model. -/ + inductive $sagaNames where $names* deriving DecidableEq, Repr)) + commands := commands.push (← `(command| + /-- What a run is started with: one saga's input. -/ + inductive $sumInput where $inputs*)) + commands := commands.push (← `(command| + /-- What a run can be told while it waits: one saga's signal. -/ + inductive $sumSignal where $signals*)) + commands := commands.push (← `(command| + /-- How a run can fail: one saga's failure. -/ + inductive $sumFailure where $failures* deriving DecidableEq, Repr)) + sagaKey ← `($sagaNames × String) + sagaInput ← `($sumInput) + sagaSignal ← `($sumSignal) + sagaFailure ← `($sumFailure) + else if let some (_, input, signal, failure) := sagas[0]? then + sagaInput := input + sagaSignal := signal + sagaFailure := failure + commands := commands.push (← `(command| + abbrev $signature : Alchemy.Signature where + aggregates := $aggregatesId + Call := $callId + Reply := $(mkIdent `Reply) + Saga := $sagaKey + SagaInput := $sagaInput + Signal := $sagaSignal + Failure := $sagaFailure)) + for (g, input, signal, failure) in sagas do + if several then + commands := commands.push (← `(command| + /-- Start a run of the saga, from a policy. A run already started is left alone. -/ + def $(under g `start):ident (id : String) (input : $input) : Alchemy.Program $signature Unit := + Alchemy.Program.startSaga (σ := $signature) ($(under sagaNames g.getId), id) + ($(under sumInput g.getId) input))) + commands := commands.push (← `(command| + /-- Tell a run of the saga something, from a policy. -/ + def $(under g `signal):ident (id : String) (signal : $signal) : Alchemy.Program $signature Unit := + Alchemy.Program.signalSaga (σ := $signature) ($(under sagaNames g.getId), id) + ($(under sumSignal g.getId) signal))) + commands := commands.push (← `(command| + /-- This saga's failure, as a failure of the model. -/ + abbrev $(under g `failure):ident (failure : $failure) : $sumFailure := + $(under sumFailure g.getId) failure)) + commands := commands.push (← `(command| + /-- Stop this saga: what it registered to undo is undone, newest first. -/ + def $(under g `failWith):ident {α : Type} (failure : $failure) : Alchemy.Program $signature α := + Alchemy.Program.fail ($(under sumFailure g.getId) failure))) + commands := commands.push (← `(command| + /-- Wait for the next signal sent to this run. `none` if it was meant for another saga. -/ + def $(under g `awaitSignal):ident : Alchemy.Program $signature (Option $signal) := + Alchemy.Program.await (σ := $signature) fun told => + match told with + | $(under sumSignal g.getId):ident signal => Alchemy.Program.pure (some signal) + | _ => Alchemy.Program.pure none)) + for a in aggregates do + commands := commands.push (← `(command| + /-- Send the aggregate a command; a rejection fails this saga with what `explain` makes of it. -/ + def $(mkIdentFrom g (g.getId ++ a.getId ++ `must)):ident (command : $(rooted a `Command)) + (explain : $(rooted a `Rejection) → $failure) + (actor : $(rooted a `Actor) := by exact default) : Alchemy.Program $signature Unit := + Alchemy.Program.step ⟨$(under name a.getId), actor, command⟩ + fun rejection => $(under sumFailure g.getId) (explain rejection))) + else + commands := commands.push (← `(command| + /-- Start a run of the saga, from a policy. A run already started is left alone. -/ + def $(under g `start):ident (id : String) (input : $input) : Alchemy.Program $signature Unit := + Alchemy.Program.startSaga (σ := $signature) id input)) + commands := commands.push (← `(command| + /-- Tell a run of the saga something, from a policy. -/ + def $(under g `signal):ident (id : String) (signal : $signal) : Alchemy.Program $signature Unit := + Alchemy.Program.signalSaga (σ := $signature) id signal)) + commands := commands.push (← `(command| + /-- Wait for the next signal sent to this run of the saga. -/ + def $(mkIdent `awaitSignal) : Alchemy.Program $signature $sagaSignal := + Alchemy.Program.awaitSignal (σ := $signature))) + commands := commands.push (← `(command| + /-- Stop the saga: what it registered to undo is undone, newest first. -/ + def $(mkIdent `failWith) {α : Type} (failure : $sagaFailure) : Alchemy.Program $signature α := + Alchemy.Program.fail failure)) + commands := commands ++ callDefs + for a in aggregates do + commands := commands.push (← `(command| + /-- Send this aggregate a command, from a policy. -/ + def $(under a `send):ident (command : $(rooted a `Command)) + (actor : $(rooted a `Actor) := by exact default) : Alchemy.Program $signature Unit := + Alchemy.Program.tell ⟨$(under name a.getId), actor, command⟩)) + commands := commands.push (← `(command| + /-- Send this aggregate a command; a rejection fails the saga with what `explain` makes of it. -/ + def $(under a `must):ident (command : $(rooted a `Command)) + (explain : $(rooted a `Rejection) → $sagaFailure) + (actor : $(rooted a `Actor) := by exact default) : Alchemy.Program $signature Unit := + Alchemy.Program.step ⟨$(under name a.getId), actor, command⟩ explain)) + commands := commands.push (← `(command| + /-- From here on, if the saga fails, send this aggregate this command. -/ + def $(under a `undoWith):ident (command : $(rooted a `Command)) + (actor : $(rooted a `Actor) := by exact default) : Alchemy.Program $signature Unit := + Alchemy.Program.undoWith fun _ => ⟨$(under name a.getId), actor, command⟩)) + commands := commands.push (← `(command| + /-- An event to record on an instance of this aggregate, in a decision. -/ + def $(under a `record):ident (id : $(rooted a `Id)) (event : $(rooted a `Event)) : + Alchemy.Record $aggregatesId := + ⟨$(under name a.getId), id, event⟩)) + commands := commands.push (← `(command| + /-- The state of an instance of this aggregate, in a decision. -/ + def $(under a `of):ident (states : Alchemy.States $aggregatesId) (id : $(rooted a `Id)) : + $(rooted a `State) := + states $(under name a.getId) id)) + commands := commands ++ later + commands := commands.push (← `(command| end $m)) + let sagaRun : Term ← if several then do + let runs ← sagas.mapM fun (g, _, _, _) => + `(Term.matchAltExpr| + | ($(under (under m `Sagas) g.getId):ident, id), $(under (under m `SagaInput) g.getId):ident input => + $(under m (g.getId ++ `run)) id input) + let runs : Array (TSyntax ``Term.matchAlt) := + (runs.push (← `(Term.matchAltExpr| | _, _ => Alchemy.Program.pure ()))).map fun alt => ⟨alt.raw⟩ + `(fun key input => match key, input with $runs:matchAlt*) + else match sagas[0]? with + | some (g, _, _, _) => `($(under m (g.getId ++ `run))) + | none => `(fun _ _ => Alchemy.Program.pure ()) + let publics := aggregates.filter fun a => !internals.any (·.getId == a.getId) + let offeredTerm : Term ← if internals.isEmpty then `(fun _ => True) else do + let closed ← internals.mapM fun a => + `(Term.matchAltExpr| | $(under (under m `Name) a.getId):ident => False) + let closed : Array (TSyntax ``Term.matchAlt) := + (closed.push (← `(Term.matchAltExpr| | _ => True))).map fun alt => ⟨alt.raw⟩ + `(fun s => match s.to with $closed:matchAlt*) + commands := commands.push (← `(command| + $[$doc:docComment]? abbrev $m:ident : Alchemy.Model where + name := $(text m) + signature := $(under m `Signature) + decisions := [$[$(decisions.map (under m ·.getId))],*] + policies := [$[$(policies.map (under m ·.getId))],*] + views := [$[$(views.map (under m ·.getId))],*] + projections := [$[$(projections.map (under m ·.getId))],*] + streams := [$[$(streams.map (under m ·.getId))],*] + queries := [$[$(queries.map (under m ·.getId))],*] + saga := $sagaRun + offered := $offeredTerm)) + -- What callers send, how the model is served, and each aggregate's rules lifted to the model. + commands := commands.push (← `(command| namespace $m)) + -- The model as it is stored: its policies and views look at an event as it is, so each + -- can be kept up one delivered event at a time. + let plain := mkIdent `plain + if policies.isEmpty then + commands := commands.push (← `(command| + /-- Every policy reacts to an event as it is. -/ + theorem $plain : Alchemy.Model.Local $(rooted m) := by + intro p mem; cases mem)) + else + commands := commands.push (← `(command| + /-- Every policy reacts to an event as it is. -/ + theorem $plain : Alchemy.Model.Local $(rooted m) := by + intro p mem history e + simp only [List.mem_cons, List.not_mem_nil, or_false] at mem + repeat' (first | (cases mem; done) | (rcases mem with h | mem; subst h) | subst mem) + all_goals rfl)) + let readsId := mkIdent `reads + let mut readSide : Term ← `(Alchemy.ReadSide.none $aggregatesId) + for p in projections.reverse do + readSide ← `(Alchemy.ReadSide.both (Alchemy.Projection.reads $p) $readSide) + for v in views.reverse do + readSide ← `(Alchemy.ReadSide.both (Alchemy.View.reads $v) $readSide) + commands := commands.push (← `(command| + /-- What is read from the model, as it is stored: each view's state and each table's rows. -/ + def $readsId : Alchemy.ReadSide $aggregatesId := $readSide)) + let mut place : Term ← `(stored) + let localTactic ← `(tactic| + (intro history e; obtain ⟨n, id, event, seq, time⟩ := e; cases n <;> rfl)) + for v in views do + commands := commands.push (← `(command| + /-- The view looks at an event as it is. -/ + theorem $(under v `plain):ident : Alchemy.View.Local $v := by $localTactic:tactic)) + commands := commands.push (← `(command| + /-- The view as it is stored. -/ + def $(under v `held):ident (stored : Alchemy.ReadSide.State $readsId) : + Alchemy.ReadSide.State (Alchemy.View.reads $v) := ($place).1)) + commands := commands.push (← `(command| + /-- The stored view, after every event, is the view the model computes from the log. -/ + theorem $(under v `stored):ident (log : List (Alchemy.Emitted $aggregatesId)) + (key : Alchemy.View.Key $v) : + $(under v `held) ((log.map Alchemy.Emitted.unplaced).foldl + (Alchemy.ReadSide.apply $readsId) (Alchemy.ReadSide.initial $readsId)) key + = Alchemy.View.stateAt $v log key := by + simp only [$readsId:ident, Alchemy.ReadSide.both_fold, $(under v `held):ident] + exact Alchemy.View.reads_exact _ $(under v `plain) log key)) + place ← `(($place).2) + for p in projections do + commands := commands.push (← `(command| + /-- The table's rows for an event depend on that event alone. -/ + theorem $(under p `plain):ident : Alchemy.Projection.Local $p := by $localTactic:tactic)) + commands := commands.push (← `(command| + /-- The table as it is stored. -/ + def $(under p `held):ident (stored : Alchemy.ReadSide.State $readsId) : + Alchemy.ReadSide.State (Alchemy.Projection.reads $p) := ($place).1)) + commands := commands.push (← `(command| + /-- The stored table, after every event, is the table the model computes from the log. -/ + theorem $(under p `stored):ident (log : List (Alchemy.Emitted $aggregatesId)) : + $(under p `held) ((log.map Alchemy.Emitted.unplaced).foldl + (Alchemy.ReadSide.apply $readsId) (Alchemy.ReadSide.initial $readsId)) + = Alchemy.Projection.table $p log := by + simp only [$readsId:ident, Alchemy.ReadSide.both_fold, $(under p `held):ident] + exact Alchemy.Projection.reads_exact _ $(under p `plain) log)) + place ← `(($place).2) + commands := commands.push (← `(command| + /-- The model run on services: the same engine, wherever its state is kept. -/ + abbrev $(mkIdent `Stored) (μ : Type → Type) := Alchemy.Engine μ $(rooted m) $readsId)) + commands := commands.push (← `(command| + /-- Everything the model asks of its host. -/ + abbrev $(mkIdent `Services) (μ : Type → Type) := Alchemy.Services μ $signature $readsId)) + let input := mkIdent `Input + let inputCtors ← publics.mapM fun a => + `(Command.ctor| | $a:ident (command : $(rooted a `Command)) + (actor : $(rooted a `Actor) := by exact default)) + commands := commands.push (← `(command| + /-- What callers send: a command for one of the aggregates. -/ + inductive $input where $inputCtors*)) + commands := commands.push (← `(command| derive_tokens $input)) + let commandAlts ← publics.mapM fun a => + `(Term.matchAltExpr| | $(under input a.getId):ident command actor => + ⟨$(under name a.getId), actor, command⟩) + let served := mkIdent `served + if decisions.isEmpty then + commands := commands.push (← `(command| + /-- How the model is spoken to: callers send commands, and its history is written as JSON. -/ + abbrev $served : Alchemy.Cloud.Served $(rooted m) where + Input := $input + command := fun input => match input with $commandAlts:matchAlt* + offered := by intro input; cases input <;> exact True.intro)) + else + let deciding := mkIdent `Deciding + let decidingCtors ← (decisions.zip decisionCommands).mapM fun (d, command) => + `(Command.ctor| | $d:ident (command : $command)) + commands := commands.push (← `(command| + /-- What callers send that is decided across instances. -/ + inductive $deciding where $decidingCtors*)) + commands := commands.push (← `(command| derive_tokens $deciding)) + let decisionAlts ← decisions.mapM fun d => + `(Term.matchAltExpr| | $(under deciding d.getId):ident command => + ⟨$(under m d.getId), ⟨by repeat (first | exact List.Mem.head _ | apply List.Mem.tail)⟩, + (), command⟩) + let decisionAlts : Array (TSyntax ``Term.matchAlt) := decisionAlts.map fun alt => ⟨alt.raw⟩ + commands := commands.push (← `(command| + /-- + How the model is spoken to: callers send commands and ask for decisions, + and its history is written as JSON. + -/ + abbrev $served : Alchemy.Cloud.Served $(rooted m) where + Input := $input + command := fun input => match input with $commandAlts:matchAlt* + offered := by intro input; cases input <;> exact True.intro + Deciding := $deciding + decision := fun input => match input with $decisionAlts:matchAlt*)) + for a in aggregates do + let always := mkIdent (a.getId ++ `always) + let here := under name a.getId + commands := commands.push (← `(command| + /-- + A rule the aggregate keeps holds of every instance, in every world the + model can reach. With decisions in the model, they must keep it too. + -/ + theorem $always {P : $(rooted a `State) → Prop} + (initially : P (Alchemy.Aggregate.initial $(rooted a))) + (kept : Alchemy.Aggregate.Keeps $(rooted a) P) + (w : Alchemy.World $signature) (reach : Alchemy.Model.Reachable $(rooted m) w) + (id : $(rooted a `Id)) + (decided : ∀ d ∈ Alchemy.Model.decisions $(rooted m), + ∀ (r : Alchemy.Recorded $aggregatesId) (ctx : Alchemy.Context d.Actor) c, + (∀ id, P (r.state $here id)) → ∀ id, P ((r.decide d ctx c).state $here id) := by + intro d mem; cases mem) : + P (w.state $here id) := + Alchemy.Model.alwaysAtWith $(rooted m) $here P initially kept decided w reach id)) + commands := commands.push (← `(command| + /-- And of the model as deployed, whatever its journal holds. -/ + theorem $(mkIdent (a.getId ++ `deployed)) {P : $(rooted a `State) → Prop} + (initially : P (Alchemy.Aggregate.initial $(rooted a))) + (kept : Alchemy.Aggregate.Keeps $(rooted a) P) + (journal : List Alchemy.Cloud.Journal.Line) (id : $(rooted a `Id)) + (decided : ∀ d ∈ Alchemy.Model.decisions $(rooted m), + ∀ (r : Alchemy.Recorded $aggregatesId) (ctx : Alchemy.Context d.Actor) c, + (∀ id, P (r.state $here id)) → ∀ id, P ((r.decide d ctx c).state $here id) := by + intro d mem; cases mem) : + P ((Alchemy.Cloud.Served.replay $served journal).state $here id) := + $always initially kept _ (Alchemy.Cloud.Served.replay_reachable $served journal) id decided)) + if decisions.isEmpty then + for a in aggregates do + let here := under name a.getId + let explained := mkIdent (a.getId ++ `explained) + commands := commands.push (← `(command| + /-- + A rule that ties an instance's state to the events it recorded holds of + every instance, in every world the model can reach. + -/ + theorem $explained + {R : $(rooted a `State) → List $(rooted a `Event) → Prop} + (explains : Alchemy.Aggregate.Explains $(rooted a) R) + (w : Alchemy.World $signature) (reach : Alchemy.Model.Reachable $(rooted m) w) + (id : $(rooted a `Id)) : + R (w.state $here id) (Alchemy.Recorded.eventsAt w.toRecorded $here id) := + Alchemy.Model.explained $(rooted m) rfl $here explains w reach id)) + commands := commands.push (← `(command| + /-- A quantity the aggregate tallies is, of every instance, the worth of everything it recorded. -/ + theorem $(mkIdent (a.getId ++ `tallied)) + {quantity : $(rooted a `State) → Int} {worth : $(rooted a `Event) → Int} + (tallies : Alchemy.Aggregate.Tallies $(rooted a) quantity worth) + (w : Alchemy.World $signature) (reach : Alchemy.Model.Reachable $(rooted m) w) + (id : $(rooted a `Id)) : + quantity (w.state $here id) = quantity (Alchemy.Aggregate.initial $(rooted a)) + + ((Alchemy.Recorded.eventsAt w.toRecorded $here id).map worth).sum := + $explained tallies.explains w reach id)) + commands := commands.push (← `(command| + /-- An event the aggregate records only after another comes after it, on every instance. -/ + theorem $(mkIdent (a.getId ++ `follows)) + {cause effect : $(rooted a `Event) → Prop} {seen : $(rooted a `State) → Prop} + (precedes : Alchemy.Aggregate.Precedes $(rooted a) cause effect seen) + (w : Alchemy.World $signature) (reach : Alchemy.Model.Reachable $(rooted m) w) + (id : $(rooted a `Id)) : + Alchemy.Aggregate.Follows cause effect + (Alchemy.Recorded.eventsAt w.toRecorded $here id) := + ($explained precedes.explains w reach id).2)) + commands := commands.push (← `(command| end $m)) + -- What a behaviour proof steps through: the model's own definitions. + let mut stepped : Array Ident := #[] + for a in aggregates do + stepped := stepped ++ #[rooted a `decide, rooted a `evolve, rooted a `key, rooted a `reply] + for helper in [`send, `must, `undoWith, `record, `of] do + stepped := stepped.push (under m (a.getId ++ helper)) + for p in policies do stepped := stepped.push (under m p.getId) + for d in decisions do stepped := stepped.push (under m (d.getId ++ `decide)) + for c in callNames do stepped := stepped.push (under m c.getId) + for (g, _, _, _) in sagas do + for helper in (if several then [`run, `start, `signal, `failWith] else [`run, `start, `signal]) do + stepped := stepped.push (under m (g.getId ++ helper)) + if several then + stepped := stepped.push (under m (g.getId ++ `awaitSignal)) + for a in aggregates do stepped := stepped.push (under m (g.getId ++ a.getId ++ `must)) + stepped := stepped ++ #[under m `awaitSignal, under m `failWith] + commands := commands.push (← `(command| attribute [behaviour] $stepped*)) + return mkNullNode commands + +end Alchemy diff --git a/packages/alchemy-lean/Alchemy/View.lean b/packages/alchemy-lean/Alchemy/View.lean new file mode 100644 index 00000000000..8a5e304a471 --- /dev/null +++ b/packages/alchemy-lean/Alchemy/View.lean @@ -0,0 +1,295 @@ +import Alchemy.Signature + +/-! +What is read from a model. Each is a function of the log of recorded events, +so a read can never disagree with what was recorded. +-/ +namespace Alchemy + +variable {g : Aggregates} + +/-- How one event changes a view at one key, and what the view emits for it. -/ +structure View.Update (Key State Event : Type) where + key : Key + evolve : State → State + /-- The view's own events, from the state before and after. -/ + emit : State → State → List Event := fun _ _ => [] + +/-- A read model, keyed by what it is about. -/ +structure View (g : Aggregates) where + name : String + Key : Type + State : Type + /-- The events the view itself emits. -/ + Event : Type + /-- Who reads it. -/ + Actor : Type + Rejection : Type + initial : State + /-- What an event does to the view, given the events before it. -/ + on : List (Emitted g) → Emitted g → List (View.Update Key State Event) + /-- Whether this actor may read this key. -/ + validate : Actor → Key → State → Except Rejection Unit := fun _ _ _ => .ok () + [decEqKey : DecidableEq Key] + [decEqState : DecidableEq State] + [decEqEvent : DecidableEq Event] + [decEqRejection : DecidableEq Rejection] + +namespace View + +attribute [instance] View.decEqKey View.decEqState View.decEqEvent View.decEqRejection + +variable (v : View g) + +/-- One event applied to the state at a key. -/ +def applyAt (history : List (Emitted g)) (e : Emitted g) (key : v.Key) (s : v.State) : v.State := + (v.on history e).foldl (fun s u => if u.key = key then u.evolve s else s) s + +def go (key : v.Key) : List (Emitted g) → List (Emitted g) → v.State → v.State + | _, [], s => s + | history, e :: rest, s => go key (history ++ [e]) rest (v.applyAt history e key s) + +/-- The view at a key, after everything in the log. -/ +def stateAt (log : List (Emitted g)) (key : v.Key) : v.State := + v.go key [] log v.initial + +/-- The view's own events for one event, given the events before it. -/ +def emittedBy (history : List (Emitted g)) (e : Emitted g) : List (v.Key × v.Event) := + (v.on history e).flatMap fun u => + let before := v.stateAt history u.key + (u.emit before (u.evolve before)).map fun x => (u.key, x) + +def emittedGo : List (Emitted g) → List (Emitted g) → List (v.Key × v.Event) + | _, [] => [] + | history, e :: rest => v.emittedBy history e ++ emittedGo (history ++ [e]) rest + +/-- Every event the view emitted at a key, in order. -/ +def emittedAt (log : List (Emitted g)) (key : v.Key) : List v.Event := + (v.emittedGo [] log).filterMap fun (k, x) => if k = key then some x else none + +/-- The view at a key, for an actor who may read it. -/ +def read (actor : v.Actor) (log : List (Emitted g)) (key : v.Key) : Except v.Rejection v.State := + let s := v.stateAt log key + (v.validate actor key s).map fun _ => s + +end View + +/-- Rows written to a store outside the model, one batch per event. -/ +structure Projection (g : Aggregates) where + name : String + Row : Type + write : List (Emitted g) → Emitted g → List Row + +namespace Projection + +def go (p : Projection g) : List (Emitted g) → List (Emitted g) → List p.Row + | _, [] => [] + | history, e :: rest => p.write history e ++ go p (history ++ [e]) rest + +/-- Everything the projection was given. -/ +def table (p : Projection g) (log : List (Emitted g)) : List p.Row := + p.go [] log + +end Projection + +/-- An ordered log per key that clients read. -/ +structure Stream (g : Aggregates) where + name : String + Key : Type + Entry : Type + Actor : Type + Rejection : Type + append : List (Emitted g) → Emitted g → List (Key × Entry) + /-- Whether this actor may read this key, given its latest entry. -/ + validate : Actor → Key → Option Entry → Except Rejection Unit := fun _ _ _ => .ok () + [decEqKey : DecidableEq Key] + [decEqEntry : DecidableEq Entry] + +namespace Stream + +attribute [instance] Stream.decEqKey Stream.decEqEntry + +def go (s : Stream g) : List (Emitted g) → List (Emitted g) → List (s.Key × s.Entry) + | _, [] => [] + | history, e :: rest => s.append history e ++ go s (history ++ [e]) rest + +def entries (s : Stream g) (log : List (Emitted g)) (key : s.Key) : List s.Entry := + (s.go [] log).filterMap fun (k, x) => if k = key then some x else none + +def read (s : Stream g) (actor : s.Actor) (log : List (Emitted g)) (key : s.Key) : + Except s.Rejection (List s.Entry) := + let all := s.entries log key + (s.validate actor key all.getLast?).map fun _ => all + +end Stream + +/-- One page of a query's rows, and where the next page starts. -/ +structure Page (Row : Type) where + entries : List Row + cursor : Option Nat +deriving DecidableEq, Repr + +/-- A question across keys, answered from the log by a handler that judges the caller. -/ +structure Query (g : Aggregates) where + name : String + Input : Type + Row : Type + Actor : Type + Rejection : Type + handle : Actor → List (Emitted g) → Input → Except Rejection (List Row) + +namespace Query + +/-- A page of the rows: `take` of them, after the first `after`. -/ +def ask (q : Query g) (actor : q.Actor) (log : List (Emitted g)) (input : q.Input) + (after : Nat := 0) (take : Nat := 50) : Except q.Rejection (Page q.Row) := + (q.handle actor log input).map fun rows => + let rest := rows.drop after + { entries := rest.take take + cursor := if rest.length > take then some (after + take) else none } + +end Query +end Alchemy + +namespace Alchemy + +variable {g : Aggregates} + +/-- A view with one value, folded over every event. -/ +abbrev View.fold {State : Type} [DecidableEq State] (name : String) (initial : State) + (step : State → Emitted g → State) : View g where + name := name + Key := Unit + State := State + Event := Empty + Actor := Unit + Rejection := Empty + initial := initial + on := fun _ event => [{ key := (), evolve := fun state => step state event }] + +theorem View.fold_go {State : Type} [DecidableEq State] (name : String) (initial : State) + (step : State → Emitted g → State) (history log : List (Emitted g)) (state : State) : + (View.fold name initial step).go () history log state = log.foldl step state := by + induction log generalizing history state with + | nil => rfl + | cons event rest ih => + show (View.fold name initial step).go () (history ++ [event]) rest + ((View.fold name initial step).applyAt history event () state) = _ + rw [ih] + simp [View.applyAt] + +/-- A folded view is exactly the fold of its step over the log, whatever was recorded. -/ +theorem View.fold_exact {State : Type} [DecidableEq State] (name : String) (initial : State) + (step : State → Emitted g → State) (log : List (Emitted g)) : + (View.fold name initial step).stateAt log () = log.foldl step initial := + View.fold_go name initial step [] log initial + +/-- A projection that writes rows for each event by itself. -/ +abbrev Projection.each {Row : Type} (name : String) (rows : Emitted g → List Row) : Projection g where + name := name + Row := Row + write := fun _ event => rows event + +theorem Projection.each_go {Row : Type} (name : String) (rows : Emitted g → List Row) + (history log : List (Emitted g)) : + (Projection.each name rows).go history log = log.flatMap rows := by + induction log generalizing history with + | nil => rfl + | cons event rest ih => + show rows event ++ (Projection.each name rows).go (history ++ [event]) rest = _ + rw [ih] + rfl + +/-- Such a projection is given exactly each event's rows, in order: none missed, none twice. -/ +theorem Projection.each_exact {Row : Type} (name : String) (rows : Emitted g → List Row) + (log : List (Emitted g)) : (Projection.each name rows).table log = log.flatMap rows := + Projection.each_go name rows [] log + +end Alchemy + +namespace Alchemy + +variable {g : Aggregates} + +/-- A view with a value for each key, folded over the events that are about that key. -/ +abbrev View.keyed {Key State : Type} [DecidableEq Key] [DecidableEq State] (name : String) + (initial : State) (key : Emitted g → Option Key) (step : State → Emitted g → State) : View g where + name := name + Key := Key + State := State + Event := Empty + Actor := Unit + Rejection := Empty + initial := initial + on := fun _ event => + match key event with + | some k => [{ key := k, evolve := fun state => step state event }] + | none => [] + +theorem View.keyed_go {Key State : Type} [DecidableEq Key] [DecidableEq State] (name : String) + (initial : State) (key : Emitted g → Option Key) (step : State → Emitted g → State) (k : Key) + (history log : List (Emitted g)) (state : State) : + (View.keyed name initial key step).go k history log state + = log.foldl (fun state event => if key event = some k then step state event else state) state := by + induction log generalizing history state with + | nil => rfl + | cons event rest ih => + show (View.keyed name initial key step).go k (history ++ [event]) rest + ((View.keyed name initial key step).applyAt history event k state) = _ + rw [ih, List.foldl_cons] + congr 1 + show ((match key event with + | some k => [({ key := k, evolve := fun state => step state event } : + View.Update Key State Empty)] + | none => []).foldl (fun s (u : View.Update Key State Empty) => + if u.key = k then u.evolve s else s) state) = _ + cases found : key event with + | none => simp + | some k' => + by_cases same : k' = k + · subst same; simp + · simp [same] + +/-- A keyed view at a key is exactly its step folded over the events about that key. -/ +theorem View.keyed_exact {Key State : Type} [DecidableEq Key] [DecidableEq State] (name : String) + (initial : State) (key : Emitted g → Option Key) (step : State → Emitted g → State) + (log : List (Emitted g)) (k : Key) : + (View.keyed name initial key step).stateAt log k + = log.foldl (fun state event => if key event = some k then step state event else state) + initial := + View.keyed_go name initial key step k [] log initial + +end Alchemy + +namespace Alchemy + +variable {g : Aggregates} + +/-- A stream that appends entries for each event by itself. -/ +abbrev Stream.each {Key Entry : Type} [DecidableEq Key] [DecidableEq Entry] (name : String) + (entries : Emitted g → List (Key × Entry)) : Stream g where + name := name + Key := Key + Entry := Entry + Actor := Unit + Rejection := Empty + append := fun _ event => entries event + +theorem Stream.each_go {Key Entry : Type} [DecidableEq Key] [DecidableEq Entry] (name : String) + (entries : Emitted g → List (Key × Entry)) (history log : List (Emitted g)) : + (Stream.each name entries).go history log = log.flatMap entries := by + induction log generalizing history with + | nil => rfl + | cons event rest ih => + show entries event ++ (Stream.each name entries).go (history ++ [event]) rest = _ + rw [ih] + rfl + +/-- Such a stream holds, at a key, exactly the entries its events gave that key, in order. -/ +theorem Stream.each_exact {Key Entry : Type} [DecidableEq Key] [DecidableEq Entry] (name : String) + (entries : Emitted g → List (Key × Entry)) (log : List (Emitted g)) (key : Key) : + (Stream.each name entries).entries log key + = (log.flatMap entries).filterMap fun (k, entry) => if k = key then some entry else none := by + simp [Stream.entries, Stream.each_go] + +end Alchemy diff --git a/packages/alchemy-lean/Dockerfile b/packages/alchemy-lean/Dockerfile new file mode 100644 index 00000000000..3c5228f2e83 --- /dev/null +++ b/packages/alchemy-lean/Dockerfile @@ -0,0 +1,24 @@ +# The bank server: built with Lean, run on a small image. +# +# docker build -t lean-bank . && docker run -p 8787:8787 -v bank:/data lean-bank +FROM debian:bookworm-slim AS build +RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates git \ + && rm -rf /var/lib/apt/lists/* +RUN curl -sSf https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain none +WORKDIR /src +COPY lean-toolchain lakefile.toml lake-manifest.json ./ +RUN /root/.elan/bin/lake --version +COPY Alchemy.lean ./ +COPY Alchemy ./Alchemy +COPY examples ./examples +RUN /root/.elan/bin/lake build bank + +FROM debian:bookworm-slim +# curl is how the server calls the outside systems at FRAUD_URL and PAYMENTS_URL. +RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates \ + && rm -rf /var/lib/apt/lists/* +COPY --from=build /src/.lake/build/bin/bank /usr/local/bin/bank +VOLUME /data +EXPOSE 8787 +CMD ["bank", "/data/bank.journal", "8787", "public"] diff --git a/packages/alchemy-lean/GUIDE.md b/packages/alchemy-lean/GUIDE.md new file mode 100644 index 00000000000..6c3178fc58f --- /dev/null +++ b/packages/alchemy-lean/GUIDE.md @@ -0,0 +1,387 @@ +# A guide to alchemy-lean + +This walks through one program, `examples/Shop.lean`, from nothing. Each step has the code, how to read it, and what it gives you. Every snippet compiles. + +## 1. Describe a thing: the aggregate + +An aggregate is something whose rules must hold together, here an order. You list what it can be asked, what it records, how it refuses, and what it remembers. + +```lean +aggregate Order where + command + | place (id item : String) (amount : Nat) + records placed + rejects alreadyPlaced, nothingToCharge + | settle (id charge : String) + records paid + rejects notAwaitingPayment + | decline (id reason : String) + records declined + rejects notAwaitingPayment + + event + | placed (item : String) (amount : Nat) + | paid (charge item : String) (amount : Nat) + | declined (reason : String) + + rejection + | alreadyPlaced + | nothingToCharge + | notAwaitingPayment + + state + status : Status := .new + item : String := "" + amount : Nat := 0 + charged : Nat := 0 +``` + +**Reading it.** Each `|` line is one case. `(id item : String)` is two fields, both strings. `Nat` is a whole number that cannot be negative. In `state`, `:= .new` is the starting value. + +## 2. Give it behaviour: decide and evolve + +Two functions hold all the logic. `decide` answers a command; `evolve` applies one event. + +```lean + decide + | s, .place _ item amount => + if s.status ≠ .new then .error .alreadyPlaced + else if amount = 0 then .error .nothingToCharge + else .ok [.placed item amount] + | s, .settle _ charge => + if s.status = .awaitingPayment then .ok [.paid charge s.item s.amount] + else .error .notAwaitingPayment + | s, .decline _ reason => + if s.status = .awaitingPayment then .ok [.declined reason] + else .error .notAwaitingPayment + + evolve + | s, .placed item amount => { s with status := .awaitingPayment, item, amount } + | s, .paid charge _ amount => { s with status := .paid charge, charged := s.charged + amount } + | s, .declined reason => { s with status := .declined reason } + + reply : Status + | s, _ => s.status +``` + +**Reading it.** Each `| pattern => result` is a branch, like a `switch`. `s` is the current state, and `_` is a field that is not used. `.ok [...]` accepts and lists events; `.error ...` refuses. `{ s with status := … }` is a copy of `s` with some fields changed. `reply` is what an accepted command answers, from the state it left. + +**What you get.** `decide` only answers and `evolve` is the only place state changes. The `records` and `rejects` lines of step 1 are checked against `decide`: omit a rejection it can give, or name an event it cannot record, and the file does not compile. + +## 3. Say what is always true: an invariant + +A rule about the state, and one line proving no command breaks it. + +```lean +def ChargedOnce (s : Order.State) : Prop := + (s.status = .new ∨ s.status = .awaitingPayment → s.charged = 0) ∧ s.charged ≤ s.amount + +theorem chargedOnce : Order.Keeps ChargedOnce := by + aggregate_rule +``` + +**Reading it.** `Prop` is a statement that is true or false. `∨` is or, `∧` is and, `→` is implies. `theorem name : claim := by tactic` is a claim and how to prove it. `aggregate_rule` tries every command and every branch of `decide`. + +**What you get.** Unlike a test, this covers every order and every sequence of commands. Delete the status check from `settle` and this line fails. + +## 4. Say what happens in a case: behaviour + +Given some history, when a command arrives, then this result. + +```lean +theorem aPaidOrderIsNeverChargedAgain (id item charge again : String) (amount : Nat) : + Order.decide (Order.after [.placed item amount, .paid charge item amount]) (.settle id again) + = .error .notAwaitingPayment := by + simp [Aggregate.after, Aggregate.apply, Order.decide, Order.evolve] +``` + +**Reading it.** The names in brackets before the `:` are "for every". `Order.after [events]` is the state after those events. A call has no brackets or commas: `f a b` is `f(a, b)`. `simp` proves it by unfolding the named definitions and computing. + +General properties are stated the same way. Every order command is idempotent, so a caller unsure it arrived can send it again: + +```lean +theorem everyOrderCommandIsIdempotent : Order.Idempotent := by + command_law +``` + +## 5. Connect things: the model + +A model joins aggregates to each other and to the outside world. + +```lean +model Shop where + aggregate Order + internal aggregate Shipment + + call charge (order : String) (amount : Nat) : Charge + call ship (order item : String) : Unit + + policy Payment on Order + | id, .placed _ amount => do + match ← charge id amount with + | .approved chargeId => Order.send (.settle id chargeId) + | .refused reason => Order.send (.decline id reason) + + policy Fulfilment on Order + | id, .paid _ item _ => Shipment.send (.schedule id item) + + policy Dispatch on Shipment + | id, .scheduled item => ship id item + + view Revenue on Order : Nat := 0 + | total, .paid _ _ amount => total + amount + + projection Packing on Shipment : String × String + | id, .scheduled item => [(id, item)] +``` + +**Reading it.** An `internal aggregate` takes commands only from the model's own policies, never from a caller. A `call` names something outside the model and what it answers, not how. A `policy` is "whenever this event is recorded, do that". `do` starts a sequence of steps, and `←` runs a step and takes its result, like `await`. A `view` is a value kept up to date from events; a `projection` writes rows. + +**What you get.** The invariant of step 3 holds across the whole model, and of the model as a function hosts it, in one line each: any callers, any gateway answer, any delivery order, any event delivered twice. + +```lean +theorem everyOrderChargedOnce (w : Alchemy.World Signature) (reach : Shop.Reachable w) + (id : String) : ChargedOnce (w.state .Order id) := + Order.always (by simp [ChargedOnce]) chargedOnce w reach id + +theorem deployedOrdersChargedOnce (journal : List Journal.Line) (id : String) : + ChargedOnce ((served.replay journal).state .Order id) := + Order.deployed (by simp [ChargedOnce]) chargedOnce journal id +``` + +## 6. Say what its history must look like + +Some rules are about the order of what happened, not one state. + +```lean +theorem paymentNeedsAPlacedOrder : + Order.Precedes Order.isPlaced Order.isPaid (fun s => s.status ≠ .new) := by + history_rule + +theorem nothingShipsUnlessPaid (w : Alchemy.World Signature) (reach : Shop.Reachable w) : + Model.Backed isShipment paidFor w.log := by + caused_by reach +``` + +**Reading it.** The first is about one order: a payment is only recorded on an order that shows it was placed. `history_rule` checks each command. The second crosses aggregates: every shipment recorded has a payment recorded for the same order. It is true because `Shipment` is `internal`, so only a policy schedules one, and `caused_by` walks every policy to check which. + +**What you get.** Both hold in every world the shop can reach. `Order.tallied` does the same for quantities: what an order was charged is the sum of the payments it recorded. + +## 7. Prove a whole flow + +A script of what happens, and a claim about where things end up. + +```lean +theorem anApprovedOrderIsPaidAndShipped (id item charge : String) (amount : Nat) + (priced : amount ≠ 0) : + let shop := Shop.run [ + .send ⟨.Order, (), .place id item amount⟩, + .answer (.charge id amount) (.approved charge)] + (shop.state .Order id).status = .paid charge ∧ + (shop.state .Shipment id).item = some item ∧ + Shop.waiting shop = [.ship id item] := by + behaviour +``` + +**Reading it.** `.send` is a caller sending a command. `.answer` is the theorem saying "suppose the gateway replies this". `let shop := …` names the world after the script. `(priced : amount ≠ 0)` is an assumption the proof may use. `behaviour` runs the script with `id` and `amount` left as unknowns. + +One line proves that the whole model stops, from any world it can reach. It finds the measure itself. + +```lean +comes_to_rest Shop +``` + +**Reading it.** The command gives every event, command and saga a weight so that each step lowers the total, then states `Shop.comesToRest`. If some reaction feeds itself, no weights exist and the line fails. + +## 8. Show one concrete case: a story + +The same thing with real values, so a person can read it and check it is what they meant. + +```lean +def aKettle : List (Story.ModelStep Shop) := [ + .when ⟨.Order, (), .place "o-1" "kettle" 40⟩, + .call (.charge "o-1" 40), + .answer (.charge "o-1" 40) (.approved "ch_o-1"), + .recorded .Order "o-1" [.placed "kettle" 40, .paid "ch_o-1" "kettle" 40], + .recorded .Shipment "o-1" [.scheduled "kettle"], + .call (.ship "o-1" "kettle"), + .answer (.ship "o-1" "kettle") (), + .view Revenue () 40, + .when ⟨.Order, (), .place "o-1" "kettle" 40⟩, + .rejected .Order .alreadyPlaced ] + +example : Shop.passes aKettle = true := by decide +``` + +**Reading it.** `def` names the story so it can be told again later. `example` is a theorem with no name. `by decide` proves it by running it, which works because nothing is unknown. A theorem says it always holds; a story shows what "it" is. + +## 9. Keep it anywhere + +The model does not say where an order's state is kept. A host gives it services, and the same engine runs on any of them. + +```lean +def inMemory : Shop.Stored (StateM (Held Signature reads)) where + services := InMemory.services _ _ fun + | .charge order amount => sandboxCharge order amount + | .ship _ _ => () +``` + +**Reading it.** `Shop.Stored μ` is the shop's engine on services that run in `μ`. `InMemory.services` is one set: every store is a value in memory, and the function says what the gateway and the warehouse answer. The engine loads one order, decides, and commits the state the events leave. + +**What you get.** One theorem for every set of services that keep their laws: the stored orders satisfy the rule of step 3. + +```lean +theorem storedOrdersChargedOnce (shop : Shop.Stored μ) (lawful : shop.services.Lawful acts held sound) + {fresh now : S} (ok : sound fresh) (empty : held fresh = Held.start _ _) + (ran : shop.Runs acts fresh now) (id : String) : + ChargedOnce ((held now).state .Order id) := +``` + +## 10. Put it on infrastructure + +A stack declares resources. A function calls what it needs, and its permissions are worked out from those calls. + +```lean +effect def theShop {role : Access Kind} (orders : Bucket) (shipments : Queue) : Hosted served role := + served.host (S3.journal orders) fun + | .charge order amount => pure (sandboxCharge order amount) + | .ship order item => SQS.sendMessage shipments s!"{order}:{item}" + +def Api (orders : Bucket) (shipments : Queue) : Construct Kind Function := do + let stage ← stage + Lambda.Function "Api" { url := true, memory := if stage = "prod" then 1024 else 512 } do + return route (theShop orders shipments) + +def Warehouse (orders : Bucket) (shipments : Queue) : Construct Kind Function := + Lambda.Function "Warehouse" {} do + SQS.consume shipments fun shipment => do + match shipment.splitOn ":" with + | [order, item] => S3.putObject orders ["packed"] order item + | _ => pure () + + return fun _ => return { status := 204 } + +def ShopStack : Stack Kind Outputs where + name := "Shop" + body := do + let orders ← S3.Bucket "Orders" + let shipments ← SQS.Queue "Shipments" + let api ← Api orders shipments + let warehouse ← Warehouse orders shipments + return { orders, shipments, api, warehouse } +``` + +**Reading it.** `def name (inputs) : Type := body` defines a function, and `fun x => …` is an anonymous one. `effect def` defines a function whose permissions are read off its body, so nobody lists them. `theShop` hosts the model: its history is a journal in the bucket, and it says who answers `charge` and `ship`. `SQS.consume` registers the function as the queue's consumer. + +## 11. Prove who can touch what + +Take the bucket in this stack. It holds two things with very different stakes. + +Under `journal/` is the shop's history: every order and every payment. It is the system of record. Everything proved in steps 3 to 6 assumes one thing about it: only the function that hosts the model appends to it. If anything else can write there, an order can be recorded as paid that nobody charged, and every domain proof is about a history that is no longer the real one. + +Under `packed/` are packing slips, written by a warehouse function that has no business seeing what customers ordered or paid. + +So there are two rules this infrastructure must keep, and today they are usually kept by someone reading IAM policy diffs in review: + +1. **One writer for the system of record.** Only the Api writes under `journal/`. +2. **The warehouse cannot read customer data.** It writes slips and reads nothing. + +Here they are theorems about the stack. + +```lean +/-- Only the Api writes the shop's history. -/ +theorem onlyTheApiWritesHistory : + prod.only [out.api] (S3.writing out.orders ["journal"]) := by + stack_rule in prod + +/-- The Warehouse reads nothing in the bucket: no order, and none of the history. -/ +theorem theWarehouseReadsNothing : + prod.never out.warehouse (S3.reading out.orders) := by + stack_rule in prod +``` + +**Reading it.** `prod` is the stack at the "prod" stage and `out` is what it built. `S3.writing out.orders ["journal"]` means writing any object under `journal/`, so each rule covers every key, not a sample. `stack_rule` computes each function's role from the stack and checks the rule against it. + +**What you get.** The rules hold as the code changes. Suppose someone, months later, makes the Warehouse read the order count from the journal to number its slips: + +```diff + SQS.consume shipments fun shipment => do + match shipment.splitOn ":" with +- | [order, item] => S3.putObject orders ["packed"] order item ++ | [order, item] => do ++ let _ ← S3.getObject orders ["journal"] "count" ++ S3.putObject orders ["packed"] order item +``` + +The call asks for a grant, the Warehouse's role gains "read Orders/journal", and the build stops at `theWarehouseReadsNothing`, showing the role that broke it: + +``` +Shop.lean:538: error: This rule does not hold of the stack. Some role allows what the rule +forbids, or lacks what it requires. The roles, as the code gives them: + … + ("Warehouse", + ((Access.on { id := "Orders" } (BucketOp.get ["journal"])).and + (Access.on { id := "Orders" } (BucketOp.put ["packed"]))).and + (Access.on { id := "Shipments" } QueueOp.receive))] +`graph --why` prints the call behind each permission. +``` + +Nobody reviewed a policy. The change looked harmless and would have deployed; the build refused it because the rule about customer data was written down once. The first rule is what connects the two halves of this guide: it is the stack-side fact that the domain proofs rely on. + +The opposite mistake, a permission left behind after the code that needed it is deleted, needs no rule at all. A role holds only what a call in the code asks for, so deleting the call removes the permission. + +`--why` shows the line behind each permission, which is what you would otherwise reconstruct by hand in a review: + +``` +$ lake exe shop graph prod --why + + Warehouse + may write Orders/packed + ← Shop.lean:325 S3.putObject orders ["packed"] order item + may receive from Shipments + ← Shop.lean:323 SQS.consume shipments fun shipment => do match shipment.s… +``` + +The domain's story also runs against the stack. It is step 8 again, but each command goes in through the Api, and the gateway and the queue answer the model's calls. This is what shows the wiring does what the model says. + +```lean +example : prod.tells deployed aKettle = true := by native_decide +``` + +## 12. Run it + +```sh +curl https://elan.lean-lang.org/elan-init.sh -sSf | sh && source ~/.elan/env +cd packages/alchemy-lean +lake build # checks every theorem and story +lake exe shop graph prod --why # resources, permissions, and the line behind each +lake exe shop plan prod after dev # what a deploy would change +``` + +``` + Warehouse + needs Orders, Shipments + may write Orders/packed + ← Shop.lean:325 S3.putObject orders ["packed"] order item + may receive from Shipments + ← Shop.lean:323 SQS.consume shipments fun shipment => do match shipment.s… + consumes Shipments + + no-op Orders + no-op Shipments + ~ update Api + memory: 512 → 1024 + no-op Warehouse +``` + +## The pattern + +Each layer has the same three moves. + +| | Define | Prove always | Show once | +|---|---|---|---| +| Aggregate | `aggregate` | invariant, behaviour | story | +| Model | `model` | flow theorem | story | +| Stack | `Stack`, functions | who can touch what | story told to the stack | + +Write the definition, write a story to see it do the right thing, then turn what must always hold into a theorem. A first exercise: change `amount = 0` to `amount < 5` in `decide`, run `lake build`, and see which theorems and stories depended on that line. diff --git a/packages/alchemy-lean/README.md b/packages/alchemy-lean/README.md new file mode 100644 index 00000000000..8ee59744068 --- /dev/null +++ b/packages/alchemy-lean/README.md @@ -0,0 +1,753 @@ +# alchemy-lean + +Alchemy in [Lean 4](https://lean-lang.org): a domain model, the stack that hosts it, and proofs about both. A prototype. + +```sh +curl https://elan.lean-lang.org/elan-init.sh -sSf | sh +lake build # proves every theorem and runs every story +``` + +New to Lean? Start with [GUIDE.md](./GUIDE.md), which builds one program step by step and explains how to read each piece. This page shows every feature, one snippet each. + +Every snippet below is from `examples/` and compiles. + +## An aggregate + +A block with its commands, events, rejections and state, and three functions. Each command says what it may record and how it may be refused, and that is checked against `decide`. `decide` answers a command with events or a rejection, and `evolve` applies one event. + +```lean +aggregate Order where + command + | place (id item : String) (amount : Nat) + records placed + rejects alreadyPlaced, nothingToCharge + | settle (id charge : String) + records paid + rejects notAwaitingPayment + | decline (id reason : String) + records declined + rejects notAwaitingPayment + + event + | placed (item : String) (amount : Nat) + | paid (charge item : String) (amount : Nat) + | declined (reason : String) + + rejection + | alreadyPlaced + | nothingToCharge + | notAwaitingPayment + + state + status : Status := .new + item : String := "" + amount : Nat := 0 + charged : Nat := 0 + + decide + | s, .place _ item amount => + if s.status ≠ .new then .error .alreadyPlaced + else if amount = 0 then .error .nothingToCharge + else .ok [.placed item amount] + | s, .settle _ charge => + if s.status = .awaitingPayment then .ok [.paid charge s.item s.amount] + else .error .notAwaitingPayment + | s, .decline _ reason => + if s.status = .awaitingPayment then .ok [.declined reason] + else .error .notAwaitingPayment + + evolve + | s, .placed item amount => { s with status := .awaitingPayment, item, amount } + | s, .paid charge _ amount => { s with status := .paid charge, charged := s.charged + amount } + | s, .declined reason => { s with status := .declined reason } +``` + +`reply` is what an accepted command answers its caller. It is given the state after the command's events are applied, and its type is the command's response type. + +```lean + reply : Status + | s, _ => s.status +``` + +The block writes plain definitions, `Order.decide`, `Order.evolve`, `Order.reply`, which is what theorems name. + +## A model + +One block declares the aggregates and the systems outside the model. A model has as many aggregates as it needs, and a policy on one can send to another (`examples/Shop.lean` has `Order` and `Shipment`). + +```lean +model Bank where + aggregate Account + + call screen (account : String) (amount : Nat) : Screening + call wire (payout account : String) (amount : Nat) : WireResult +``` + +A policy reacts to an event. It may call outside and send commands. + +```lean + policy Compliance on Account + | id, .deposited amount => do + if amount ≥ 10000 then + match ← screen id amount with + | .flagged reason => Account.send (.freeze id reason) + | .clear => pure () +``` + +A decision reads several instances and records on all of them or none. + +```lean + decision Transfer (TransferRequest) : TransferRefused + | accounts, ⟨source, destination, amount⟩ => + … + else if (Account.of accounts source).balance < amount then + .error (.insufficientFunds (Account.of accounts source).balance amount) + else .ok [ + Account.record source (.transferredOut amount), + Account.record destination (.transferredIn amount)] +``` + +A saga runs steps in order. `undoWith` says what to send if a later step fails. A model can have several, each with its own failures. + +```lean + saga Payout (PayoutRequest) (Unit) : PayoutFailed + | payout, ⟨account, amount⟩ => do + Account.must (.withdraw account amount) fun _ => .refused + Account.undoWith (.deposit account amount) + match ← wire payout account amount with + | .sent => pure () + | .bounced => failWith .bounced +``` + +A view folds a value over events. A projection writes rows for them. + +```lean + view Holdings on Account : Int := 0 + | total, .deposited amount => total + amount + | total, .withdrawn amount => total - amount + + projection Statement on Account : String × String × Nat + | id, .deposited amount => [(id, "deposit", amount)] + | id, .withdrawn amount => [(id, "withdrawal", amount)] +``` + +A view can keep a value for each instance. + +```lean + view Balances on Account by id : Int := 0 + | balance, .deposited amount => balance + amount + | balance, .withdrawn amount => balance - amount + | balance, .transferredIn amount => balance + amount + | balance, .transferredOut amount => balance - amount +``` + +A stream is an ordered log per instance, and a query answers from everything recorded. + +```lean + stream Activity on Account : String + | _, .deposited amount => [s!"+{amount}"] + | _, .withdrawn amount => [s!"-{amount}"] + | _, .frozen reason => [s!"frozen: {reason}"] + + query Frozen (Unit) : String + | log, _ => (log.filterMap fun + | ⟨.Account, id, .frozen _, _, _⟩ => some id + | _ => none).eraseDups +``` + +An aggregate can say who sends its commands. `decide` is then given the actor first. + +```lean +aggregate Watch where + actor : Who + + decide + | _, _, .assess _ amount => + if amount = 0 then .error .nothingToAssess + else if amount ≥ 50000 then .ok [.flagged amount] + else .ok [.cleared amount] + | .officer name, s, .dismiss _ => + if s.flagged = 0 then .error .nothingFlagged else .ok [.dismissed name] + | .system, _, .dismiss _ => .error .notAnOfficer +``` + +## Behaviour + +Given events, when a command, then a result. It holds for every id and amount. + +```lean +theorem anOverdraftIsRefused (id owner : String) (held amount : Nat) (tooMuch : held < amount) : + Account.decide (Account.after [.opened owner, .deposited held]) (.withdraw id amount) + = .error (.insufficientFunds held amount) +``` + +## Invariants + +A fact about the state. `aggregate_rule` proves no accepted command breaks it. + +```lean +def Balanced (s : Account.State) : Prop := s.balance + s.withdrawn = s.deposited + +theorem balanced_kept : Account.Keeps Balanced := by + aggregate_rule +``` + +Other facts follow from an invariant by arithmetic, for every history. + +```lean +theorem neverPaysOutMoreThanCameIn (commands : List Account.Sent) : + (Account.replay {} commands).withdrawn ≤ (Account.replay {} commands).deposited := by + have := balanced.always commands + simp only [balanced, Balanced] at this + omega +``` + +`Account.always` lifts it to every world the model can reach: any callers, any outside answers, any delivery order. + +```lean +theorem everyAccountBalanced (w : Alchemy.World Signature) (reach : Bank.Reachable w) + (id : String) : Balanced (w.state .Account id) := + Account.always (by simp [Balanced]) balanced_kept w reach id transfer_balanced +``` + +`Account.deployed` does the same for the model as a function hosts it, whatever its journal holds. + +```lean +theorem deployedAccountsBalanced (journal : List Journal.Line) (id : String) : + Balanced ((served.replay journal).state .Account id) := + Account.deployed (by simp [Balanced]) balanced_kept journal id transfer_balanced +``` + +A rule across aggregates is stated over the whole record. + +```lean +def Conserved (r : Recorded Aggregates) : Prop := + ((r.eventsOf .Account).map movedOut).sum = ((r.eventsOf .Account).map movedIn).sum + +theorem noTransferCreatesMoney (w : Alchemy.World Signature) (reach : Bank.Reachable w) : + Conserved w.toRecorded +``` + +Views and projections come with their theorems. + +```lean +#check (Holdings.exact : ∀ log, Holdings.stateAt log () = log.foldl Holdings.step 0) +#check (Statement.exact : ∀ log, Statement.table log = log.flatMap Statement.rows) +``` + +## Scenarios + +A scenario is a list of moves: commands sent, and outside calls answered. + +```lean +def aPayoutBounces (id owner payout : String) (held amount : Nat) : List (Model.Move Bank) := [ + .send ⟨.Account, (), .open id owner⟩, + .send ⟨.Account, (), .deposit id held⟩, + .send ⟨.Account, (), .requestPayout id payout amount⟩, + .answer (.wire payout id amount) .bounced] +``` + +A theorem proves its outcome for every input. `behaviour` runs the model with the variables left as they are. + +```lean +theorem aBouncedPayoutIsRefunded (id owner payout : String) (held amount : Nat) + (some : amount ≠ 0) (enough : amount ≤ held) (modest : held < 10000) : + let bank := Bank.run (aPayoutBounces id owner payout held amount) + (bank.state .Account id).balance = held ∧ bank.sagas (.Payout, payout) = .failed (.Payout .bounced) := by + … + behaviour [aPayoutBounces] +``` + +A story follows the same scenario with real values and checks each step. `.next` makes the next move. + +```lean +example : Bank.follows (aPayoutBounces "a-1" "Sam" "p-1" 500 200) [ + .next 3, + .call (.wire "p-1" "a-1" 200), + .state .Account "a-1" + { status := .open, owner := "Sam", balance := 300, deposited := 500, withdrawn := 200 }, + .next, + .saga (.Payout, "p-1") (.failed (.Payout .bounced)), + .recorded .Account "a-1" [.opened "Sam", .deposited 500, .payoutRequested "p-1" 200, + .withdrawn 200, .deposited 200] + ] = true := by decide +``` + +## Two models + +A `Link` says which of one model's calls another model answers. + +```lean +def screening : Link Bank Compliance where + ask + | .screen account amount => some ⟨.Watch, .system, .assess account amount⟩ + | .wire .. => none + reply + | .screen .., ⟨.Watch, _, _⟩, .ok [.flagged _] => .flagged "over the reporting threshold" + | .screen .., _, _ => .clear + | .wire .., _, _ => .bounced +``` + +What was proved of each model holds of both, with nothing proved again. + +```lean +theorem bothAreSound (w : screening.Worlds) (reach : screening.Reachable w) (account : String) : + Bank.Balanced (w.1.state .Account account) ∧ + Bank.Conserved w.1.toRecorded ∧ + Compliance.FlagsAreAssessments (w.2.state .Watch account) := + ⟨Bank.everyAccountBalanced _ (screening.reachable_left reach) account, + Bank.noTransferCreatesMoney _ (screening.reachable_left reach), + Compliance.everyWatchIsSound _ (screening.reachable_right reach) account⟩ +``` + +`behaviour` proves a flow across the two. + +```lean +theorem aReportableDepositFreezesTheAccount (id owner : String) (amount : Nat) + (reportable : amount ≥ 50000) : + let both := screening.run [ + .send ⟨.Account, (), .open id owner⟩, + .send ⟨.Account, (), .deposit id amount⟩] + (both.1.state .Account id).status = .frozen "over the reporting threshold" ∧ + both.2.state .Watch id = { assessed := 1, flagged := 1 } +``` + +Any number of models join in a `Network`. The same holds of all of them, and a run goes through each. + +```lean +theorem allThreeAreSound (w : institution.Worlds) (reach : institution.Reachable w) + (account : String) (payout : WireId) : + Bank.Balanced ((w .bank).state .Account account) ∧ + Bank.Conserved (w .bank).toRecorded ∧ + Compliance.FlagsAreAssessments ((w .compliance).state .Watch account) ∧ + Wires.SentOnce ((w .wires).state .Transfer payout) := +``` + +## Eventually + +Left to run, a flow comes to rest with nothing in flight and the outcome it should have. + +```lean +theorem anApprovedOrderEventuallyShips (id item charge : String) (amount : Nat) + (priced : amount ≠ 0) : + Shop.Eventually + (Shop.run [ + .send ⟨.Order, (), .place id item amount⟩, + .answer (.charge id amount) (.approved charge), + .answer (.ship id item) ()]) + fun shop => shop.Settled ∧ (shop.state .Order id).status = .paid charge ∧ + (shop.state .Shipment id).item = some item := by + refine Shop.eventually_now _ ?_ ?_ <;> behaviour +``` + +`comes_to_rest` proves that a model stops from any world it can reach. It finds a weight for each event, command and saga so that every step lowers the total; nobody writes the weights. + +```lean +comes_to_rest Shop + +theorem theShopComesToRest (w : Alchemy.World Signature) (reach : Shop.Reachable w) : + ∃ steps, Shop.AtRest (Shop.settle steps w) := + Shop.comesToRest w reach +``` + +When every reaction only calls outside, tells an aggregate and ends, the number of steps comes with it. + +```lean +theorem theShopComesToRestIn (w : Alchemy.World Signature) (reach : Shop.Reachable w) : + Shop.AtRest (Shop.settle ((ranking.weights reacts).measure w) w) := + Shop.comesToRestIn w reach +``` + +A model whose reaction feeds itself is refused, with the event that keeps growing. + +```lean +model Loop where + aggregate Counter + + -- whenever the counter is bumped, bump it again + policy Again on Counter + | id, .bumped => Counter.send (.bump id) + +/-- +error: Loop may never come to rest: no weights hold together, because some reaction leads back to the event it reacts to. These kept growing: [Counter.Event.bumped] +-/ +#guard_msgs in +comes_to_rest Loop +``` + +The same line covers sagas and their undos. The weights it found can be read. + +```lean +comes_to_rest Bank + +example : ranking.event .Account (.payoutRequested "p-1" 200) = 21 := rfl +``` + +## History + +Some rules tie a state to the events its instance recorded. Each is proved of the aggregate, one command at a time, and holds of every instance in every world the model can reach. + +A quantity that is the sum of what was recorded: + +```lean +def Order.worth : Order.Event → Int + | .paid _ _ amount => amount + | _ => 0 + +theorem chargesAreTallied : Order.Tallies (fun s => s.charged) Order.worth := by + history_rule + +theorem chargedIsWhatWasPaid (w : Alchemy.World Signature) (reach : Shop.Reachable w) (id : String) : + ((w.state .Order id).charged : Int) + = ((w.toRecorded.eventsAt .Order id).map Order.worth).sum := by + simpa using Order.tallied chargesAreTallied w reach id +``` + +An event that is only recorded after another, on the same instance: + +```lean +theorem paymentNeedsAPlacedOrder : + Order.Precedes Order.isPlaced Order.isPaid (fun s => s.status ≠ .new) := by + history_rule + +theorem noOrderIsPaidBeforeItIsPlaced (w : Alchemy.World Signature) (reach : Shop.Reachable w) + (id : String) : + Aggregate.Follows Order.isPlaced Order.isPaid (w.toRecorded.eventsAt .Order id) := + Order.follows paymentNeedsAPlacedOrder w reach id +``` + +`Aggregate.Commutes.replay_perm` says that when commands commute, any order of delivery leaves the same state, and `Aggregate.Idempotent.replay_again` that a command delivered twice leaves what it leaves once. + +## Across aggregates + +An `internal aggregate` takes no commands from callers: only the model's policies and sagas reach it. + +```lean +model Shop where + aggregate Order + internal aggregate Shipment +``` + +That makes "nothing ships unless it was paid" true, and `caused_by` proves it by walking every policy's reaction to every event. + +```lean +def isShipment : Emitted Aggregates → Prop + | ⟨.Shipment, _, _, _, _⟩ => True + | _ => False + +def paidFor : Emitted Aggregates → Emitted Aggregates → Prop + | ⟨.Shipment, id, _, _, _⟩, ⟨.Order, id', .paid .., _, _⟩ => id = id' + | _, _ => False + +theorem nothingShipsUnlessPaid (w : Alchemy.World Signature) (reach : Shop.Reachable w) : + Model.Backed isShipment paidFor w.log := by + caused_by reach +``` + +## Kept in stores + +A model says nothing about where its state is kept. `Shop.Services` is what it asks of a host: a store for its aggregates, delivery of what they record, its calls, the clock. The engine is written once against them. It loads an instance, decides, and commits the state the events leave; it replays nothing. + +```lean +def inMemory : Shop.Stored (StateM (Held Signature reads)) where + services := InMemory.services _ _ fun + | .charge order amount => sandboxCharge order amount + | .ship _ _ => () +``` + +Each service has a law. For any services that keep theirs, whatever the host is sent, what is stored stands for a world the model can reach. So a rule proved of the model holds of the stored state, wherever that is. + +```lean +theorem storedOrdersChargedOnce (shop : Shop.Stored μ) (lawful : shop.services.Lawful acts held sound) + {fresh now : S} (ok : sound fresh) (empty : held fresh = Held.start _ _) + (ran : shop.Runs acts fresh now) (id : String) : + ChargedOnce ((held now).state .Order id) := +``` + +Views are stored as their state, changed once per delivered event, and are still exactly the view of everything recorded. + +```lean +theorem storedRevenueIsExact (shop : Shop.Stored μ) (lawful : shop.services.Lawful acts held sound) + {fresh now : S} (ok : sound fresh) (empty : held fresh = Held.start _ _) + (ran : shop.Runs acts fresh now) (delivered : (held now).pending = []) : + ∃ w, Shop.Reachable w ∧ Revenue.held (held now).read () = Revenue.stateAt w.log () := by +``` + +## Services and Layers + +Code is written against a service, and a Layer says how the service is built. A Layer can ask for what it is built from, so two services share one dependency, provided once where the application is wired. + +```lean +def JobIndexOnS3 (bucket : Bucket) [Uses In (S3.GetObject.Client bucket ["jobs"])] : + Layer In JobIndex := + .make do + let objects ← S3.GetObject bucket ["jobs"] + return { has := fun id => do + match ← (objects.call id).result with + | .ok _ => return true + | .error (_ : S3.GetObjectError) => return false } + +def JobServices (bucket : Bucket) : Layer Nothing (Both JobStorage JobIndex) := + (JobStorageOnS3 bucket ++ JobIndexOnS3 bucket).provide + (S3.GetObjectLive bucket ["jobs"] ++ S3.PutObjectLive bucket ["jobs"]) +``` + +## A stack + +Resources and functions are steps of the stack's block. + +```lean +def ShopStack : Stack Kind Outputs where + name := "Shop" + body := do + let orders ← S3.Bucket "Orders" + let shipments ← SQS.Queue "Shipments" + let api ← Api orders shipments + let warehouse ← Warehouse orders shipments + return { orders, shipments, api, warehouse } +``` + +A function calls the operations it needs. Its role is read off those calls; nobody writes it. + +```lean +def Warehouse (orders : Bucket) (shipments : Queue) : Construct Kind Function := + Lambda.Function "Warehouse" {} do + SQS.consume shipments fun shipment => do + match shipment.splitOn ":" with + | [order, item] => S3.putObject orders ["packed"] order item + | _ => pure () + + return fun _ => return { status := 204 } +``` + +`served.host` runs a domain model on a journal, and says who answers each call the model makes to the outside. + +```lean +effect def theShop {role : Access Kind} (orders : Bucket) (shipments : Queue) : Hosted served role := + served.host (S3.journal orders) fun + | .charge order amount => pure (sandboxCharge order amount) + | .ship order item => SQS.sendMessage shipments s!"{order}:{item}" + +def Api (orders : Bucket) (shipments : Queue) : Construct Kind Function := do + let stage ← stage + Lambda.Function "Api" { url := true, memory := if stage = "prod" then 1024 else 512 } do + return route (theShop orders shipments) +``` + +A Cloudflare Worker is the same, and ends with `fetch` and typed methods other Workers call. + +```lean +def Inbox (mail : Bucket) (incoming : Queue) : Construct Kind (Worker Api) := + Workers.Worker "Inbox" {} Api do + Queues.consume incoming fun message => store mail message + + return { + fetch := fun request => do + match request.method, request.path with + | "POST", "/messages" => + Queues.send incoming request.body + return { status := 202 } + | _, _ => return { status := 404 } + rpc := fun + | .count => return (← R2.list mail).length + | .read id => R2.get mail (toString id) } +``` + +## Access + +Who can do what, for every key under a prefix. `stack_rule` computes each role from the stack. + +```lean +theorem onlyTheApiWritesHistory : + prod.only [out.api] (S3.writing out.orders ["journal"]) := by + stack_rule in prod + +theorem theWarehouseReadsNothing : + prod.never out.warehouse (S3.reading out.orders) := by + stack_rule in prod + +theorem nobodyListsTheOrders : prod.nobody (S3.listing out.orders) := by + stack_rule in prod + +theorem shipmentsGoOneWay : + prod.only [out.api] (SQS.sending out.shipments) ∧ + prod.only [out.warehouse] (SQS.receiving out.shipments) := by + constructor <;> stack_rule in prod +``` + +## A story, told to the stack + +The same story as the domain's, word for word. Each command goes in through the Api, the bindings answer the model's calls, and what is recorded is read back from the bucket. + +```lean +def deployed : Telling Shop InMemory where + kind := .function + host := out.api + request + | ⟨.Order, _, command⟩ => (post out.api "/orders" command).request + world := shopIn out.orders + +example : prod.tells deployed aKettle = true := by native_decide +``` + +## Testing a stack + +Requests and what they must answer, run against the whole stack in memory. These are tests of the wiring, in HTTP and buckets; stories stay in the domain's language. + +```lean +def postingAnOrder : List (Graph.Step Kind InMemory) := [ + post out.api "/orders" (Order.Command.place "o-1" "kettle" 40) ⇒ (200, "paid ch_o-1"), + .holds "the warehouse filed a slip" (·.object out.orders ["packed", "o-1"] == some "kettle"), + .holds "and took the shipment off the queue" (·.queued out.shipments == []), + get out.api "/orders/o-1" ⇒ (200, "paid ch_o-1"), + post out.api "/orders" (Order.Command.place "o-1" "kettle" 40) + ⇒ (409, "Order.Rejection.alreadyPlaced"), + get out.api "/revenue" ⇒ (200, "40") ] + +example : prod.passes postingAnOrder = true := by native_decide +``` + +## Least privilege + +A role holds only what a call in the function's code asks for, so there is nothing to state: delete the call and the permission goes with it. + +`lake exe shop graph prod --why` prints the call behind each grant. + +``` + Api + may read Orders/journal + ← Shop.lean:280 theShop _ orders shipments + may send to Shipments + ← Shop.lean:280 theShop _ orders shipments + Warehouse + may write Orders/packed + ← Shop.lean:279 S3.putObject orders ["packed"] order item + may receive from Shipments + ← Shop.lean:277 SQS.consume shipments fun shipment => do match shipment.s… +``` + +A test gives the stronger claim: each grant is not only written but used in a run. + +```lean +theorem leastPrivilege : prod.LeastPrivilege InMemory := + .of_tests [postingAnOrder] (by native_decide) +``` + +## Behaviour of a function + +Given what the bucket holds, when a request arrives, then the response and the bucket afterwards. + +```lean +theorem gettingAnOrder (id : String) (cloud : Memory) : + (getOrder (theShop (role := role) orders shipments) id).eval InMemory cloud + = (.ok (describe ((shopIn orders cloud).state .Order id).status), cloud) +``` + +A response follows from the domain's `decide`, for every item and amount. + +```lean +theorem placingAnOrderTwiceIsRefused (id item : String) (amount : Nat) (cloud : Memory) + (whole : Whole orders cloud) + (placed : ((shopIn orders cloud).state .Order id).status ≠ .new) : + ((postOrder (theShop (role := role) orders shipments) (.place id item amount)).eval InMemory cloud).1 + = .ok { status := 409, body := reprStr Order.Rejection.alreadyPlaced } +``` + +These rest on a law per binding: what a call answers and what it does to the cloud. + +```lean +structure PutObject.Lawful {bucket : AWS.Bucket} {under : Path} + (client : PutObject.Client bucket under access) : Prop where + put : ∀ (m : Memory) (name body : String), + (client.call name body).eval InMemory m = (.ok (), m.put bucket (under ++ [name]) body) +``` + +## Run it + +A stack is a value, so its graph is computed from the code. `lake exe shop graph prod` prints it. + +``` +Shop (prod) + + Orders + Shipments + Api + needs Orders, Shipments + may read Orders/journal + may write Orders/journal + may read Orders/journal/lines + may write Orders/journal/lines + may send to Shipments + Warehouse + needs Orders, Shipments + may write Orders/packed + may receive from Shipments + consumes Shipments +``` + +`lake exe shop plan prod` prints the plan for a fresh account. + +``` + + create Orders + + create Shipments + + create Api + + create Warehouse + + 4 to create, 0 to update, 0 to replace, 0 to delete, 0 unchanged +``` + +`lake exe shop plan prod after dev` plans against an account the dev stage was deployed to. + +``` + no-op Orders + no-op Shipments + ~ update Api + memory: 512 → 1024 + no-op Warehouse + + 0 to create, 1 to update, 0 to replace, 0 to delete, 3 unchanged +``` + +The program is one line. + +```lean +def main (args : List String) : IO UInt32 := Alchemy.AWS.cli Shop.ShopStack args +``` + +The same plan is a value a theorem can state. + +```lean +example : plan Control.providers prod fresh.state = [ + ("Orders", .create), ("Shipments", .create), ("Api", .create), ("Warehouse", .create)] := by + native_decide +``` + +In the editor, `#eval` shows any of it without running a program. + +```lean +-- #eval prod.order gives ["Orders", "Shipments", "Api", "Warehouse"] +-- #eval prod.edges gives [("Api", "Orders"), ("Api", "Shipments"), …] +``` + +`python3 check-docs.py` checks that every line of Lean on this page and in the guide is in the library or an example. + +## Examples + +| File | Shows | +|---|---| +| `examples/Wallet.lean` | One aggregate, one invariant, one story | +| `examples/Accounts.lean` | The bank above | +| `examples/Linked.lean` | The bank linked to a compliance model | +| `examples/Shop.lean` | A model on an AWS stack | +| `examples/Uploads.lean` | Proving an infrastructure design: uploads that cannot be served before they are scanned | +| `examples/Inbox.lean` | Cloudflare Workers | +| `examples/Jobs.lean` | Services, Layers and typed errors | +| `examples/Bank/` | A larger bank in the long form: keyed views, streams, queries, actors | + +## Limits + +- Stacks run against a cloud held in memory. Nothing deploys to a real account. +- A host handles one request at a time, by design. +- The engine on stores has services held in memory only. Stores on S3, DynamoDB or a Durable Object are not written, and the stack still hosts the shop through its journal. +- The engine on stores runs commands, policies, sagas, views and tables. Decisions, streams and queries are only in the model's own engine. +- What is part-way through (a saga waiting, a call not yet answered) is kept as a value, which a real store cannot hold: it needs a journal per saga. diff --git a/packages/alchemy-lean/check-docs.py b/packages/alchemy-lean/check-docs.py new file mode 100644 index 00000000000..db8885e8fec --- /dev/null +++ b/packages/alchemy-lean/check-docs.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Checks that every line of Lean shown in the README and the guide is a line of +the library or an example, so the documents cannot drift from code that compiles. +A line holding `…` marks a cut and is skipped, and a line may stop short of +the one in the code, as a statement shown without its proof does. Run from this directory.""" +import pathlib, re, sys + +root = pathlib.Path(__file__).parent +source = set() +for path in list(root.glob("examples/**/*.lean")) + list(root.glob("Alchemy/**/*.lean")): + for line in path.read_text().splitlines(): + source.add(" ".join(line.split())) + +missing = [] +for doc in sys.argv[1:] or ["README.md", "GUIDE.md"]: + text = (root / doc).read_text() if not doc.startswith("/") else pathlib.Path(doc).read_text() + for block in re.findall(r"```lean\n(.*?)```", text, flags=re.S): + for line in block.splitlines(): + shown = " ".join(line.split()) + if not shown or "…" in shown or shown.startswith("--") or shown.startswith("#check"): + continue + if shown in source: + continue + # A statement shown without its proof: `theorem … :=` cut before `by`. + if any(have.startswith(shown) for have in source): + continue + missing.append((doc, line)) + +for doc, line in missing: + print(f"{doc}: not in the code: {line}") +sys.exit(1 if missing else 0) diff --git a/packages/alchemy-lean/examples/Accounts.lean b/packages/alchemy-lean/examples/Accounts.lean new file mode 100644 index 00000000000..717b23e26d0 --- /dev/null +++ b/packages/alchemy-lean/examples/Accounts.lean @@ -0,0 +1,670 @@ +import Alchemy + +/-! +# A bank + +How a verified domain model is built up, in six steps: + +1. the domain: what an account can be asked, what it records, why it refuses; +2. behaviour: given this history, when this command arrives, then this happens; +3. invariants: facts about an account's state that no command can break; +4. consequences: what follows from the invariants, for every history; +5. across accounts: a transfer, decided over two accounts at once, creates no money; +6. the model: the same facts in every world the bank can reach, and as deployed. +-/ + +open Alchemy Cloud + +/-! ## 1. The domain -/ + +inductive Account.Status where + | new + | open + | frozen (reason : String) + | closed +deriving DecidableEq, Repr + +aggregate Account where + command + | open (id owner : String) + records opened + rejects alreadyOpen + | deposit (id : String) (amount : Nat) + records deposited + rejects nothingToMove, frozen, notOpen + | withdraw (id : String) (amount : Nat) + records withdrawn + rejects nothingToMove, insufficientFunds, frozen, notOpen + | freeze (id reason : String) + records frozen + rejects notOpen + | close (id : String) + records closed + rejects notEmpty, notOpen + | requestPayout (id payout : String) (amount : Nat) + records payoutRequested + rejects notOpen + + event + | opened (owner : String) + | deposited (amount : Nat) + | withdrawn (amount : Nat) + | transferredOut (amount : Nat) + | transferredIn (amount : Nat) + | frozen (reason : String) + | closed + | payoutRequested (payout : String) (amount : Nat) + + rejection + | alreadyOpen + | notOpen + | nothingToMove + | insufficientFunds (balance requested : Nat) + | frozen (reason : String) + | notEmpty (balance : Nat) + + -- the balance, and separately everything that ever came in and went out + state + status : Status := .new + owner : String := "" + balance : Nat := 0 + deposited : Nat := 0 + withdrawn : Nat := 0 + + decide + | s, .open _ owner => + if s.status = .new then .ok [.opened owner] else .error .alreadyOpen + | s, .deposit _ amount => + if amount = 0 then .error .nothingToMove + else match s.status with + | .open => .ok [.deposited amount] + | .frozen reason => .error (.frozen reason) + | _ => .error .notOpen + | s, .withdraw _ amount => + if amount = 0 then .error .nothingToMove + else match s.status with + | .open => + if amount ≤ s.balance then .ok [.withdrawn amount] + else .error (.insufficientFunds s.balance amount) + | .frozen reason => .error (.frozen reason) + | _ => .error .notOpen + | s, .freeze _ reason => + if s.status = .open then .ok [.frozen reason] else .error .notOpen + | s, .close _ => + if s.status = .open then + if s.balance = 0 then .ok [.closed] else .error (.notEmpty s.balance) + else .error .notOpen + | s, .requestPayout _ payout amount => + if s.status = .open then .ok [.payoutRequested payout amount] else .error .notOpen + + evolve + | s, .opened owner => { s with status := .open, owner } + | s, .deposited amount => + { s with balance := s.balance + amount, deposited := s.deposited + amount } + | s, .withdrawn amount => + { s with balance := s.balance - amount, withdrawn := s.withdrawn + amount } + | s, .transferredOut amount => + { s with balance := s.balance - amount, withdrawn := s.withdrawn + amount } + | s, .transferredIn amount => + { s with balance := s.balance + amount, deposited := s.deposited + amount } + | s, .frozen reason => { s with status := .frozen reason } + | s, .closed => { s with status := .closed } + | s, .payoutRequested .. => s + + -- an accepted command answers the balance it left + reply : Nat + | s, _ => s.balance + +/-- What the compliance check answers about a deposit. -/ +inductive Screening where + | clear + | flagged (reason : String) +deriving DecidableEq, Repr + +derive_tokens Screening + +/-- Move money from one account to another. -/ +structure TransferRequest where + source : String + destination : String + amount : Nat +deriving DecidableEq, Repr + +derive_tokens TransferRequest + +inductive TransferRefused where + | sameAccount + | nothingToMove + | sourceNotOpen + | destinationNotOpen + | insufficientFunds (balance requested : Nat) +deriving DecidableEq, Repr + +/-- What a payout is started with. -/ +structure PayoutRequest where + account : String + amount : Nat +deriving DecidableEq, Repr + +/-- What the wire service answers. -/ +inductive WireResult where + | sent + | bounced +deriving DecidableEq, Repr + +derive_tokens WireResult + +inductive PayoutFailed where + | refused + | bounced +deriving DecidableEq, Repr + +inductive FarewellFailed where + | alreadyGone +deriving DecidableEq, Repr + +model Bank where + aggregate Account + + -- A transfer is decided across two accounts at once: both record it, or neither does. + decision Transfer (TransferRequest) : TransferRefused + | accounts, ⟨source, destination, amount⟩ => + if source = destination then .error .sameAccount + else if amount = 0 then .error .nothingToMove + else if (Account.of accounts source).status ≠ .open then .error .sourceNotOpen + else if (Account.of accounts destination).status ≠ .open then .error .destinationNotOpen + else if (Account.of accounts source).balance < amount then + .error (.insufficientFunds (Account.of accounts source).balance amount) + else .ok [ + Account.record source (.transferredOut amount), + Account.record destination (.transferredIn amount)] + + call screen (account : String) (amount : Nat) : Screening + call wire (payout account : String) (amount : Nat) : WireResult + + -- A payout takes the money out, then wires it. If the wire bounces, the money goes back. + saga Payout (PayoutRequest) (Unit) : PayoutFailed + | payout, ⟨account, amount⟩ => do + Account.must (.withdraw account amount) fun _ => .refused + Account.undoWith (.deposit account amount) + match ← wire payout account amount with + | .sent => pure () + | .bounced => failWith .bounced + + -- A second saga, with a failure type of its own. When an account closes, it is + -- frozen against reuse; a closed account cannot be, so the run fails and says why. + saga Farewell (Unit) (Unit) : FarewellFailed + | account, _ => Account.must (.freeze account "closed") fun _ => .alreadyGone + + policy Payouts on Account + | id, .payoutRequested payout amount => Payout.start payout ⟨id, amount⟩ + | id, .closed => Farewell.start id () + + -- Whenever a large deposit arrives, have it screened, and freeze the account if it is flagged. + policy Compliance on Account + | id, .deposited amount => do + if amount ≥ 10000 then + match ← screen id amount with + | .flagged reason => Account.send (.freeze id reason) + | .clear => pure () + + -- All the money the bank holds. + view Holdings on Account : Int := 0 + | total, .deposited amount => total + amount + | total, .withdrawn amount => total - amount + + -- A line for each movement of money, for the account's statement. + -- Each account's balance, as a reader sees it. + view Balances on Account by id : Int := 0 + | balance, .deposited amount => balance + amount + | balance, .withdrawn amount => balance - amount + | balance, .transferredIn amount => balance + amount + | balance, .transferredOut amount => balance - amount + + -- Each account's movements, in order, for a reader to follow. + stream Activity on Account : String + | _, .deposited amount => [s!"+{amount}"] + | _, .withdrawn amount => [s!"-{amount}"] + | _, .frozen reason => [s!"frozen: {reason}"] + + -- The accounts that are frozen, from everything recorded. + query Frozen (Unit) : String + | log, _ => (log.filterMap fun + | ⟨.Account, id, .frozen _, _, _⟩ => some id + | _ => none).eraseDups + + projection Statement on Account : String × String × Nat + | id, .deposited amount => [(id, "deposit", amount)] + | id, .withdrawn amount => [(id, "withdrawal", amount)] + +namespace Bank + +/-! ## 2. Behaviour: given, when, then + +Each holds for every owner, id and amount, not for one example. +-/ + +/-- Given an open account with money in it, when less than that is withdrawn, then it is paid out. -/ +theorem withdrawingWhatIsThere (id owner : String) (held amount : Nat) + (some : amount ≠ 0) (enough : amount ≤ held) : + Account.decide (Account.after [.opened owner, .deposited held]) (.withdraw id amount) + = .ok [.withdrawn amount] := by + simp [Aggregate.after, Aggregate.apply, Account.decide, Account.evolve, some, enough] + +/-- Given an open account, when more than it holds is withdrawn, then it is refused. -/ +theorem anOverdraftIsRefused (id owner : String) (held amount : Nat) (tooMuch : held < amount) : + Account.decide (Account.after [.opened owner, .deposited held]) (.withdraw id amount) + = .error (.insufficientFunds held amount) := by + have some : amount ≠ 0 := by omega + have short : ¬amount ≤ held := by omega + simp [Aggregate.after, Aggregate.apply, Account.decide, Account.evolve, some, short] + +/-- Given a frozen account, when money is withdrawn, then it is refused, whatever it holds. -/ +theorem aFrozenAccountPaysNothingOut (id owner reason : String) (held amount : Nat) + (some : amount ≠ 0) : + Account.decide (Account.after [.opened owner, .deposited held, .frozen reason]) + (.withdraw id amount) + = .error (.frozen reason) := by + simp [Aggregate.after, Aggregate.apply, Account.decide, Account.evolve, some] + +/-- Given an account with money in it, when it is closed, then it is refused. -/ +theorem anAccountWithMoneyStaysOpen (id owner : String) (held : Nat) (some : held ≠ 0) : + Account.decide (Account.after [.opened owner, .deposited held]) (.close id) + = .error (.notEmpty held) := by + simp [Aggregate.after, Aggregate.apply, Account.decide, Account.evolve, some] + +/-- Given a closed account, when money is deposited, then it is refused. -/ +theorem aClosedAccountTakesNoDeposits (id owner : String) (amount : Nat) (some : amount ≠ 0) : + Account.decide (Account.after [.opened owner, .closed]) (.deposit id amount) + = .error .notOpen := by + simp [Aggregate.after, Aggregate.apply, Account.decide, Account.evolve, some] + +/-- Given an open account, when money is withdrawn, then the caller is told the balance that is left. -/ +theorem aWithdrawalAnswersWhatIsLeft (id owner : String) (held amount : Nat) : + Account.reply (Account.after [.opened owner, .deposited held, .withdrawn amount]) + (.withdraw id amount) + = held - amount := by + simp [Aggregate.after, Aggregate.apply, Account.reply, Account.evolve] + +/-! ## General properties of the commands -/ + +/-- Freezing and closing are idempotent: doing either twice is doing it once. -/ +theorem freezingIsIdempotent (id reason : String) : Account.IdempotentAt (.freeze id reason) := by + command_law + +theorem closingIsIdempotent (id : String) : Account.IdempotentAt (.close id) := by + command_law + +/-- A deposit is not: sent twice, the money arrives twice. A caller must not retry it blindly. -/ +theorem aDepositIsNotIdempotent (id : String) : ¬Account.IdempotentAt (.deposit id 1) := by + intro idempotent + have := idempotent ⟨(), 0⟩ { status := .open } + simp [Aggregate.step, Aggregate.apply, Account.decide, Account.evolve] at this + +/-- Two deposits commute: the order they arrive in does not matter. -/ +theorem depositsCommute (id other : String) (amount more : Nat) : + Account.Commute (.deposit id amount) (.deposit other more) := by + command_law + +/-! ## 3. Invariants: what no command can break + +A behaviour theorem is about one history. An invariant is about every state an +account can ever be in. It is proved in two parts: it holds of a new account, +and no accepted command breaks it. +-/ + +/-- The balance is exactly what came in less what went out. -/ +def Balanced (s : Account.State) : Prop := s.balance + s.withdrawn = s.deposited + +/-- A closed account holds nothing. -/ +def ClosedIsEmpty (s : Account.State) : Prop := s.status = .closed → s.balance = 0 + +theorem balanced_kept : Account.Keeps Balanced := by + aggregate_rule + +theorem closedIsEmpty_kept : Account.Keeps ClosedIsEmpty := by + aggregate_rule + +/-- The two together, as named invariants: each holds at the start and is kept. -/ +def balanced : Aggregate.Invariant Account := + { name := "Balanced", holds := Balanced, initially := by simp [Balanced], kept := balanced_kept } + +def closedIsEmpty : Aggregate.Invariant Account := + { name := "ClosedIsEmpty", holds := ClosedIsEmpty, initially := by simp [ClosedIsEmpty], + kept := closedIsEmpty_kept } + +/-! ## 4. Consequences: for every history + +An invariant holds after any sequence of commands, sent by anyone, in any +order. Other facts then follow from it by arithmetic. +-/ + +/-- An account never pays out more than was paid in: after any commands at all. -/ +theorem neverPaysOutMoreThanCameIn (commands : List Account.Sent) : + (Account.replay {} commands).withdrawn ≤ (Account.replay {} commands).deposited := by + have := balanced.always commands + simp only [balanced, Balanced] at this + omega + +/-- No money is lost inside an account: what it holds and what it paid out add up to what came in. -/ +theorem noMoneyIsLost (commands : List Account.Sent) : + (Account.replay {} commands).balance + (Account.replay {} commands).withdrawn + = (Account.replay {} commands).deposited := + balanced.always commands + +/-- After any commands, an account that is closed is empty. -/ +theorem aClosedAccountIsEmpty (commands : List Account.Sent) + (closed : (Account.replay {} commands).status = .closed) : + (Account.replay {} commands).balance = 0 := + closedIsEmpty.always commands closed + +/-- What one command may do: nothing but a withdrawal lowers a balance. -/ +theorem onlyAWithdrawalLowersTheBalance : + Account.Transition fun _ before command after => + (∀ id amount, command ≠ .withdraw id amount) → before.balance ≤ after.balance := by + intro ctx s c es eq + cases c <;> simp only [Account.decide] at eq <;> (repeat' split at eq) <;> + grind [Aggregate.apply, Account.evolve] + +/-! ## 5. Across accounts: a transfer + +A transfer touches two accounts, so no one account's rule can speak for it. It +is a decision: it reads both accounts and records on both, or on neither. Two +things are proved of it. Each account it touches still keeps its invariants. +And across all accounts, it moves money without making any. +-/ + +/-- What the transfer records when it accepts, and what was true for it to accept. -/ +theorem transfer_accepted {accounts : States Aggregates} {request : TransferRequest} + {records : List (Record Aggregates)} (accepted : Transfer.decide accounts request = .ok records) : + request.source ≠ request.destination ∧ + (accounts .Account request.source).status = .open ∧ + (accounts .Account request.destination).status = .open ∧ + request.amount ≤ (accounts .Account request.source).balance ∧ + records = [⟨.Account, request.source, .transferredOut request.amount⟩, + ⟨.Account, request.destination, .transferredIn request.amount⟩] := by + obtain ⟨source, destination, amount⟩ := request + simp only [Transfer.decide, Account.of, Account.record] at accepted + by_cases same : source = destination + · simp [same] at accepted + by_cases none : amount = 0 + · simp [same, none] at accepted + by_cases sourceOpen : (accounts .Account source).status = .open + · by_cases destinationOpen : (accounts .Account destination).status = .open + · by_cases short : (accounts .Account source).balance < amount + · simp [same, none, sourceOpen, destinationOpen, short] at accepted + · simp [same, none, sourceOpen, destinationOpen, short] at accepted + exact ⟨same, sourceOpen, destinationOpen, Nat.le_of_not_lt short, accepted.symm⟩ + · simp [same, none, sourceOpen, destinationOpen] at accepted + · simp [same, none, sourceOpen] at accepted + +/-- A rule about one account survives every decision of the bank. -/ +abbrev SurvivesDecisions (P : Account.State → Prop) : Prop := + ∀ d ∈ Bank.decisions, ∀ (r : Recorded Aggregates) (ctx : Context d.Actor) c, + (∀ id, P (r.state .Account id)) → ∀ id, P ((r.decide d ctx c).state .Account id) + +/-- +A rule about one account survives a transfer, if it survives money leaving an +open account that holds enough, and money arriving in an open account. +-/ +theorem transfer_keeps {P : Account.State → Prop} + (leaving : ∀ s amount, P s → s.status = .open → amount ≤ s.balance → + P (Account.evolve s (.transferredOut amount))) + (arriving : ∀ s amount, P s → s.status = .open → P (Account.evolve s (.transferredIn amount))) : + SurvivesDecisions P := by + intro d mem + simp only [List.mem_singleton] at mem + subst mem + intro r ctx request holds id + simp only [Recorded.decide] + cases accepted : Transfer.decide r.state request with + | error _ => exact holds id + | ok records => + obtain ⟨differ, sourceOpen, destinationOpen, enough, rfl⟩ := transfer_accepted accepted + simp only [Recorded.records, List.foldl, Recorded.record_state] + by_cases toHere : request.destination = id + · have notSource : ¬request.source = request.destination := differ + simp only [toHere, ite_true] + subst toHere + simp only [notSource, ite_false] + exact arriving _ _ (holds _) destinationOpen + · simp only [toHere, ite_false] + by_cases fromHere : request.source = id + · subst fromHere + simp only [ite_true] + exact leaving _ _ (holds _) sourceOpen enough + · simp only [fromHere, ite_false] + exact holds id + +/-- Money moved out by transfers, and money moved in, as each event records it. -/ +def movedOut : Account.Event → Nat + | .transferredOut amount => amount + | _ => 0 + +def movedIn : Account.Event → Nat + | .transferredIn amount => amount + | _ => 0 + +/-- Across every account: all the money transfers took out equals all the money they put in. -/ +def Conserved (r : Recorded Aggregates) : Prop := + ((r.eventsOf .Account).map movedOut).sum = ((r.eventsOf .Account).map movedIn).sum + +/-- No command sent to one account moves money between accounts. -/ +theorem commands_move_nothing {s : Account.State} {command : Account.Command} + {events : List Account.Event} (accepted : Account.decide s command = .ok events) : + (events.map movedOut).sum = 0 ∧ (events.map movedIn).sum = 0 := by + cases command <;> simp only [Account.decide] at accepted <;> (repeat' split at accepted) <;> + first | cases accepted | skip + all_goals simp [movedOut, movedIn] + +/-- +No transfer creates or destroys money. In every world the bank can reach, +whatever is sent to any account and whatever transfers are decided, in any +order, what transfers took out of accounts is exactly what they put into accounts. +-/ +theorem noTransferCreatesMoney (w : Alchemy.World Signature) (reach : Bank.Reachable w) : + Conserved w.toRecorded := by + refine Bank.invariant (rule := Conserved) (by simp [Conserved, Recorded.eventsOf, Recorded.start]) ⟨?_, ?_⟩ w reach + · intro r now s conserved + rcases r.dispatch_cases now s with same | ⟨events, accepted, recorded⟩ + · rw [same]; exact conserved + · obtain ⟨to, actor, command⟩ := s + cases to + have nothing := commands_move_nothing (s := r.state .Account (Account.key command)) accepted + rw [recorded] + simp only [Conserved, Recorded.eventsOf_record_self, List.map_append, List.sum_append] at * + omega + · intro d mem r ctx request conserved + simp only [List.mem_singleton] at mem + subst mem + simp only [Recorded.decide] + cases accepted : Transfer.decide r.state request with + | error _ => exact conserved + | ok records => + obtain ⟨_, _, _, _, rfl⟩ := transfer_accepted accepted + simp only [Conserved, Recorded.records, List.foldl, Recorded.eventsOf_record_self, + List.map_append, List.sum_append, List.map_cons, List.map_nil, List.sum_cons, List.sum_nil, + movedOut, movedIn] at * + omega + +/-! ## 6. The model: every world the bank can reach + +The bank is many accounts, transfers between them, a policy that reacts to +deposits, and an outside system that answers whatever it likes. The invariants +hold all the same, of every account, and of the bank as it is deployed. +-/ + +theorem transfer_balanced : SurvivesDecisions Balanced := + transfer_keeps + (by intro s amount h _ enough; simp only [Balanced, Account.evolve] at *; omega) + (by intro s amount h _; simp only [Balanced, Account.evolve] at *; omega) + +theorem transfer_closedIsEmpty : SurvivesDecisions ClosedIsEmpty := + transfer_keeps + (by intro s amount _ isOpen _; simp [ClosedIsEmpty, Account.evolve, isOpen]) + (by intro s amount _ isOpen; simp [ClosedIsEmpty, Account.evolve, isOpen]) + +/-- +In every world the bank can reach, every account is balanced: whatever callers +send, whatever transfers are decided, whatever compliance answers, in any order +of delivery, with any event delivered twice. +-/ +theorem everyAccountBalanced (w : Alchemy.World Signature) (reach : Bank.Reachable w) + (id : String) : Balanced (w.state .Account id) := + Account.always (by simp [Balanced]) balanced_kept w reach id transfer_balanced + +/-- And of the bank as deployed: whatever its journal holds. -/ +theorem deployedAccountsBalanced (journal : List Journal.Line) (id : String) : + Balanced ((served.replay journal).state .Account id) := + Account.deployed (by simp [Balanced]) balanced_kept journal id transfer_balanced + +/-- So the deployed bank never pays out of an account more than was paid into it. -/ +theorem theBankNeverPaysOutMoreThanCameIn (journal : List Journal.Line) (id : String) : + ((served.replay journal).state .Account id).withdrawn + ≤ ((served.replay journal).state .Account id).deposited := by + have := deployedAccountsBalanced journal id + simp only [Balanced] at this + omega + +/-- And a closed account in the deployed bank is empty. -/ +theorem deployedClosedAccountsAreEmpty (journal : List Journal.Line) (id : String) + (closed : ((served.replay journal).state .Account id).status = .closed) : + ((served.replay journal).state .Account id).balance = 0 := + (Account.deployed (by simp [ClosedIsEmpty]) closedIsEmpty_kept journal id + transfer_closedIsEmpty : ClosedIsEmpty _) closed + +/-! ## Stories and theorems, together + +One scenario, written once, used three ways: a story follows it step by step for +one customer; a theorem proves its outcome for every customer; and the theorem, +given that customer, is the story's outcome again. +-/ + +/-- The scenario: an account is opened and funded, a payout is requested, and the wire bounces. -/ +def aPayoutBounces (id owner payout : String) (held amount : Nat) : List (Model.Move Bank) := [ + .send ⟨.Account, (), .open id owner⟩, + .send ⟨.Account, (), .deposit id held⟩, + .send ⟨.Account, (), .requestPayout id payout amount⟩, + .answer (.wire payout id amount) .bounced] + +/-- +The story: Sam's payout of 200 from 500. It follows the scenario, and says +what is seen on the way, with real values. +-/ +example : Bank.follows (aPayoutBounces "a-1" "Sam" "p-1" 500 200) [ + .next 3, + .call (.wire "p-1" "a-1" 200), + .state .Account "a-1" + { status := .open, owner := "Sam", balance := 300, deposited := 500, withdrawn := 200 }, + .next, + .saga (.Payout, "p-1") (.failed (.Payout .bounced)), + .recorded .Account "a-1" [.opened "Sam", .deposited 500, .payoutRequested "p-1" 200, + .withdrawn 200, .deposited 200] + ] = true := by decide + +/-- +The theorem: given an open account with money in it, when a payout is requested +and the wire bounces, then the money is back and the payout has failed. For +every account, owner and amount. +-/ +theorem aBouncedPayoutIsRefunded (id owner payout : String) (held amount : Nat) + (some : amount ≠ 0) (enough : amount ≤ held) (modest : held < 10000) : + let bank := Bank.run (aPayoutBounces id owner payout held amount) + (bank.state .Account id).balance = held ∧ bank.sagas (.Payout, payout) = .failed (.Payout .bounced) := by + behaviour [aPayoutBounces] + +/-- Sam's case is one instance of the theorem: nothing is run, the values are filled in. -/ +example : + let bank := Bank.run (aPayoutBounces "a-1" "Sam" "p-1" 500 200) + (bank.state .Account "a-1").balance = 500 ∧ bank.sagas (.Payout, "p-1") = .failed (.Payout .bounced) := + aBouncedPayoutIsRefunded "a-1" "Sam" "p-1" 500 200 (by decide) (by decide) (by decide) + +/-- +Given an open, empty account, when it is closed, then it is closed, and the +Farewell saga's run for it has failed with its own failure: a closed account +cannot be frozen. Two sagas, each with its own way to fail, in one model. +-/ +theorem closingRunsTheFarewell (id owner : String) : + let bank := Bank.run [ + .send ⟨.Account, (), .open id owner⟩, + .send ⟨.Account, (), .close id⟩] + (bank.state .Account id).status = .closed ∧ + bank.sagas (.Farewell, id) = .failed (.Farewell .alreadyGone) := by + behaviour + +/-! What is read from the bank. These came with the model. -/ + +/-- An account's activity is exactly the entries its events gave it, in order. -/ +example (log : List (Emitted Aggregates)) (id : String) : + Activity.entries log id + = (log.flatMap Activity.appended).filterMap fun (k, entry) => if k = id then some entry else none := + Activity.exact log id + +/-- A query is answered from the log: after the story below, one account is frozen. -/ +example : + ((Frozen.ask () (Bank.run [ + .send ⟨.Account, (), .open "a-1" "Sam"⟩, + .send ⟨.Account, (), .freeze "a-1" "review"⟩]).log ()).toOption.map (·.entries)) + = some ["a-1"] := by decide + +example (log : List (Emitted Aggregates)) : + Holdings.stateAt log () = log.foldl Holdings.step 0 := Holdings.exact log + +example (log : List (Emitted Aggregates)) : + Statement.table log = log.flatMap Statement.rows := Statement.exact log + +/-! ## A story: one run, as a test -/ + +example : Bank.passes [ + .when ⟨.Account, (), .open "a-1" "Sam"⟩, + .when ⟨.Account, (), .deposit "a-1" 500⟩, + .replies ⟨.Account, (), .withdraw "a-1" 200⟩ 300, + .when ⟨.Account, (), .withdraw "a-1" 200⟩, + .view Holdings () 300, + .when ⟨.Account, (), .open "a-2" "Alex"⟩, + .decide Transfer () ⟨"a-1", "a-2", 100⟩, + .state .Account "a-2" { status := .open, owner := "Alex", balance := 100, deposited := 100 }, + .decide Transfer () ⟨"a-1", "a-2", 5000⟩ (some (.insufficientFunds 200 5000)), + .view Holdings () 300, + .when ⟨.Account, (), .deposit "a-1" 25000⟩, + .call (.screen "a-1" 25000), + .answer (.screen "a-1" 25000) (.flagged "source of funds"), + .recorded .Account "a-1" [.opened "Sam", .deposited 500, .withdrawn 200, .transferredOut 100, + .deposited 25000, .frozen "source of funds"], + .recorded .Account "a-2" [.opened "Alex", .transferredIn 100], + .view Balances "a-2" 100, + .when ⟨.Account, (), .withdraw "a-1" 100⟩, + .rejected .Account (.frozen "source of funds") + ] = true := by decide + +/-! ## Eventually: the bank comes to rest + +Policies, two sagas with their undos, outside calls. Left to run from any world +it can reach, the bank stops. Each event is given a weight, each command at +least what it records, and each saga a rank; every step then lowers what is left. +-/ + + +end Bank + +comes_to_rest Bank + +namespace Bank + +/-- The weights it found, to read. -/ +example : ranking.event .Account (.payoutRequested "p-1" 200) = 21 := rfl + +/-- +The bank comes to rest. From any world it can reach, after some number of steps +nothing can go on without a caller, an outside answer or the clock. +-/ +theorem theBankComesToRest (w : Alchemy.World Signature) (reach : Bank.Reachable w) : + ∃ steps, Bank.AtRest (Bank.settle steps w) := + Bank.comesToRest w reach + +/-- So eventually, from any world the bank can reach, it is at rest with every account balanced. -/ +theorem eventuallyAtRestAndBalanced (w : Alchemy.World Signature) (reach : Bank.Reachable w) + (id : String) : Bank.Eventually w fun rested => Balanced (rested.state .Account id) := + ranking.eventually reacts (fun rested reached _ => everyAccountBalanced rested reached id) w reach + +end Bank diff --git a/packages/alchemy-lean/examples/Bank.lean b/packages/alchemy-lean/examples/Bank.lean new file mode 100644 index 00000000000..13d687a5813 --- /dev/null +++ b/packages/alchemy-lean/examples/Bank.lean @@ -0,0 +1,17 @@ +import Bank.Types +import Bank.Account +import Bank.Customer +import Bank.Transfer +import Bank.Shape +import Bank.Registration +import Bank.Views +import Bank.Reads +import Bank.Processes +import Bank.Model +import Bank.Stories +import Bank.Api +import Bank.Search +import Bank.Server +import Bank.Money +import Bank.Web +import Bank.Pending diff --git a/packages/alchemy-lean/examples/Bank/Account.lean b/packages/alchemy-lean/examples/Bank/Account.lean new file mode 100644 index 00000000000..f4798cf7b13 --- /dev/null +++ b/packages/alchemy-lean/examples/Bank/Account.lean @@ -0,0 +1,363 @@ +import Alchemy +import Bank.Types + +open Alchemy + +namespace Bank + +/-! ## Commands -/ + +structure OpenAccount where + accountId : AccountId + customerId : CustomerId + owner : String +deriving DecidableEq, Repr + +/-- Hand an account to another customer. Only an agent may. -/ +structure ChangeOwner where + accountId : AccountId + customerId : CustomerId +deriving DecidableEq, Repr + +structure DepositMoney where + accountId : AccountId + amount : Cents +deriving DecidableEq, Repr + +structure WithdrawMoney where + accountId : AccountId + amount : Cents +deriving DecidableEq, Repr + +structure FreezeAccount where + accountId : AccountId + reason : String +deriving DecidableEq, Repr + +structure CloseAccount where + accountId : AccountId +deriving DecidableEq, Repr + +/-- Take a transfer's money out, on behalf of whoever asked for the transfer. -/ +structure DebitTransfer where + accountId : AccountId + transferId : TransferId + amount : Cents + requestedBy : Actor +deriving DecidableEq, Repr + +structure CreditTransfer where + accountId : AccountId + transferId : TransferId + amount : Cents +deriving DecidableEq, Repr + +/-- Give a transfer's money back. It reports a fact, so it is never rejected. -/ +structure RefundTransfer where + accountId : AccountId + transferId : TransferId + amount : Cents +deriving DecidableEq, Repr + +/-- Money arrived from the payment processor. It reports a fact, so it is never rejected. -/ +structure RecordSettlement where + accountId : AccountId + settlementId : String + amount : Cents +deriving DecidableEq, Repr + +/-- The commands an account decides. -/ +inductive AccountCommand where + | openAccount (c : OpenAccount) + | changeOwner (c : ChangeOwner) + | deposit (c : DepositMoney) + | withdraw (c : WithdrawMoney) + | freeze (c : FreezeAccount) + | close (c : CloseAccount) + | debitTransfer (c : DebitTransfer) + | creditTransfer (c : CreditTransfer) + | refundTransfer (c : RefundTransfer) + | recordSettlement (c : RecordSettlement) +deriving DecidableEq, Repr + +/-! ## Events, rejections and state -/ + +inductive AccountEvent where + | accountOpened (customerId : CustomerId) (owner : String) + | ownerChanged (previous customerId : CustomerId) (by_ : Actor) + | moneyDeposited (amount balanceAfter : Cents) + | moneyWithdrawn (amount balanceAfter : Cents) + | accountFrozen (reason : String) (by_ : Actor) + | accountClosed + | transferDebited (transferId : TransferId) (amount balanceAfter : Cents) + | transferCredited (transferId : TransferId) (amount balanceAfter : Cents) + | transferRefunded (transferId : TransferId) (amount balanceAfter : Cents) + /-- A refund arrived at an account that is no longer open. -/ + | refundStranded (transferId : TransferId) (amount : Cents) + | settlementReceived (settlementId : String) (amount balanceAfter : Cents) + | settlementOnClosedAccount (settlementId : String) (amount : Cents) +deriving DecidableEq, Repr + +inductive AccountRejection where + | alreadyOpen + | notOpen + | notOwner + | notPermitted + | frozen (reason : String) + | insufficientFunds (balance requested : Cents) + | dailyLimitExceeded (remaining : Cents) + | balanceNotZero (balance : Cents) +deriving DecidableEq, Repr + +/-- An open account. -/ +structure Open where + customerId : CustomerId + owner : String + balance : Cents + /-- Why it is frozen, if it is. -/ + frozen : Option String + /-- The day of the last withdrawal, and what was withdrawn that day. -/ + day : Nat + withdrawn : Cents +deriving DecidableEq, Repr + +inductive AccountState where + | unopened + | opened (account : Open) + | closed +deriving DecidableEq, Repr + +/-- The most an account may withdraw in a day, in cents. -/ +def dailyLimit : Cents := 100000 + +/-! ## Decide and evolve -/ + +/-- The open account, if this actor may act on it: customers on their own, agents and the system on any. -/ +def openFor (s : AccountState) (actor : Actor) : Except AccountRejection Open := + match s with + | .opened account => + match actor with + | .customer customerId => + if customerId = account.customerId then .ok account else .error .notOwner + | _ => .ok account + | _ => .error .notOpen + +/-- What was withdrawn so far on the day of `now`. -/ +def withdrawnOn (account : Open) (now : Time) : Cents := + if account.day = dayOf now then account.withdrawn else 0 + +def decideAccount (ctx : Context Actor) (s : AccountState) : + AccountCommand → Except AccountRejection (List AccountEvent) + | .openAccount c => + match s with + | .unopened => .ok [.accountOpened c.customerId c.owner] + | _ => .error .alreadyOpen + | .changeOwner c => + match s with + | .opened account => + match ctx.actor with + | .agent _ => .ok [.ownerChanged account.customerId c.customerId ctx.actor] + | _ => .error .notPermitted + | _ => .error .notOpen + | .deposit c => + match openFor s ctx.actor with + | .error r => .error r + | .ok account => .ok [.moneyDeposited c.amount (account.balance + c.amount)] + | .withdraw c => + match openFor s ctx.actor with + | .error r => .error r + | .ok account => + match account.frozen with + | some reason => .error (.frozen reason) + | none => + if c.amount > account.balance then + .error (.insufficientFunds account.balance c.amount) + else if withdrawnOn account ctx.now + c.amount > dailyLimit then + .error (.dailyLimitExceeded (dailyLimit - withdrawnOn account ctx.now)) + else .ok [.moneyWithdrawn c.amount (account.balance - c.amount)] + | .freeze c => + match openFor s ctx.actor with + | .error r => .error r + | .ok account => + match account.frozen with + | some _ => .ok [] + | none => .ok [.accountFrozen c.reason ctx.actor] + | .close _ => + match openFor s ctx.actor with + | .error r => .error r + | .ok account => + if account.balance = 0 then .ok [.accountClosed] + else .error (.balanceNotZero account.balance) + | .debitTransfer c => + match openFor s c.requestedBy with + | .error r => .error r + | .ok account => + match account.frozen with + | some reason => .error (.frozen reason) + | none => + if c.amount > account.balance then + .error (.insufficientFunds account.balance c.amount) + else .ok [.transferDebited c.transferId c.amount (account.balance - c.amount)] + | .creditTransfer c => + match s with + | .opened account => + .ok [.transferCredited c.transferId c.amount (account.balance + c.amount)] + | _ => .error .notOpen + | .refundTransfer c => + match s with + | .opened account => + .ok [.transferRefunded c.transferId c.amount (account.balance + c.amount)] + | _ => .ok [.refundStranded c.transferId c.amount] + | .recordSettlement c => + match s with + | .opened account => + .ok [.settlementReceived c.settlementId c.amount (account.balance + c.amount)] + | _ => .ok [.settlementOnClosedAccount c.settlementId c.amount] + +/-- Events carry the outcome `decide` worked out, so `evolve` only copies it. -/ +def evolveAccount (s : AccountState) (e : AccountEvent) (time : Time) : AccountState := + match s, e with + | .unopened, .accountOpened customerId owner => + .opened { customerId, owner, balance := 0, frozen := none, day := 0, withdrawn := 0 } + | .opened account, .ownerChanged _ customerId _ => .opened { account with customerId } + | .opened account, .moneyDeposited _ balance => .opened { account with balance } + | .opened account, .moneyWithdrawn amount balance => + .opened { account with + balance, day := dayOf time, withdrawn := withdrawnOn account time + amount } + | .opened account, .accountFrozen reason _ => .opened { account with frozen := some reason } + | .opened _, .accountClosed => .closed + | .opened account, .transferDebited _ _ balance => .opened { account with balance } + | .opened account, .transferCredited _ _ balance => .opened { account with balance } + | .opened account, .transferRefunded _ _ balance => .opened { account with balance } + | .opened account, .settlementReceived _ _ balance => .opened { account with balance } + | s, _ => s + +def keyOfAccount : AccountCommand → AccountId + | .openAccount c => c.accountId + | .changeOwner c => c.accountId + | .deposit c => c.accountId + | .withdraw c => c.accountId + | .freeze c => c.accountId + | .close c => c.accountId + | .debitTransfer c => c.accountId + | .creditTransfer c => c.accountId + | .refundTransfer c => c.accountId + | .recordSettlement c => c.accountId + +/-- A deposit and a withdrawal answer with the new balance. -/ +def replyAccount (s : AccountState) : AccountCommand → Option Cents + | .deposit _ | .withdraw _ => + match s with + | .opened account => some account.balance + | _ => none + | _ => none + +/-- A bank account. -/ +abbrev Account : Aggregate where + name := "Account" + Id := AccountId + State := AccountState + Command := AccountCommand + Event := AccountEvent + Rejection := AccountRejection + Actor := Actor + initial := .unopened + keyOf := keyOfAccount + decide := decideAccount + evolve := evolveAccount + Reply := Option Cents + reply := replyAccount + +/-- An actor acts only on an open account, and is handed that account. -/ +theorem openFor_opened {s : AccountState} {actor : Actor} {account : Open} + (h : openFor s actor = .ok account) : s = .opened account := by + unfold openFor at h + split at h + · split at h + · split at h <;> simp_all + · simp_all + · simp at h + +/-! ## Rules -/ + +/-- An open account has withdrawn no more than the daily limit. -/ +def WithinDailyLimit : AccountState → Prop + | .opened account => account.withdrawn ≤ dailyLimit + | _ => True + +/-- No command an account accepts takes it past the daily limit. -/ +theorem withinDailyLimit_kept : Account.Keeps WithinDailyLimit := by + intro ctx s c es h eq + cases s <;> cases c <;> + grind [→ openFor_opened, decideAccount, evolveAccount, withdrawnOn, Aggregate.apply, + WithinDailyLimit] + +/-- The rule with its proofs, as a value a model can list and name in a report. -/ +def withinDailyLimit : Aggregate.Invariant Account where + name := "WithinDailyLimit" + holds := WithinDailyLimit + initially := trivial + kept := withinDailyLimit_kept + +/-- Whatever an account is sent, by whoever and whenever, it stays within the daily limit. -/ +theorem alwaysWithinDailyLimit (commands : List Account.Sent) : + WithinDailyLimit (Account.replay .unopened commands) := + withinDailyLimit.always commands + +/-- A closed account stays closed. -/ +theorem aClosedAccountStaysClosed : + Account.Transition fun _ before _ after => before = .closed → after = .closed := by + intro ctx s c es eq closed + subst closed + cases c <;> grind [→ openFor_opened, decideAccount, evolveAccount, Aggregate.apply] + +/-- Money leaves an account only by a withdrawal or a transfer's debit. -/ +theorem moneyLeavesOnlyByWithdrawalOrTransfer : + Account.Transition fun _ before command after => + ∀ b a, before = .opened b → after = .opened a → + b.balance ≤ a.balance ∨ (∃ c, command = .withdraw c) ∨ ∃ c, command = .debitTransfer c := by + intro ctx s c es eq + cases s <;> cases c <;> + grind [→ openFor_opened, decideAccount, evolveAccount, withdrawnOn, Aggregate.apply] + +/-- Only an agent changes who an account belongs to. -/ +theorem onlyAnAgentChangesTheOwner : + Account.Transition fun ctx before _ after => + ∀ b a, before = .opened b → after = .opened a → + b.customerId = a.customerId ∨ ∃ agentId, ctx.actor = .agent agentId := by + intro ctx s c es eq + cases s <;> cases c <;> + grind [→ openFor_opened, decideAccount, evolveAccount, withdrawnOn, Aggregate.apply] + +/-- A frozen account pays nothing out. -/ +theorem aFrozenAccountPaysNothingOut : + Account.Transition fun _ before _ after => + ∀ b a reason, before = .opened b → b.frozen = some reason → after = .opened a → + b.balance ≤ a.balance := by + intro ctx s c es eq + cases s <;> cases c <;> + grind [→ openFor_opened, decideAccount, evolveAccount, withdrawnOn, Aggregate.apply] + +/-- A story with variables in it: any withdrawal the balance and the limit allow is recorded. -/ +theorem withdrawsWhatIsAllowed (account : Open) (amount : Cents) (now : Time) + (unfrozen : account.frozen = none) (enough : amount ≤ account.balance) + (within : withdrawnOn account now + amount ≤ dailyLimit) : + Account.decide ⟨.customer account.customerId, now⟩ (.opened account) (.withdraw ⟨"a-1", amount⟩) + = .ok [.moneyWithdrawn amount (account.balance - amount)] := by + grind [decideAccount, openFor] + +/-! ## A story about one account, run when this file compiles -/ + +example : Account.story (.customer "c-1") [ + .given [.accountOpened "c-1" "Sam", .moneyDeposited 100 100], + .when (.withdraw ⟨"a-1", 30⟩), + .recorded [.moneyWithdrawn 30 70], + .as (.customer "c-2"), + .when (.withdraw ⟨"a-1", 30⟩), + .rejected .notOwner, + .as (.customer "c-1"), + .when (.withdraw ⟨"a-1", 100⟩), + .rejected (.insufficientFunds 70 100) + ] = true := by decide + +end Bank diff --git a/packages/alchemy-lean/examples/Bank/Api.lean b/packages/alchemy-lean/examples/Bank/Api.lean new file mode 100644 index 00000000000..f020239ab2c --- /dev/null +++ b/packages/alchemy-lean/examples/Bank/Api.lean @@ -0,0 +1,34 @@ +import Alchemy +import Bank.Model + +open Alchemy + +namespace Bank + +/-- What customers send and read. -/ +def CustomerApi : Api Bank where + name := "CustomerApi" + accepts + | ⟨.account, _, .deposit _⟩ | ⟨.account, _, .withdraw _⟩ | ⟨.account, _, .close _⟩ + | ⟨.transfer, _, .request _⟩ => true + | _ => false + decisions := [Registration] + views := [CustomerDashboard, AccountSummary, Statement, AccountTransfers, TransferStatus] + streams := [AccountCard] + queries := [AccountLedger] + +/-- What support agents send and read. -/ +def SupportApi : Api Bank where + name := "SupportApi" + accepts + | ⟨.account, _, .freeze _⟩ | ⟨.account, _, .changeOwner _⟩ | ⟨.transfer, _, .approve _⟩ => true + | _ => false + views := [AccountSummary, AccountActivity] + queries := [AccountLedger] + +/-- A customer cannot credit an account through their Api. -/ +example : + (CustomerApi.send (World.start BankSignature) + ⟨.account, .customer "c-1", .creditTransfer ⟨"a-1", "t-1", 100⟩⟩).isNone = true := by decide + +end Bank diff --git a/packages/alchemy-lean/examples/Bank/Customer.lean b/packages/alchemy-lean/examples/Bank/Customer.lean new file mode 100644 index 00000000000..9527fc69d9a --- /dev/null +++ b/packages/alchemy-lean/examples/Bank/Customer.lean @@ -0,0 +1,63 @@ +import Alchemy +import Bank.Types + +open Alchemy + +namespace Bank + +inductive CustomerState where + | new + | registered (name : String) (username : Username) +deriving DecidableEq, Repr + +inductive CustomerEvent where + | customerRegistered (name : String) (username : Username) +deriving DecidableEq, Repr + +/-- +A customer. It decides nothing alone: registering involves the username too, so +`Registration` decides it and records `customerRegistered` here. +-/ +abbrev Customer : Aggregate where + name := "Customer" + Id := CustomerId + State := CustomerState + Command := Empty + Event := CustomerEvent + Rejection := Empty + Actor := Actor + initial := .new + keyOf := nofun + decide := nofun + evolve + | _, .customerRegistered name username, _ => .registered name username + +inductive UsernameClaimState where + | free + | claimed (customerId : CustomerId) +deriving DecidableEq, Repr + +inductive UsernameClaimEvent where + | usernameClaimed (customerId : CustomerId) +deriving DecidableEq, Repr + +/-- +One username, and who holds it. Uniqueness spans every customer, so the rule has +an aggregate of its own, keyed by the username: every registration that asks for +a name reads this one instance. +-/ +abbrev UsernameClaim : Aggregate where + name := "UsernameClaim" + Id := Username + State := UsernameClaimState + Command := Empty + Event := UsernameClaimEvent + Rejection := Empty + Actor := Actor + initial := .free + keyOf := nofun + decide := nofun + evolve + | _, .usernameClaimed customerId, _ => .claimed customerId + +end Bank diff --git a/packages/alchemy-lean/examples/Bank/Model.lean b/packages/alchemy-lean/examples/Bank/Model.lean new file mode 100644 index 00000000000..a2f63a7d31c --- /dev/null +++ b/packages/alchemy-lean/examples/Bank/Model.lean @@ -0,0 +1,144 @@ +import Alchemy +import Bank.Registration +import Bank.Reads +import Bank.Processes + +open Alchemy + +open Bank in +/-- The bank: every aggregate, decision, view, policy, projection, stream, saga and query. -/ +abbrev Bank : Model where + name := "Bank" + signature := BankSignature + decisions := [Registration] + views := [AccountSummary, CustomerDashboard, Statement, AccountActivity, TransferStatus, + AccountTransfers, DailyOutflow] + policies := [MainAccountProvisioning, TransferExecution, TransferApprovalDeadline, FraudReview, + SettlementRefund] + projections := [Ledger] + streams := [AccountCard] + queries := [AccountLedger] + saga := executeTransfer + +namespace Bank + +/-! ## Rules about every instance -/ + +/-- A registration records nothing on an account or a transfer. -/ +theorem registration_holds {P : Model.Rule BankAggregates} + (customers : ∀ s, P .customer s) (claims : ∀ s, P .usernameClaim s) + (r : Recorded BankAggregates) (ctx : Context Actor) (c : RegisterCustomer) + (h : Model.Holds P r) : Model.Holds P (r.decide Registration ctx c) := by + cases eq : decideRegistration ctx r.state c with + | error _ => simpa [Recorded.decide, Registration, eq] using h + | ok rs => + obtain ⟨_, _, accounts, transfers⟩ := registration_states r ctx c rs eq + intro n id + cases n + · exact customers _ + · exact claims _ + · rw [accounts]; exact h .account id + · rw [transfers]; exact h .transfer id + +/-- +No account in the bank withdraws more than the daily limit, and every transfer +is between two different accounts: in every world the bank can reach, whatever +callers send, in any order of delivery, with any event delivered again, whatever +the outside systems answer, and whenever scheduled commands fire. +-/ +theorem everyInstanceKeepsItsRules (w : World BankSignature) (reach : Bank.Reachable w) : + (∀ id, WithinDailyLimit (w.state .account id)) ∧ + ∀ id, BetweenTwoAccounts (w.state .transfer id) := by + have all := Bank.always + (P := fun + | .account => WithinDailyLimit + | .transfer => BetweenTwoAccounts + | _ => fun _ => True) + (by intro n; cases n <;> trivial) + (by + intro n + cases n + · intro _ _ c; cases c + · intro _ _ c; cases c + · exact withinDailyLimit.kept + · exact betweenTwoAccounts.kept) + (by + intro d mem r ctx c h + simp only [List.mem_singleton] at mem + subst mem + exact registration_holds (fun _ => trivial) (fun _ => trivial) r ctx c h) + w reach + exact ⟨fun id => all .account id, fun id => all .transfer id⟩ + +/-! ## Rules that relate two instances -/ + +/-- +Whoever a username is claimed for is registered under it, and a registered +customer holds the username they registered under. +-/ +def NamesMatch (r : Recorded BankAggregates) : Prop := + (∀ username customerId, r.state .usernameClaim username = .claimed customerId → + ∃ name, r.state .customer customerId = .registered name username) ∧ + (∀ customerId name username, r.state .customer customerId = .registered name username → + r.state .usernameClaim username = .claimed customerId) + +theorem namesMatch_registration (r : Recorded BankAggregates) (ctx : Context Actor) + (c : RegisterCustomer) (h : NamesMatch r) : NamesMatch (r.decide Registration ctx c) := by + cases eq : decideRegistration ctx r.state c with + | error _ => simpa [Recorded.decide, Registration, eq] using h + | ok rs => + obtain ⟨customers, claims, _, _⟩ := registration_states r ctx c rs eq + obtain ⟨new, free, _⟩ := registration_accepted eq + obtain ⟨claimed, registered⟩ := h + constructor + · intro username customerId + rw [claims, customers] + grind + · intro customerId name username + rw [claims, customers] + grind + +/-- +In every world the bank can reach, usernames and customers agree: no two +customers hold one name, and nobody is registered under a name they do not hold. +-/ +theorem namesAlwaysMatch (w : World BankSignature) (reach : Bank.Reachable w) : + NamesMatch w.toRecorded := by + refine Bank.invariant (rule := NamesMatch) ?_ ?_ w reach + · constructor + · intro _ _ h; cases h + · intro _ _ _ h; cases h + · constructor + · intro r now s h + have customers : ∀ id, (r.dispatch now s).state .customer id = r.state .customer id := by + intro id + cases to : s.to with + | customer => obtain ⟨to', _, c⟩ := s; subst to; cases c + | _ => exact Recorded.dispatch_state_of_ne_name r now s .customer id (by simp [to]) + have claims : + ∀ id, (r.dispatch now s).state .usernameClaim id = r.state .usernameClaim id := by + intro id + cases to : s.to with + | usernameClaim => obtain ⟨to', _, c⟩ := s; subst to; cases c + | _ => exact Recorded.dispatch_state_of_ne_name r now s .usernameClaim id (by simp [to]) + constructor + · intro username customerId; rw [claims, customers]; exact h.1 username customerId + · intro customerId name username; rw [claims, customers]; exact h.2 customerId name username + · intro d mem r ctx c h + simp only [List.mem_singleton] at mem + subst mem + exact namesMatch_registration r ctx c h + +/-- No two customers hold one username. -/ +theorem noTwoCustomersHoldOneName (w : World BankSignature) (reach : Bank.Reachable w) + (one two : CustomerId) (nameOne nameTwo : String) (username : Username) + (first : w.state .customer one = .registered nameOne username) + (second : w.state .customer two = .registered nameTwo username) : one = two := by + obtain ⟨_, registered⟩ := namesAlwaysMatch w reach + have a := registered one nameOne username first + have b := registered two nameTwo username second + rw [a] at b + cases b + rfl + +end Bank diff --git a/packages/alchemy-lean/examples/Bank/Money.lean b/packages/alchemy-lean/examples/Bank/Money.lean new file mode 100644 index 00000000000..c69b806f323 --- /dev/null +++ b/packages/alchemy-lean/examples/Bank/Money.lean @@ -0,0 +1,700 @@ +import Alchemy +import Bank.Model +import Bank.Api + +/-! +Every cent a transfer takes out of an account is paid into another, paid back, +or recorded as stranded: proved for every world the bank can reach when callers +send what its Apis offer. The proof follows the ExecuteTransfer saga through each +of its steps, so it holds whatever happens between two of them. +-/ + +open Alchemy + +namespace Bank + +/-! ## What the saga's steps are, as programs -/ + +theorem executeTransfer_eq (id : TransferId) (input : ExecuteTransferInput) : + executeTransfer id input = .compensate (finalizer id) (gate id input) := rfl + +theorem gate_waits (id : TransferId) (input : ExecuteTransferInput) (h : input.needsApproval = true) : + gate id input = .await fun approval => + match approval with + | .expired => .pure () + | .approved => debit id input.details := by + simp only [gate, h] + show Program.bind _ _ = _ + simp only [Program.awaitSignal, Program.bind] + congr 1 + +theorem gate_goes (id : TransferId) (input : ExecuteTransferInput) (h : input.needsApproval = false) : + gate id input = debit id input.details := by + simp only [gate, h] + rfl + +theorem debit_eq (id : TransferId) (d : TransferDetails) : + debit id d = .send (debitSend id d) fun answer => + match answer with + | .ok _ => debited id d + | .error r => .fail (whyNotDebited r) := by + show Program.bind _ _ = _ + simp only [Program.step, Program.bind] + congr 1 + funext answer + cases answer <;> rfl + +theorem debited_eq (id : TransferId) (d : TransferDetails) : + debited id d = .compensate (refunder id d) (credit id d) := rfl + +theorem credit_eq (id : TransferId) (d : TransferDetails) : + credit id d = .send (creditSend id d) fun answer => + match answer with + | .ok _ => Program.tell (completeSend id) + | .error _ => .fail .destinationClosed := by + show Program.bind _ _ = _ + simp only [Program.step, Program.bind] + congr 1 + funext answer + cases answer <;> rfl + +/-! ## Money taken and given -/ + +/-- What an event takes out of an account for a transfer. -/ +def takenOf : AccountEvent → Nat + | .transferDebited _ amount _ => amount + | _ => 0 + +/-- What an event pays in, pays back, or records as stranded. -/ +def givenOf : AccountEvent → Nat + | .transferCredited _ amount _ | .transferRefunded _ amount _ | .refundStranded _ amount => amount + | _ => 0 + +def taken (r : Recorded BankAggregates) : Nat := ((r.eventsOf .account).map takenOf).sum +def given (r : Recorded BankAggregates) : Nat := ((r.eventsOf .account).map givenOf).sum + +/-- A command to an account, as a send. -/ +abbrev accountSend (actor : Actor) (command : AccountCommand) : Send BankAggregates := + ⟨.account, actor, command⟩ + +/-- What a command to an account adds to the account events. -/ +def added (r : Recorded BankAggregates) (now : Time) (actor : Actor) (command : AccountCommand) : + List AccountEvent := + match decideAccount ⟨actor, now⟩ (r.state .account (keyOfAccount command)) command with + | .ok es => es + | .error _ => [] + +theorem account_events (r : Recorded BankAggregates) (now : Time) (actor : Actor) + (command : AccountCommand) : + (r.dispatch now (accountSend actor command)).eventsOf .account + = r.eventsOf .account ++ added r now actor command := by + have outcome : r.outcome now (accountSend actor command) + = decideAccount ⟨actor, now⟩ (r.state .account (keyOfAccount command)) command := rfl + unfold Recorded.dispatch added + cases h : decideAccount ⟨actor, now⟩ (r.state .account (keyOfAccount command)) command with + | ok es => + rw [outcome, h] + exact Recorded.eventsOf_record_self r now .account (keyOfAccount command) es + | error e => + rw [outcome, h] + simp + +theorem account_money (r : Recorded BankAggregates) (now : Time) (actor : Actor) + (command : AccountCommand) : + taken (r.dispatch now (accountSend actor command)) + = taken r + ((added r now actor command).map takenOf).sum ∧ + given (r.dispatch now (accountSend actor command)) + = given r + ((added r now actor command).map givenOf).sum := by + simp [taken, given, account_events] + +/-- A command that moves no transfer money. -/ +def quietCommand : AccountCommand → Prop + | .debitTransfer _ | .creditTransfer _ | .refundTransfer _ => False + | _ => True + +/-- A send that moves no transfer money: anything but a transfer's debit, credit or refund. -/ +def Quiet : Send BankAggregates → Prop + | ⟨.account, _, command⟩ => quietCommand command + | _ => True + +theorem quiet_events {ctx : Context Actor} {state : AccountState} {command : AccountCommand} + {es : List AccountEvent} (quiet : quietCommand command) + (h : decideAccount ctx state command = .ok es) : + (es.map takenOf).sum = 0 ∧ (es.map givenOf).sum = 0 := by + cases command <;> simp only [quietCommand] at quiet <;> simp only [decideAccount] at h <;> + (repeat' split at h) <;> (try cases h) <;> simp [takenOf, givenOf] + +theorem quiet_adds_nothing (r : Recorded BankAggregates) (now : Time) (actor : Actor) + (command : AccountCommand) (quiet : quietCommand command) : + ((added r now actor command).map takenOf).sum = 0 ∧ + ((added r now actor command).map givenOf).sum = 0 := by + unfold added + cases h : decideAccount ⟨actor, now⟩ (r.state .account (keyOfAccount command)) command with + | ok es => exact quiet_events quiet h + | error e => simp + +/-- A quiet send changes neither total. -/ +theorem quiet_money (r : Recorded BankAggregates) (now : Time) (s : Send BankAggregates) + (quiet : Quiet s) : + taken (r.dispatch now s) = taken r ∧ given (r.dispatch now s) = given r := by + obtain ⟨to, actor, command⟩ := s + cases to with + | customer => cases command + | usernameClaim => cases command + | account => + have money := account_money r now actor command + have nothing := quiet_adds_nothing r now actor command quiet + exact ⟨by rw [money.1, nothing.1]; rfl, by rw [money.2, nothing.2]; rfl⟩ + | transfer => + have same : (r.dispatch now ⟨.transfer, actor, command⟩).eventsOf .account + = r.eventsOf .account := by + unfold Recorded.dispatch + split + · exact Recorded.eventsOf_record_of_ne r now .transfer .account _ _ (by decide) + · rfl + simp [taken, given, same] + +theorem added_of_ok {r : Recorded BankAggregates} {now : Time} {actor : Actor} + {command : AccountCommand} {es : List AccountEvent} + (h : r.outcome now (accountSend actor command) = .ok es) : added r now actor command = es := by + have decided : decideAccount ⟨actor, now⟩ (r.state .account (keyOfAccount command)) command + = .ok es := h + simp [added, decided] + +theorem added_of_error {r : Recorded BankAggregates} {now : Time} {actor : Actor} + {command : AccountCommand} {e : AccountRejection} + (h : r.outcome now (accountSend actor command) = .error e) : added r now actor command = [] := by + have decided : decideAccount ⟨actor, now⟩ (r.state .account (keyOfAccount command)) command + = .error e := h + simp [added, decided] + +/-- A debit that is accepted takes exactly the amount. -/ +theorem debit_events {ctx : Context Actor} {state : AccountState} {c : DebitTransfer} + {es : List AccountEvent} (h : decideAccount ctx state (.debitTransfer c) = .ok es) : + (es.map takenOf).sum = c.amount ∧ (es.map givenOf).sum = 0 := by + simp only [decideAccount] at h + (repeat' split at h) <;> (try cases h) <;> simp [takenOf, givenOf] + +/-- A credit that is accepted gives exactly the amount. -/ +theorem credit_events {ctx : Context Actor} {state : AccountState} {c : CreditTransfer} + {es : List AccountEvent} (h : decideAccount ctx state (.creditTransfer c) = .ok es) : + (es.map takenOf).sum = 0 ∧ (es.map givenOf).sum = c.amount := by + simp only [decideAccount] at h + (repeat' split at h) <;> (try cases h) <;> simp [takenOf, givenOf] + +/-- A refund is never rejected, and gives exactly the amount: paid back, or recorded as stranded. -/ +theorem refund_events (ctx : Context Actor) (state : AccountState) (c : RefundTransfer) : + ∃ es, decideAccount ctx state (.refundTransfer c) = .ok es ∧ + (es.map takenOf).sum = 0 ∧ (es.map givenOf).sum = c.amount := by + cases state <;> simp [decideAccount, takenOf, givenOf] + +/-! ## Programs that move no transfer money -/ + +/-- A policy's reaction: it sends quiet commands, calls outside, starts and signals sagas. -/ +inductive Harmless : Program BankSignature Unit → Prop where + | pure : Harmless (.pure ()) + | send (s k) : Quiet s → (∀ answer, Harmless (k answer)) → Harmless (.send s k) + | call (c k) : (∀ reply, Harmless (k reply)) → Harmless (.call c k) + | start (saga input k) : Harmless k → Harmless (.start saga input k) + | signal (saga signal k) : Harmless k → Harmless (.signal saga signal k) + | schedule (after s k) : Quiet s → Harmless k → Harmless (.schedule after s k) + +theorem Harmless.bind {p : Program BankSignature Unit} {f : Unit → Program BankSignature Unit} + (hp : Harmless p) (hf : Harmless (f ())) : Harmless (p.bind f) := by + induction hp with + | pure => exact hf + | send s k quiet _ ih => exact .send s _ quiet ih + | call c k _ ih => exact .call c _ ih + | start saga input k _ ih => exact .start saga input _ ih + | signal saga signal k _ ih => exact .signal saga signal _ ih + | schedule after s k quiet _ ih => exact .schedule after s _ quiet ih + +theorem harmless_tell (s : Send BankAggregates) (quiet : Quiet s) : Harmless (Program.tell s) := + .send s _ quiet fun _ => .pure + +/-- Every policy of the bank reacts harmlessly, to any event after any history. -/ +theorem policies_harmless (p : Policy BankSignature) (mem : p ∈ Bank.policies) + (history : List (Emitted BankAggregates)) (e : Emitted BankAggregates) : + Harmless (p.react history e) := by + simp only [Bank, List.mem_cons, List.mem_nil_iff, or_false] at mem + obtain ⟨source, id, event, seq, time⟩ := e + rcases mem with rfl | rfl | rfl | rfl | rfl + · -- MainAccountProvisioning + cases source <;> simp only [MainAccountProvisioning, Policy.on] <;> (try exact .pure) + cases event + exact harmless_tell _ trivial + · -- TransferExecution + cases source <;> simp only [TransferExecution, Policy.on] <;> (try exact .pure) + cases event + · exact .start _ _ _ .pure + · exact .signal _ _ _ .pure + · exact .pure + · exact .signal _ _ _ .pure + · -- TransferApprovalDeadline + cases source <;> simp only [TransferApprovalDeadline, Policy.on] <;> (try exact .pure) + cases event <;> (try exact .pure) + rename_i details needsApproval + cases needsApproval + · exact .pure + · exact .schedule _ _ _ trivial .pure + · -- FraudReview + simp only [FraudReview, Policy.onView] + generalize DailyOutflow.emittedBy history _ = emitted + induction emitted with + | nil => exact .pure + | cons x rest ih => + refine Harmless.bind ?_ ih + refine .call _ _ fun score => ?_ + show Harmless (if score.risk > 80 then _ else _) + split + · exact harmless_tell _ trivial + · exact .pure + · -- SettlementRefund + cases source <;> simp only [SettlementRefund, Policy.on] <;> (try exact .pure) + cases event <;> (try exact .pure) + exact .call _ _ fun _ => .pure + +/-! ## The bank as its callers reach it -/ + +/-- The bank, with callers sending only what its Apis offer. -/ +abbrev ServedBank : Model := + { Bank with offered := fun s => CustomerApi.accepts s = true ∨ SupportApi.accepts s = true } + +/-- The Apis offer no way to debit, credit or refund a transfer directly. -/ +theorem offered_quiet (s : Send BankAggregates) (h : ServedBank.offered s) : Quiet s := by + obtain ⟨to, actor, command⟩ := s + cases to <;> cases command <;> simp_all [Quiet, quietCommand, CustomerApi, SupportApi] + +/-- Two lists that go together, item by item. -/ +inductive Each {α β : Type} (R : α → β → Prop) : List α → List β → Prop where + | nil : Each R [] [] + | cons {a b as bs} : R a b → Each R as bs → Each R (a :: as) (b :: bs) + +theorem Each.append {α β : Type} {R : α → β → Prop} {as as' : List α} {bs bs' : List β} + (h : Each R as bs) (h' : Each R as' bs') : Each R (as ++ as') (bs ++ bs') := by + induction h with + | nil => exact h' + | cons r _ ih => exact .cons r ih + +theorem Each.split {α β : Type} {R : α → β → Prop} {before after : List α} {a : α} : + ∀ {bs : List β}, Each R (before ++ a :: after) bs → + ∃ bb b ba, bs = bb ++ b :: ba ∧ Each R before bb ∧ R a b ∧ Each R after ba := by + induction before with + | nil => + intro bs h + cases h with + | cons r rest => exact ⟨[], _, _, rfl, .nil, r, rest⟩ + | cons x xs ih => + intro bs h + cases h with + | cons r rest => + obtain ⟨bb, b, ba, eq, hb, hr, ha⟩ := ih rest + exact ⟨_ :: bb, b, ba, by rw [eq]; rfl, .cons r hb, hr, ha⟩ + +/-! ## Where the saga stands, and what it owes -/ + +/-- A step of the ExecuteTransfer saga a run can be at. -/ +inductive Stage where + | begin (id : TransferId) (input : ExecuteTransferInput) + | gate (id : TransferId) (input : ExecuteTransferInput) + | debit (id : TransferId) (d : TransferDetails) + /-- The debit is recorded, and its compensation is not yet registered. -/ + | debited (id : TransferId) (d : TransferDetails) + | credit (id : TransferId) (d : TransferDetails) + | completing (id : TransferId) (d : TransferDetails) + | finished (id : TransferId) (undo : List (TransferFailure → Send BankAggregates)) + /-- The credit was refused: the refund is next. -/ + | refunding (id : TransferId) (d : TransferDetails) (failure : TransferFailure) + | failing (id : TransferId) (failure : TransferFailure) + | failed (id : TransferId) (failure : TransferFailure) + +/-- The run's fiber at a stage. -/ +def Stage.fiber : Stage → Fiber BankSignature + | .begin id input => ⟨some id, executeTransfer id input, []⟩ + | .gate id input => ⟨some id, Bank.gate id input, [finalizer id]⟩ + | .debit id d => ⟨some id, Bank.debit id d, [finalizer id]⟩ + | .debited id d => ⟨some id, Bank.debited id d, [finalizer id]⟩ + | .credit id d => ⟨some id, Bank.credit id d, [refunder id d, finalizer id]⟩ + | .completing id d => ⟨some id, Program.tell (completeSend id), [refunder id d, finalizer id]⟩ + | .finished id undo => ⟨some id, .pure (), undo⟩ + | .refunding id d failure => ⟨some id, .fail failure, [refunder id d, finalizer id]⟩ + | .failing id failure => ⟨some id, .fail failure, [finalizer id]⟩ + | .failed id failure => ⟨some id, .fail failure, []⟩ + +/-- What a run at a stage has taken and not yet given back or passed on. -/ +def Stage.owed : Stage → Nat + | .debited _ d | .credit _ d | .refunding _ d _ => d.amount + | _ => 0 + +/-- What a fiber owes: a saga's run by its stage, a policy's reaction nothing. -/ +inductive Owes : Fiber BankSignature → Nat → Prop where + | saga (stage : Stage) : Owes stage.fiber stage.owed + | policy (p : Program BankSignature Unit) : Harmless p → Owes ⟨none, p, []⟩ 0 + +theorem dispatch_toRecorded (w : World BankSignature) (s : Send BankAggregates) : + (w.dispatch s).toRecorded = w.toRecorded.dispatch w.now s := rfl + +theorem finish_toRecorded (w : World BankSignature) (owner : Option TransferId) + (status : SagaStatus BankSignature) : (w.finish owner status).toRecorded = w.toRecorded := by + cases owner <;> rfl + +theorem finish_schedule (w : World BankSignature) (owner : Option TransferId) + (status : SagaStatus BankSignature) : (w.finish owner status).schedule = w.schedule := by + cases owner <;> rfl + +/-- What a quiet send leaves of the two totals, on the world. -/ +theorem quiet_world (w : World BankSignature) (s : Send BankAggregates) (quiet : Quiet s) : + taken (w.dispatch s).toRecorded = taken w.toRecorded ∧ + given (w.dispatch s).toRecorded = given w.toRecorded := + quiet_money w.toRecorded w.now s quiet + +/-- What the saga's debit does to the two totals: takes the amount, or nothing. -/ +theorem debit_world (w : World BankSignature) (id : TransferId) (d : TransferDetails) : + (∀ es, w.toRecorded.outcome w.now (debitSend id d) = .ok es → + taken (w.dispatch (debitSend id d)).toRecorded = taken w.toRecorded + d.amount ∧ + given (w.dispatch (debitSend id d)).toRecorded = given w.toRecorded) ∧ + (∀ e, w.toRecorded.outcome w.now (debitSend id d) = .error e → + taken (w.dispatch (debitSend id d)).toRecorded = taken w.toRecorded ∧ + given (w.dispatch (debitSend id d)).toRecorded = given w.toRecorded) := by + have money := account_money w.toRecorded w.now sagaActor + (.debitTransfer ⟨d.source, id, d.amount, d.requestedBy⟩) + constructor + · intro es outcome + have events := debit_events (ctx := ⟨sagaActor, w.now⟩) (state := w.state .account d.source) + (c := ⟨d.source, id, d.amount, d.requestedBy⟩) (es := es) outcome + rw [added_of_ok outcome] at money + exact ⟨by rw [dispatch_toRecorded, money.1, events.1], by rw [dispatch_toRecorded, money.2, events.2]; rfl⟩ + · intro e outcome + rw [added_of_error outcome] at money + exact ⟨by rw [dispatch_toRecorded, money.1]; rfl, by rw [dispatch_toRecorded, money.2]; rfl⟩ + +/-- What the saga's credit does to the two totals: gives the amount, or nothing. -/ +theorem credit_world (w : World BankSignature) (id : TransferId) (d : TransferDetails) : + (∀ es, w.toRecorded.outcome w.now (creditSend id d) = .ok es → + taken (w.dispatch (creditSend id d)).toRecorded = taken w.toRecorded ∧ + given (w.dispatch (creditSend id d)).toRecorded = given w.toRecorded + d.amount) ∧ + (∀ e, w.toRecorded.outcome w.now (creditSend id d) = .error e → + taken (w.dispatch (creditSend id d)).toRecorded = taken w.toRecorded ∧ + given (w.dispatch (creditSend id d)).toRecorded = given w.toRecorded) := by + have money := account_money w.toRecorded w.now sagaActor + (.creditTransfer ⟨d.destination, id, d.amount⟩) + constructor + · intro es outcome + have events := credit_events (ctx := ⟨sagaActor, w.now⟩) + (state := w.state .account d.destination) (c := ⟨d.destination, id, d.amount⟩) (es := es) outcome + rw [added_of_ok outcome] at money + exact ⟨by rw [dispatch_toRecorded, money.1, events.1]; rfl, by rw [dispatch_toRecorded, money.2, events.2]⟩ + · intro e outcome + rw [added_of_error outcome] at money + exact ⟨by rw [dispatch_toRecorded, money.1]; rfl, by rw [dispatch_toRecorded, money.2]; rfl⟩ + +/-- The refund always gives the amount back: paid in, or recorded as stranded. -/ +theorem refund_world (w : World BankSignature) (id : TransferId) (d : TransferDetails) + (failure : TransferFailure) : + taken (w.dispatch (refunder id d failure)).toRecorded = taken w.toRecorded ∧ + given (w.dispatch (refunder id d failure)).toRecorded = given w.toRecorded + d.amount := by + have money := account_money w.toRecorded w.now sagaActor (.refundTransfer ⟨d.source, id, d.amount⟩) + obtain ⟨es, decided, none, all⟩ := refund_events ⟨sagaActor, w.now⟩ (w.state .account d.source) + ⟨d.source, id, d.amount⟩ + rw [added_of_ok (r := w.toRecorded) (now := w.now) (actor := sagaActor) + (command := .refundTransfer ⟨d.source, id, d.amount⟩) decided] at money + exact ⟨by rw [dispatch_toRecorded, money.1, none]; rfl, by rw [dispatch_toRecorded, money.2, all]⟩ + +/-- +One step of a fiber keeps the books: what it takes and gives matches what it +owes before and after. `os` is what the fibers that replace it owe. +-/ +theorem advance_owes {w w' : World BankSignature} {f : Fiber BankSignature} + {fs : List (Fiber BankSignature)} {o : Nat} (owes : Owes f o) + (adv : ServedBank.advance w f = some (w', fs)) : + ∃ os, Each Owes fs os ∧ + taken w'.toRecorded + given w.toRecorded + o + = taken w.toRecorded + given w'.toRecorded + os.sum ∧ + ∀ x ∈ w'.schedule, x ∈ w.schedule ∨ Quiet x.2 := by + cases owes with + | saga stage => + cases stage with + | «begin» id input => + simp only [Stage.fiber, Model.advance, executeTransfer_eq] at adv + cases adv + exact ⟨[0], .cons (.saga (.gate id input)) .nil, by simp [Stage.owed], fun x h => .inl h⟩ + | gate id input => + cases approval : input.needsApproval with + | false => + simp only [Stage.fiber, Model.advance, gate_goes id input approval, debit_eq] at adv + cases adv + cases outcome : w.toRecorded.outcome w.now (debitSend id input.details) with + | ok es => + obtain ⟨t, g⟩ := (debit_world w id input.details).1 es outcome + refine ⟨[input.details.amount], .cons ?_ .nil, ?_, fun x h => .inl h⟩ + · simpa [Stage.fiber, Stage.owed, outcome] using Owes.saga (.debited id input.details) + · simp only [Stage.owed, List.sum_cons, List.sum_nil] + omega + | error e => + obtain ⟨t, g⟩ := (debit_world w id input.details).2 e outcome + refine ⟨[0], .cons ?_ .nil, ?_, fun x h => .inl h⟩ + · simpa [Stage.fiber, Stage.owed, outcome] using Owes.saga (.failing id (whyNotDebited e)) + · simp only [Stage.owed, List.sum_cons, List.sum_nil] + omega + | true => + simp only [Stage.fiber, Model.advance, gate_waits id input approval] at adv + split at adv + · cases adv + · next signal rest _ => + cases adv + cases signal with + | approved => + exact ⟨[0], .cons (.saga (.debit id input.details)) .nil, by simp [Stage.owed], + fun x h => .inl h⟩ + | expired => + exact ⟨[0], .cons (.saga (.finished id [finalizer id])) .nil, by simp [Stage.owed], + fun x h => .inl h⟩ + | debit id d => + simp only [Stage.fiber, Model.advance, debit_eq] at adv + cases adv + cases outcome : w.toRecorded.outcome w.now (debitSend id d) with + | ok es => + obtain ⟨t, g⟩ := (debit_world w id d).1 es outcome + refine ⟨[d.amount], .cons ?_ .nil, ?_, fun x h => .inl h⟩ + · simpa [Stage.fiber, Stage.owed, outcome] using Owes.saga (.debited id d) + · simp only [Stage.owed, List.sum_cons, List.sum_nil] + omega + | error e => + obtain ⟨t, g⟩ := (debit_world w id d).2 e outcome + refine ⟨[0], .cons ?_ .nil, ?_, fun x h => .inl h⟩ + · simpa [Stage.fiber, Stage.owed, outcome] using Owes.saga (.failing id (whyNotDebited e)) + · simp only [Stage.owed, List.sum_cons, List.sum_nil] + omega + | debited id d => + simp only [Stage.fiber, Model.advance, debited_eq] at adv + cases adv + exact ⟨[d.amount], .cons (.saga (.credit id d)) .nil, by simp [Stage.owed], fun x h => .inl h⟩ + | credit id d => + simp only [Stage.fiber, Model.advance, credit_eq] at adv + cases adv + cases outcome : w.toRecorded.outcome w.now (creditSend id d) with + | ok es => + obtain ⟨t, g⟩ := (credit_world w id d).1 es outcome + refine ⟨[0], .cons ?_ .nil, ?_, fun x h => .inl h⟩ + · simpa [Stage.fiber, Stage.owed, outcome] using Owes.saga (.completing id d) + · simp only [Stage.owed, List.sum_cons, List.sum_nil] + omega + | error e => + obtain ⟨t, g⟩ := (credit_world w id d).2 e outcome + refine ⟨[d.amount], .cons ?_ .nil, ?_, fun x h => .inl h⟩ + · simpa [Stage.fiber, Stage.owed, outcome] using + Owes.saga (.refunding id d .destinationClosed) + · simp only [Stage.owed, List.sum_cons, List.sum_nil] + omega + | completing id d => + simp only [Stage.fiber, Model.advance, Program.tell] at adv + cases adv + obtain ⟨t, g⟩ := quiet_world w (completeSend id) trivial + refine ⟨[0], .cons (.saga (.finished id [refunder id d, finalizer id])) .nil, ?_, + fun x h => .inl h⟩ + simp only [Stage.owed, List.sum_cons, List.sum_nil] + omega + | finished id undo => + simp only [Stage.fiber, Model.advance] at adv + cases adv + refine ⟨[], .nil, ?_, fun x h => .inl (by simpa [finish_schedule] using h)⟩ + simp [Stage.owed, finish_toRecorded] + | refunding id d failure => + simp only [Stage.fiber, Model.advance] at adv + cases adv + obtain ⟨t, g⟩ := refund_world w id d failure + refine ⟨[0], .cons (.saga (.failing id failure)) .nil, ?_, fun x h => .inl h⟩ + simp only [Stage.owed, List.sum_cons, List.sum_nil] + omega + | failing id failure => + simp only [Stage.fiber, Model.advance] at adv + cases adv + obtain ⟨t, g⟩ := quiet_world w (finalizer id failure) trivial + refine ⟨[0], .cons (.saga (.failed id failure)) .nil, ?_, fun x h => .inl h⟩ + simp only [Stage.owed, List.sum_cons, List.sum_nil] + omega + | failed id failure => + simp only [Stage.fiber, Model.advance] at adv + cases adv + refine ⟨[], .nil, ?_, fun x h => .inl (by simpa [finish_schedule] using h)⟩ + simp [Stage.owed, finish_toRecorded] + | policy p harmless => + cases harmless with + | pure => + simp only [Model.advance] at adv + cases adv + exact ⟨[], .nil, by simp [finish_toRecorded], fun x h => .inl (by simpa [finish_schedule] using h)⟩ + | send s k quiet next => + simp only [Model.advance] at adv + cases adv + obtain ⟨t, g⟩ := quiet_world w s quiet + refine ⟨[0], .cons (.policy _ (next _)) .nil, ?_, fun x h => .inl h⟩ + simp only [List.sum_cons, List.sum_nil] + omega + | call c k next => + simp only [Model.advance] at adv + cases adv + | start saga input k next => + simp only [Model.advance] at adv + split at adv + · cases adv + exact ⟨[0, 0], .cons (.policy _ next) (.cons (.saga (.begin saga input)) .nil), by simp, + fun x h => .inl h⟩ + · cases adv + exact ⟨[0], .cons (.policy _ next) .nil, by simp, fun x h => .inl h⟩ + | signal saga signal k next => + simp only [Model.advance] at adv + cases adv + exact ⟨[0], .cons (.policy _ next) .nil, by simp, fun x h => .inl h⟩ + | schedule after s k quiet next => + simp only [Model.advance] at adv + cases adv + refine ⟨[0], .cons (.policy _ next) .nil, by simp, fun x h => ?_⟩ + simp only [List.mem_append, List.mem_singleton] at h + rcases h with h | rfl + · exact .inl h + · exact .inr quiet + +/-! ## The rule -/ + +/-- A registration records nothing on an account. -/ +theorem registration_money (r : Recorded BankAggregates) (ctx : Context Actor) + (c : RegisterCustomer) : + taken (r.decide Registration ctx c) = taken r ∧ given (r.decide Registration ctx c) = given r := by + have same : (r.decide Registration ctx c).eventsOf .account = r.eventsOf .account := by + cases eq : decideRegistration ctx r.state c with + | error _ => simp [Recorded.decide, Registration, eq] + | ok rs => + obtain ⟨_, _, records⟩ := registration_accepted eq + subst records + simp only [Recorded.decide, Registration, eq, Recorded.records, List.foldl] + rw [Recorded.eventsOf_record_of_ne (g := BankAggregates) (n := .usernameClaim) + (n' := .account) _ _ _ _ (by decide), + Recorded.eventsOf_record_of_ne (g := BankAggregates) (n := .customer) (n' := .account) + _ _ _ _ (by decide)] + simp [taken, given, same] + +/-- What the books say: the fibers' debts add up to what was taken and not given. -/ +def Balanced (w : World BankSignature) : Prop := + (∃ debts : List Nat, Each Owes w.fibers debts ∧ + taken w.toRecorded = (given w.toRecorded) + debts.sum) ∧ + -- Nothing scheduled moves transfer money. + ∀ x, x ∈ w.schedule → Quiet x.2 + +/-- The policies' reactions to an event owe nothing. -/ +theorem reactions_owe_nothing (history : List (Emitted BankAggregates)) + (e : Emitted BankAggregates) : + ∀ policies : List (Policy BankSignature), (∀ p ∈ policies, p ∈ Bank.policies) → + ∃ owed, Each Owes + (policies.map fun p => ({ owner := none, program := p.react history e, undo := [] } : + Fiber BankSignature)) owed ∧ owed.sum = 0 := by + intro policies + induction policies with + | nil => intro _; exact ⟨[], .nil, rfl⟩ + | cons p ps ih => + intro mem + obtain ⟨owed, each, zero⟩ := ih fun q h => mem q (List.mem_cons_of_mem _ h) + exact ⟨0 :: owed, .cons (.policy _ (policies_harmless p (mem p List.mem_cons_self) history e)) each, + by simp [zero]⟩ + +theorem react_balanced (w : World BankSignature) (e : Emitted BankAggregates) + (h : Balanced w) : Balanced (ServedBank.react w e) := by + obtain ⟨owed, each, books⟩ := h.1 + obtain ⟨more, reactions, zero⟩ := reactions_owe_nothing (w.log.take e.seq) e Bank.policies + fun _ h => h + refine ⟨⟨owed ++ more, each.append reactions, ?_⟩, h.2⟩ + rw [List.sum_append, zero] + exact books + +/-- +Every cent a transfer takes out of an account is paid into another, paid back, +recorded as stranded, or still owed by a saga's run that is part-way through. +It holds in every world the bank can reach when callers send what the Apis +offer: in any order of delivery, with any event delivered again, whichever +step runs next, whatever the outside systems answer, whenever time passes. +-/ +theorem alwaysBalanced (w : World BankSignature) (reach : ServedBank.Reachable w) : Balanced w := by + refine ServedBank.worldInvariant (rule := Balanced) ?_ ?_ w reach + · exact ⟨⟨[], .nil, rfl⟩, fun x h => by cases h⟩ + · intro w w' h step + obtain ⟨owed, each, books⟩ := h.1 + cases step with + | send s offered => + obtain ⟨t, g⟩ := quiet_world w s (offered_quiet s offered) + exact ⟨⟨owed, each, by omega⟩, h.2⟩ + | decide d actor c mem => + simp only [List.mem_singleton] at mem + subst mem + obtain ⟨t, g⟩ := registration_money w.toRecorded ⟨actor, w.now⟩ c + refine ⟨⟨owed, each, ?_⟩, h.2⟩ + show taken (w.toRecorded.decide Registration ⟨actor, w.now⟩ c) + = given (w.toRecorded.decide Registration ⟨actor, w.now⟩ c) + owed.sum + exact t.trans (books.trans (congrArg (· + owed.sum) g.symm)) + | deliver e before after _ => + exact react_balanced { w with inbox := before ++ after } e ⟨⟨owed, each, books⟩, h.2⟩ + | redeliver e _ => exact react_balanced w e h + | advance f before after w'' fs fibers adv => + rw [fibers] at each + obtain ⟨ob, o, oa, eq, eb, owes, ea⟩ := each.split + obtain ⟨os, eachs, money, sched⟩ := advance_owes owes adv + subst eq + refine ⟨⟨ob ++ os ++ oa, (eb.append eachs).append ea, ?_⟩, ?_⟩ + · simp only [List.sum_append, List.sum_cons] at books ⊢ + show taken w''.toRecorded = given w''.toRecorded + _ + omega + · intro x mem + rcases sched x mem with old | quiet + · exact h.2 x old + · exact quiet + | answer f before after c k reply fibers program => + rw [fibers] at each + obtain ⟨ob, o, oa, eq, eb, owes, ea⟩ := each.split + subst eq + have ⟨zero, next⟩ : o = 0 ∧ Owes { f with program := k reply } 0 := by + cases owes with + | saga stage => + exfalso + cases stage with + | gate id input => + cases approval : input.needsApproval with + | false => simp [Stage.fiber, gate_goes id input approval, debit_eq] at program + | true => simp [Stage.fiber, gate_waits id input approval] at program + | _ => + simp [Stage.fiber, executeTransfer_eq, debit_eq, debited_eq, credit_eq, Program.tell] + at program + | policy p harmless => + cases harmless with + | call c' k' following => cases program; exact ⟨rfl, .policy _ (following _)⟩ + | _ => cases program + subst zero + exact ⟨⟨ob ++ 0 :: oa, eb.append (.cons next ea), books⟩, h.2⟩ + | tick time _ => exact ⟨⟨owed, each, books⟩, h.2⟩ + | fire due s before after schedule _ => + have quiet : Quiet s := h.2 (due, s) (by rw [schedule]; simp) + obtain ⟨t, g⟩ := quiet_world { w with schedule := before ++ after } s quiet + refine ⟨⟨owed, each, by + show taken ({ w with schedule := before ++ after }.dispatch s).toRecorded = _ + have : taken w.toRecorded = given w.toRecorded + owed.sum := books + simp only [] at t g + omega⟩, ?_⟩ + intro x mem + apply h.2 + rw [schedule] + have here : x ∈ before ++ after := mem + simp only [List.mem_append, List.mem_cons] at here ⊢ + rcases here with m | m + · exact .inl m + · exact .inr (.inr m) + +/-- +Once nothing is part-way through, the books close: every cent a transfer took +out of an account was paid into another, paid back, or recorded as stranded. +-/ +theorem transfersLoseNoMoney (w : World BankSignature) (reach : ServedBank.Reachable w) + (settled : w.fibers = []) : taken w.toRecorded = given w.toRecorded := by + obtain ⟨⟨owed, each, books⟩, _⟩ := alwaysBalanced w reach + rw [settled] at each + cases each + simpa using books + +end Bank diff --git a/packages/alchemy-lean/examples/Bank/Pending.lean b/packages/alchemy-lean/examples/Bank/Pending.lean new file mode 100644 index 00000000000..d684d012397 --- /dev/null +++ b/packages/alchemy-lean/examples/Bank/Pending.lean @@ -0,0 +1,1062 @@ +import Alchemy +import Bank.Money + +/-! +Every transfer ends, and none is left pending: proved for every world the bank +can reach, whatever its callers send. Once every event is delivered and no +policy or saga is part-way through or waiting, each transfer that was asked for +has completed or has failed. +-/ + +open Alchemy + +namespace Bank + +/-! ## Where a transfer has got to -/ + +/-- Past its request and any approval: pending, or ended. -/ +def PastState : TransferState → Prop + | .pending _ | .completed | .failed _ => True + | _ => False + +def FailedState : TransferState → Prop + | .failed _ => True + | _ => False + +def EndedState : TransferState → Prop + | .completed | .failed _ => True + | _ => False + +abbrev PastAt (r : Recorded BankAggregates) (t : TransferId) : Prop := PastState (r.state .transfer t) +abbrev FailedAt (r : Recorded BankAggregates) (t : TransferId) : Prop := + FailedState (r.state .transfer t) +abbrev EndedAt (r : Recorded BankAggregates) (t : TransferId) : Prop := EndedState (r.state .transfer t) + +theorem FailedState.past {s : TransferState} (h : FailedState s) : PastState s := by + cases s <;> simp_all [FailedState, PastState] + +theorem FailedState.ended {s : TransferState} (h : FailedState s) : EndedState s := by + cases s <;> simp_all [FailedState, EndedState] + +/-! ## What one command does to a transfer -/ + +/-- A transfer only moves forward. -/ +theorem transfer_forward {ctx : Context Actor} {s : TransferState} {c : TransferCommand} + {es : List TransferEvent} (h : decideTransfer ctx s c = .ok es) : + (PastState s → PastState (Transfer.apply s es ctx.now)) ∧ + (FailedState s → FailedState (Transfer.apply s es ctx.now)) ∧ + (EndedState s → EndedState (Transfer.apply s es ctx.now)) ∧ + (s ≠ .new → Transfer.apply s es ctx.now ≠ .new) := by + cases s <;> cases c <;> simp only [decideTransfer] at h <;> (repeat' split at h) <;> + (try cases h) <;> + simp_all [Aggregate.apply, evolveTransfer, PastState, FailedState, EndedState] + +/-- What the events a command records say about where the transfer is after them. -/ +theorem transfer_events {ctx : Context Actor} {s : TransferState} {c : TransferCommand} + {es : List TransferEvent} (h : decideTransfer ctx s c = .ok es) : + (∀ d, .transferRequested d false ∈ es → PastState (Transfer.apply s es ctx.now)) ∧ + (∀ d actor, .transferApproved d actor ∈ es → PastState (Transfer.apply s es ctx.now)) ∧ + (∀ reason, .transferFailed reason ∈ es → FailedState (Transfer.apply s es ctx.now)) ∧ + (Transfer.apply s es ctx.now ≠ .new → s ≠ .new ∨ ∃ d n, .transferRequested d n ∈ es) := by + cases s <;> cases c <;> simp only [decideTransfer] at h <;> (repeat' split at h) <;> + (try cases h) <;> + simp_all [Aggregate.apply, evolveTransfer, PastState, FailedState] <;> + (try (intro small; simp [Nat.not_le.mpr small])) + +/-- Completing a transfer that is past its request ends it. -/ +theorem complete_ends {ctx : Context Actor} {s : TransferState} (c : CompleteTransfer) + (past : PastState s) : EndedState (Transfer.step ctx s (.complete c)) := by + cases s <;> simp_all [Aggregate.step, decideTransfer, Aggregate.apply, evolveTransfer, PastState, + EndedState] + +/-- Failing a transfer that is past its request ends it. -/ +theorem fail_ends {ctx : Context Actor} {s : TransferState} (c : FailTransfer) + (past : PastState s) : EndedState (Transfer.step ctx s (.fail c)) := by + cases s <;> simp_all [Aggregate.step, decideTransfer, Aggregate.apply, evolveTransfer, PastState, + EndedState] + +/-! ## What the log says about a transfer -/ + +/-- The entry records a request for this transfer. -/ +def isRequest (t : TransferId) (d : TransferDetails) (n : Bool) (e : Emitted BankAggregates) : Prop := + ∃ seq time, e = ⟨.transfer, t, .transferRequested d n, seq, time⟩ + +def isApproved (t : TransferId) (e : Emitted BankAggregates) : Prop := + ∃ d actor seq time, e = ⟨.transfer, t, .transferApproved d actor, seq, time⟩ + +def isFailed (t : TransferId) (e : Emitted BankAggregates) : Prop := + ∃ reason seq time, e = ⟨.transfer, t, .transferFailed reason, seq, time⟩ + +/-- What the log and the transfers' states always say about each other. -/ +structure Facts (r : Recorded BankAggregates) : Prop where + /-- A small transfer is past its request as soon as it is asked for. -/ + requested : ∀ e, e ∈ r.log → ∀ t d, isRequest t d false e → PastAt r t + approved : ∀ e, e ∈ r.log → ∀ t, isApproved t e → PastAt r t + failed : ∀ e, e ∈ r.log → ∀ t, isFailed t e → FailedAt r t + /-- A transfer that is not new was asked for. -/ + known : ∀ t, r.state .transfer t ≠ .new → ∃ e, e ∈ r.log ∧ ∃ d n, isRequest t d n e + +/-- A command to a transfer, as a send. -/ +abbrev transferSend (actor : Actor) (command : TransferCommand) : Send BankAggregates := + ⟨.transfer, actor, command⟩ + +/-- A command to a transfer changes nothing, or records what the transfer decided. -/ +theorem transfer_dispatch (r : Recorded BankAggregates) (now : Time) (actor : Actor) + (c : TransferCommand) : + r.dispatch now (transferSend actor c) = r ∨ + ∃ es, decideTransfer ⟨actor, now⟩ (r.state .transfer (Transfer.keyOf c)) c = .ok es ∧ + r.dispatch now (transferSend actor c) = r.record now .transfer (Transfer.keyOf c) es := + Recorded.dispatch_cases r now (transferSend actor c) + +/-- No command moves a transfer backward, whichever instance it is sent to. -/ +theorem dispatch_forward (r : Recorded BankAggregates) (now : Time) (s : Send BankAggregates) + (t : TransferId) : + (PastAt r t → PastAt (r.dispatch now s) t) ∧ (FailedAt r t → FailedAt (r.dispatch now s) t) ∧ + (EndedAt r t → EndedAt (r.dispatch now s) t) ∧ + (r.state .transfer t ≠ .new → (r.dispatch now s).state .transfer t ≠ .new) := by + obtain ⟨to, actor, c⟩ := s + cases to with + | customer => cases c + | usernameClaim => cases c + | account => + have same := Recorded.dispatch_state_of_ne_name r now ⟨.account, actor, c⟩ .transfer t (by simp) + simp only [PastAt, FailedAt, EndedAt, same] + exact ⟨id, id, id, id⟩ + | transfer => + rcases transfer_dispatch r now actor c with same | ⟨es, decided, recorded⟩ + · simp only [PastAt, FailedAt, EndedAt, transferSend] at same ⊢ + rw [same] + exact ⟨id, id, id, id⟩ + · simp only [PastAt, FailedAt, EndedAt, transferSend] at recorded ⊢ + rw [recorded] + by_cases here : Transfer.keyOf c = t + · subst here + rw [Recorded.record_state_self] + exact transfer_forward decided + · rw [Recorded.record_state_of_ne _ _ _ _ _ _ here] + exact ⟨id, id, id, id⟩ + +/-- A log entry of another aggregate says nothing about a transfer. -/ +theorem not_transfer_entry {n : BankAggregate} (ne : n ≠ .transfer) {id : (BankAggregates.of n).Id} + {x : (BankAggregates.of n).Event} {seq : Nat} {time : Time} (t : TransferId) : + (∀ d k, ¬ isRequest t d k ⟨n, id, x, seq, time⟩) ∧ ¬ isApproved t ⟨n, id, x, seq, time⟩ ∧ + ¬ isFailed t ⟨n, id, x, seq, time⟩ := by + refine ⟨?_, ?_, ?_⟩ + · rintro d k ⟨_, _, eq⟩; cases eq; exact ne rfl + · rintro ⟨_, _, _, _, eq⟩; cases eq; exact ne rfl + · rintro ⟨_, _, _, eq⟩; cases eq; exact ne rfl + +/-- Recording on another aggregate keeps what the log says about transfers. -/ +theorem facts_record_other {r : Recorded BankAggregates} (h : Facts r) (time : Time) + (n : BankAggregate) (ne : n ≠ .transfer) (id : (BankAggregates.of n).Id) + (es : List (BankAggregates.of n).Event) : Facts (r.record time n id es) := by + have same : ∀ t, (r.record time n id es).state .transfer t = r.state .transfer t := + fun t => Recorded.record_state_of_ne_name r time n .transfer id t es ne + refine ⟨?_, ?_, ?_, ?_⟩ + · intro e mem t d req + rcases Recorded.mem_record_log mem with old | ⟨x, _, seq, rfl⟩ + · simpa [PastAt, same] using h.requested e old t d req + · exact absurd req ((not_transfer_entry ne t).1 d false) + · intro e mem t app + rcases Recorded.mem_record_log mem with old | ⟨x, _, seq, rfl⟩ + · simpa [PastAt, same] using h.approved e old t app + · exact absurd app (not_transfer_entry ne t).2.1 + · intro e mem t failed + rcases Recorded.mem_record_log mem with old | ⟨x, _, seq, rfl⟩ + · simpa [FailedAt, same] using h.failed e old t failed + · exact absurd failed (not_transfer_entry ne t).2.2 + · intro t notNew + rw [same] at notNew + obtain ⟨e, mem, d, n', req⟩ := h.known t notNew + exact ⟨e, by simp [Recorded.record, mem], d, n', req⟩ + +/-- Every command keeps what the log says about transfers. -/ +theorem facts_dispatch {r : Recorded BankAggregates} (h : Facts r) (now : Time) + (s : Send BankAggregates) : Facts (r.dispatch now s) := by + obtain ⟨to, actor, c⟩ := s + cases to with + | customer => cases c + | usernameClaim => cases c + | account => + rcases Recorded.dispatch_cases r now ⟨.account, actor, c⟩ with same | ⟨es, _, recorded⟩ + · rw [same]; exact h + · rw [recorded]; exact facts_record_other h now .account (by decide) _ es + | transfer => + rcases transfer_dispatch r now actor c with same | ⟨es, decided, recorded⟩ + · simp only [transferSend] at same; rw [same]; exact h + · simp only [transferSend] at recorded + rw [recorded] + have forward : ∀ t, (PastAt r t → PastAt (r.record now .transfer (Transfer.keyOf c) es) t) ∧ + (FailedAt r t → FailedAt (r.record now .transfer (Transfer.keyOf c) es) t) := by + intro t + have all := dispatch_forward r now (transferSend actor c) t + simp only [transferSend, recorded] at all + exact ⟨all.1, all.2.1⟩ + refine ⟨?_, ?_, ?_, ?_⟩ + · intro e mem t d req + rcases Recorded.mem_record_log mem with old | ⟨x, xmem, seq, rfl⟩ + · exact (forward t).1 (h.requested e old t d req) + · obtain ⟨_, _, eq⟩ := req + cases eq + show PastState _ + rw [Recorded.record_state_self] + exact (transfer_events decided).1 d xmem + · intro e mem t app + rcases Recorded.mem_record_log mem with old | ⟨x, xmem, seq, rfl⟩ + · exact (forward t).1 (h.approved e old t app) + · obtain ⟨d, by_, _, _, eq⟩ := app + cases eq + show PastState _ + rw [Recorded.record_state_self] + exact (transfer_events decided).2.1 d by_ xmem + · intro e mem t failed + rcases Recorded.mem_record_log mem with old | ⟨x, xmem, seq, rfl⟩ + · exact (forward t).2 (h.failed e old t failed) + · obtain ⟨reason, _, _, eq⟩ := failed + cases eq + show FailedState _ + rw [Recorded.record_state_self] + exact (transfer_events decided).2.2.1 reason xmem + · intro t notNew + by_cases here : Transfer.keyOf c = t + · subst here + rw [Recorded.record_state_self] at notNew + rcases (transfer_events decided).2.2.2 notNew with was | ⟨d, n, xmem⟩ + · obtain ⟨e, mem, d, n, req⟩ := h.known _ was + exact ⟨e, by simp [Recorded.record, mem], d, n, req⟩ + · obtain ⟨seq, mem⟩ := Recorded.mem_log_of_recorded r now .transfer (Transfer.keyOf c) es xmem + exact ⟨_, List.mem_of_mem_drop mem, d, n, seq, now, rfl⟩ + · rw [Recorded.record_state_of_ne _ _ _ _ _ _ here] at notNew + obtain ⟨e, mem, d, n, req⟩ := h.known t notNew + exact ⟨e, by simp [Recorded.record, mem], d, n, req⟩ + +/-- A registration keeps what the log says about transfers. -/ +theorem facts_decide {r : Recorded BankAggregates} (h : Facts r) (ctx : Context Actor) + (c : RegisterCustomer) : Facts (r.decide Registration ctx c) := by + cases eq : decideRegistration ctx r.state c with + | error _ => simpa [Recorded.decide, Registration, eq] using h + | ok rs => + obtain ⟨_, _, records⟩ := registration_accepted eq + subst records + simp only [Recorded.decide, Registration, eq, Recorded.records, List.foldl] + exact facts_record_other (facts_record_other h _ .customer (by decide) _ _) _ .usernameClaim + (by decide) _ _ + +theorem facts_start : Facts (.start BankAggregates) where + requested := fun _ mem => nomatch mem + approved := fun _ mem => nomatch mem + failed := fun _ mem => nomatch mem + known := fun _ notNew => absurd rfl notNew + +/-! ## Policies whose starts and signals the log backs -/ + +/-- +A policy's reaction that starts a small transfer's saga only once the transfer +is past its request, signals an approval only once it is approved, and signals +an expiry only once it has failed. +-/ +inductive Sound (r : Recorded BankAggregates) : Program BankSignature Unit → Prop where + | pure : Sound r (.pure ()) + | send (s k) : (∀ answer, Sound r (k answer)) → Sound r (.send s k) + | call (c k) : (∀ reply, Sound r (k reply)) → Sound r (.call c k) + | start (t input k) : (input.needsApproval = false → PastAt r t) → Sound r k → + Sound r (.start t input k) + | signal (t sig k) : (sig = .approved → PastAt r t) → (sig = .expired → FailedAt r t) → + Sound r k → Sound r (.signal t sig k) + | schedule (after s k) : Sound r k → Sound r (.schedule after s k) + +/-- Transfers only move forward from `r` to `r'`. -/ +def Forward (r r' : Recorded BankAggregates) : Prop := + ∀ t, (PastAt r t → PastAt r' t) ∧ (FailedAt r t → FailedAt r' t) ∧ (EndedAt r t → EndedAt r' t) + +theorem Forward.refl (r : Recorded BankAggregates) : Forward r r := fun _ => ⟨id, id, id⟩ + +theorem forward_dispatch (r : Recorded BankAggregates) (now : Time) (s : Send BankAggregates) : + Forward r (r.dispatch now s) := fun t => + let all := dispatch_forward r now s t + ⟨all.1, all.2.1, all.2.2.1⟩ + +theorem Sound.forward {r r' : Recorded BankAggregates} {p : Program BankSignature Unit} + (forward : Forward r r') (h : Sound r p) : Sound r' p := by + induction h with + | pure => exact .pure + | send s k _ ih => exact .send s k ih + | call c k _ ih => exact .call c k ih + | start t input k past _ ih => exact .start t input k (fun eq => (forward t).1 (past eq)) ih + | signal t sig k past failed _ ih => + exact .signal t sig k (fun eq => (forward t).1 (past eq)) (fun eq => (forward t).2.1 (failed eq)) ih + | schedule after s k _ ih => exact .schedule after s k ih + +theorem Sound.bind {r : Recorded BankAggregates} {p : Program BankSignature Unit} + {f : Unit → Program BankSignature Unit} (hp : Sound r p) (hf : Sound r (f ())) : + Sound r (p.bind f) := by + induction hp with + | pure => exact hf + | send s k _ ih => exact .send s _ ih + | call c k _ ih => exact .call c _ ih + | start t input k past _ ih => exact .start t input _ past ih + | signal t sig k past failed _ ih => exact .signal t sig _ past failed ih + | schedule after s k _ ih => exact .schedule after s _ ih + +/-- Every policy's reaction to an event in the log is sound. -/ +theorem policies_sound {r : Recorded BankAggregates} (facts : Facts r) + (p : Policy BankSignature) (mem : p ∈ Bank.policies) + (history : List (Emitted BankAggregates)) (e : Emitted BankAggregates) (logged : e ∈ r.log) : + Sound r (p.react history e) := by + simp only [Bank, List.mem_cons, List.mem_nil_iff, or_false] at mem + obtain ⟨source, id, event, seq, time⟩ := e + rcases mem with rfl | rfl | rfl | rfl | rfl + · cases source <;> simp only [MainAccountProvisioning, Policy.on] <;> (try exact .pure) + cases event + exact .send _ _ fun _ => .pure + · cases source <;> simp only [TransferExecution, Policy.on] <;> (try exact .pure) + cases event with + | transferRequested details needsApproval => + refine .start _ _ _ (fun small => ?_) .pure + have small' : needsApproval = false := small + subst small' + exact facts.requested _ logged id details ⟨seq, time, rfl⟩ + | transferApproved details actor => + exact .signal _ _ _ (fun _ => facts.approved _ logged id ⟨details, actor, seq, time, rfl⟩) + (fun eq => nomatch eq) .pure + | transferCompleted => exact .pure + | transferFailed reason => + exact .signal _ _ _ (fun eq => nomatch eq) + (fun _ => facts.failed _ logged id ⟨reason, seq, time, rfl⟩) .pure + · cases source <;> simp only [TransferApprovalDeadline, Policy.on] <;> (try exact .pure) + cases event <;> (try exact .pure) + rename_i details needsApproval + cases needsApproval + · exact .pure + · exact .schedule _ _ _ .pure + · simp only [FraudReview, Policy.onView] + generalize DailyOutflow.emittedBy history _ = emitted + induction emitted with + | nil => exact .pure + | cons x rest ih => + refine Sound.bind ?_ ih + refine .call _ _ fun score => ?_ + show Sound r (if score.risk > 80 then _ else _) + split + · exact .send _ _ fun _ => .pure + · exact .pure + · cases source <;> simp only [SettlementRefund, Policy.on] <;> (try exact .pure) + cases event <;> (try exact .pure) + exact .call _ _ fun _ => .pure + +/-! ## Where a saga's run may stand -/ + +def Stage.id : Stage → TransferId + | .begin id _ | .gate id _ | .debit id _ | .debited id _ | .credit id _ | .completing id _ + | .finished id _ | .refunding id _ _ | .failing id _ | .failed id _ => id + +theorem Stage.owner (stage : Stage) : stage.fiber.owner = some stage.id := by + cases stage <;> rfl + +/-- What has to be true of the transfer for a run to stand at a stage. -/ +def StageOk (r : Recorded BankAggregates) : Stage → Prop + | .begin t input | .gate t input => input.needsApproval = false → PastAt r t + | .debit t _ | .debited t _ | .credit t _ | .completing t _ | .refunding t _ _ | .failing t _ => + PastAt r t + | .finished t _ | .failed t _ => EndedAt r t + +theorem StageOk.forward {r r' : Recorded BankAggregates} {stage : Stage} (forward : Forward r r') + (h : StageOk r stage) : StageOk r' stage := by + cases stage <;> simp only [StageOk] at h ⊢ <;> + first + | exact fun small => (forward _).1 (h small) + | exact (forward _).1 h + | exact (forward _).2.2 h + +/-- A fiber the bank can have: a saga's run at a stage it may stand at, or a sound reaction. -/ +def Good (r : Recorded BankAggregates) (f : Fiber BankSignature) : Prop := + (∃ stage, f = stage.fiber ∧ StageOk r stage) ∨ (∃ p, f = ⟨none, p, []⟩ ∧ Sound r p) + +theorem Good.forward {r r' : Recorded BankAggregates} {f : Fiber BankSignature} + (forward : Forward r r') (h : Good r f) : Good r' f := by + rcases h with ⟨stage, eq, ok⟩ | ⟨p, eq, sound⟩ + · exact .inl ⟨stage, eq, ok.forward forward⟩ + · exact .inr ⟨p, eq, sound.forward forward⟩ + +/-! ## What always holds of the bank -/ + +/-- A fiber that is about to start a saga's run, and nothing else. -/ +abbrev starter (t : TransferId) (input : ExecuteTransferInput) : Fiber BankSignature := + ⟨none, .start t input (.pure ()), []⟩ + +/-- The log has a request for this transfer. -/ +def WasAsked (log : List (Emitted BankAggregates)) (t : TransferId) : Prop := + ∃ e, e ∈ log ∧ ∃ d n, isRequest t d n e + +structure Tidy (w : World BankSignature) : Prop where + facts : Facts w.toRecorded + /-- Every undelivered event is in the log. -/ + inbox : ∀ e, e ∈ w.inbox → e ∈ w.log + good : ∀ f, f ∈ w.fibers → Good w.toRecorded f + /-- A signal a run has not taken yet is backed by where its transfer is. -/ + signals : ∀ t, (Approval.approved ∈ w.signals t → PastAt w.toRecorded t) ∧ + (Approval.expired ∈ w.signals t → FailedAt w.toRecorded t) + /-- A transfer that was asked for has its saga started, or about to be. -/ + coming : ∀ t, WasAsked w.log t → + WasAsked w.inbox t ∨ (∃ input, starter t input ∈ w.fibers) ∨ w.sagas t ≠ .notStarted + /-- A run that is running has a fiber. -/ + running : ∀ t, w.sagas t = .running → ∃ stage : Stage, stage.fiber ∈ w.fibers ∧ stage.id = t + /-- A run that ended left its transfer ended. -/ + ended : ∀ t, (w.sagas t = .completed ∨ ∃ x, w.sagas t = .failed x) → EndedAt w.toRecorded t + +/-- +Taking on a new record keeps the bank tidy, when the facts hold of it, the +transfers only moved forward, and the log only grew. +-/ +theorem tidy_lift {w : World BankSignature} (h : Tidy w) (r : Recorded BankAggregates) + (facts : Facts r) (forward : Forward w.toRecorded r) + (grew : ∃ more, r.log = w.log ++ more) : Tidy (w.lift r) := by + obtain ⟨more, grew⟩ := grew + have inbox : (w.lift r).inbox = w.inbox ++ more := by simp [World.lift, grew] + refine ⟨facts, ?_, ?_, ?_, ?_, ?_, ?_⟩ + · intro e mem + rw [inbox] at mem + show e ∈ r.log + rw [grew] + rcases List.mem_append.mp mem with old | new + · exact List.mem_append_left _ (h.inbox e old) + · exact List.mem_append_right _ new + · intro f mem + exact (h.good f mem).forward forward + · intro t + exact ⟨fun mem => (forward t).1 ((h.signals t).1 mem), fun mem => (forward t).2.1 ((h.signals t).2 mem)⟩ + · intro t asked + obtain ⟨e, mem, req⟩ := asked + have mem' : e ∈ w.log ++ more := grew ▸ mem + rcases List.mem_append.mp mem' with old | new + · rcases h.coming t ⟨e, old, req⟩ with ⟨e', mem'', req'⟩ | fiber | started + · exact .inl ⟨e', by rw [inbox]; exact List.mem_append_left _ mem'', req'⟩ + · exact .inr (.inl fiber) + · exact .inr (.inr started) + · exact .inl ⟨e, by rw [inbox]; exact List.mem_append_right _ new, req⟩ + · exact h.running + · intro t done + exact (forward t).2.2 (h.ended t done) + +theorem dispatch_log (r : Recorded BankAggregates) (now : Time) (s : Send BankAggregates) : + ∃ more, (r.dispatch now s).log = r.log ++ more := by + rcases Recorded.dispatch_cases r now s with same | ⟨es, _, recorded⟩ + · exact ⟨[], by simp [same]⟩ + · exact ⟨_, by rw [recorded]; rfl⟩ + +/-- Sending a command keeps the bank tidy. -/ +theorem tidy_dispatch {w : World BankSignature} (h : Tidy w) (s : Send BankAggregates) : + Tidy (w.dispatch s) := + tidy_lift h _ (facts_dispatch h.facts w.now s) (forward_dispatch w.toRecorded w.now s) + (dispatch_log w.toRecorded w.now s) + +/-- Recording keeps what was in the log. -/ +theorem records_log (r : Recorded BankAggregates) (time : Time) (rs : List (Record BankAggregates)) : + ∃ more, (r.records time rs).log = r.log ++ more := by + unfold Recorded.records + induction rs generalizing r with + | nil => exact ⟨[], by simp⟩ + | cons x rs ih => + obtain ⟨more, eq⟩ := ih (r.record time x.to x.id [x.event]) + exact ⟨_, by rw [List.foldl_cons, eq]; simp only [Recorded.record, List.append_assoc]; rfl⟩ + +/-- A registration keeps the bank tidy. -/ +theorem tidy_decide {w : World BankSignature} (h : Tidy w) (actor : Actor) (c : RegisterCustomer) : + Tidy (w.decide Registration actor c) := by + refine tidy_lift h _ (facts_decide h.facts ⟨actor, w.now⟩ c) ?_ ?_ + · intro t + have same : (w.toRecorded.decide Registration ⟨actor, w.now⟩ c).state .transfer t + = w.state .transfer t := by + cases eq : decideRegistration ⟨actor, w.now⟩ w.state c with + | error _ => simp [Recorded.decide, Registration, eq] + | ok rs => exact (registration_states w.toRecorded ⟨actor, w.now⟩ c rs eq).2.2.2 t + simp only [PastAt, FailedAt, EndedAt, same] + exact ⟨id, id, id⟩ + · cases eq : decideRegistration ⟨actor, w.now⟩ w.state c with + | error _ => exact ⟨[], by simp [Recorded.decide, Registration, eq]⟩ + | ok rs => + obtain ⟨more, grew⟩ := records_log w.toRecorded w.now rs + exact ⟨more, by simpa [Recorded.decide, Registration, eq] using grew⟩ + +/-! ## Replacing one fiber -/ + +theorem stage_not_starter (stage : Stage) (t : TransferId) (input : ExecuteTransferInput) : + stage.fiber ≠ starter t input := by + intro eq + have owner := congrArg Fiber.owner eq + rw [Stage.owner] at owner + cases owner + +theorem same_run {stage stage' : Stage} (eq : stage.fiber = stage'.fiber) : stage.id = stage'.id := by + have owner := congrArg Fiber.owner eq + rw [Stage.owner, Stage.owner] at owner + exact Option.some.inj owner + +theorem mem_swap {α : Type} {before after fs : List α} {f g : α} + (mem : g ∈ before ++ f :: after) : g = f ∨ g ∈ before ++ fs ++ after := by + simp only [List.mem_append, List.mem_cons] at mem ⊢ + rcases mem with b | rfl | a + · exact .inr (.inl (.inl b)) + · exact .inl rfl + · exact .inr (.inr a) + +/-- +The bank stays tidy when one fiber is replaced by others, with the record and +the inbox as they were, provided the new fibers, signals and saga statuses keep +each promise the old ones made. +-/ +theorem tidy_swap {w w' : World BankSignature} (h : Tidy w) + {before after fs : List (Fiber BankSignature)} {f : Fiber BankSignature} + (fibers : w.fibers = before ++ f :: after) + (record : w'.toRecorded = w.toRecorded) (inbox : w'.inbox = w.inbox) + (fibers' : w'.fibers = before ++ fs ++ after) + (good : ∀ g, g ∈ fs → Good w.toRecorded g) + (signals : ∀ t, (Approval.approved ∈ w'.signals t → PastAt w.toRecorded t) ∧ + (Approval.expired ∈ w'.signals t → FailedAt w.toRecorded t)) + (started : ∀ t input, f = starter t input → w'.sagas t ≠ .notStarted) + (kept : ∀ t, w.sagas t ≠ .notStarted → w'.sagas t ≠ .notStarted) + (running : ∀ t, w'.sagas t = .running → + (∃ stage : Stage, stage.fiber ∈ fs ∧ stage.id = t) ∨ + (w.sagas t = .running ∧ ∀ stage : Stage, f = stage.fiber → stage.id ≠ t)) + (ended : ∀ t, (w'.sagas t = .completed ∨ ∃ x, w'.sagas t = .failed x) → + EndedAt w.toRecorded t ∨ (w.sagas t = .completed ∨ ∃ x, w.sagas t = .failed x)) : + Tidy w' := by + refine ⟨record ▸ h.facts, ?_, ?_, ?_, ?_, ?_, ?_⟩ + · intro e mem + rw [inbox] at mem + show e ∈ w'.toRecorded.log + rw [record] + exact h.inbox e mem + · intro g mem + rw [fibers'] at mem + rw [record] + simp only [List.mem_append] at mem + rcases mem with (b | m) | a + · exact h.good g (by rw [fibers]; simp [b]) + · exact good g m + · exact h.good g (by rw [fibers]; simp [a]) + · intro t + rw [record] + exact signals t + · intro t asked + have asked' : WasAsked w.log t := by + have : w'.log = w.log := congrArg Recorded.log record + rw [← this]; exact asked + rcases h.coming t asked' with inboxed | ⟨input, mem⟩ | begun + · exact .inl (inbox ▸ inboxed) + · rw [fibers] at mem + rcases mem_swap (fs := fs) mem with same | still + · exact .inr (.inr (started t input same.symm)) + · exact .inr (.inl ⟨input, fibers' ▸ still⟩) + · exact .inr (.inr (kept t begun)) + · intro t run + rcases running t run with ⟨stage, mem, id⟩ | ⟨old, other⟩ + · exact ⟨stage, by rw [fibers']; simp [mem], id⟩ + · obtain ⟨stage, mem, id⟩ := h.running t old + rw [fibers] at mem + rcases mem_swap (fs := fs) mem with same | still + · exact absurd id (other stage same.symm) + · exact ⟨stage, fibers' ▸ still, id⟩ + · intro t done + rw [record] + rcases ended t done with now | old + · exact now + · exact h.ended t old + +/-- A saga's run moves to its next stage. -/ +theorem tidy_next {w w' : World BankSignature} (h : Tidy w) + {before after : List (Fiber BankSignature)} {f : Fiber BankSignature} + (fibers : w.fibers = before ++ f :: after) (stage stage' : Stage) (at_ : f = stage.fiber) + (same : stage'.id = stage.id) (ok : StageOk w.toRecorded stage') + (record : w'.toRecorded = w.toRecorded) (inbox : w'.inbox = w.inbox) + (fibers' : w'.fibers = before ++ [stage'.fiber] ++ after) + (sagas : w'.sagas = w.sagas) + (signals : ∀ t, (Approval.approved ∈ w'.signals t → PastAt w.toRecorded t) ∧ + (Approval.expired ∈ w'.signals t → FailedAt w.toRecorded t)) : Tidy w' := by + refine tidy_swap h fibers record inbox fibers' ?_ ?_ ?_ ?_ ?_ ?_ + · intro g mem + simp only [List.mem_singleton] at mem + exact .inl ⟨stage', mem, ok⟩ + · exact signals + · intro t input eq + exact absurd (at_ ▸ eq) (stage_not_starter stage t input) + · intro t; rw [sagas]; exact id + · intro t run + rw [sagas] at run + by_cases here : stage.id = t + · exact .inl ⟨stage', by simp, same.trans here⟩ + · exact .inr ⟨run, fun other eq => fun id => here ((same_run (at_ ▸ eq)).trans id)⟩ + · intro t done + rw [sagas] at done + exact .inr done + +/-! ## Each kind of step -/ + +/-- Where a transfer is after a command to it. -/ +theorem transfer_state_after (r : Recorded BankAggregates) (now : Time) (actor : Actor) + (c : TransferCommand) : + (r.dispatch now (transferSend actor c)).state .transfer (Transfer.keyOf c) + = Transfer.step ⟨actor, now⟩ (r.state .transfer (Transfer.keyOf c)) c := by + have outcome : r.outcome now (transferSend actor c) + = decideTransfer ⟨actor, now⟩ (r.state .transfer (Transfer.keyOf c)) c := rfl + have decide : Transfer.decide ⟨actor, now⟩ (r.state .transfer (Transfer.keyOf c)) c + = decideTransfer ⟨actor, now⟩ (r.state .transfer (Transfer.keyOf c)) c := rfl + unfold Recorded.dispatch Aggregate.step + rw [outcome, decide] + cases decideTransfer ⟨actor, now⟩ (r.state .transfer (Transfer.keyOf c)) c with + | ok es => exact Recorded.record_state_self r now .transfer (Transfer.keyOf c) es + | error e => rfl + +/-- The policies' reactions to an event in the log keep the bank tidy. -/ +theorem tidy_react {w : World BankSignature} (h : Tidy w) (e : Emitted BankAggregates) + (logged : e ∈ w.log) : Tidy (Bank.react w e) := by + refine ⟨h.facts, h.inbox, ?_, h.signals, ?_, ?_, h.ended⟩ + · intro f mem + simp only [Model.react, List.mem_append, List.mem_map] at mem + rcases mem with old | ⟨p, pmem, rfl⟩ + · exact h.good f old + · exact .inr ⟨_, rfl, policies_sound h.facts p pmem _ e logged⟩ + · intro t asked + rcases h.coming t asked with inboxed | ⟨input, mem⟩ | begun + · exact .inl inboxed + · exact .inr (.inl ⟨input, by simp [Model.react, mem]⟩) + · exact .inr (.inr begun) + · intro t run + obtain ⟨stage, mem, id⟩ := h.running t run + exact ⟨stage, by simp [Model.react, mem], id⟩ + +/-- What TransferExecution does about a request: it starts the saga's run. -/ +theorem execution_starts (history : List (Emitted BankAggregates)) (t : TransferId) + (d : TransferDetails) (n : Bool) (seq : Nat) (time : Time) : + ({ owner := none + program := TransferExecution.react history ⟨.transfer, t, .transferRequested d n, seq, time⟩ + undo := [] } : Fiber BankSignature) = starter t ⟨d, n⟩ := by + simp [TransferExecution, Policy.on, Program.startSaga, starter] + +/-- Delivering an undelivered event keeps the bank tidy. -/ +theorem tidy_deliver {w : World BankSignature} (h : Tidy w) (e : Emitted BankAggregates) + (before after : List (Emitted BankAggregates)) (inbox : w.inbox = before ++ e :: after) : + Tidy (Bank.react { w with inbox := before ++ after } e) := by + have logged : e ∈ w.log := h.inbox e (by rw [inbox]; simp) + refine ⟨h.facts, ?_, ?_, h.signals, ?_, ?_, h.ended⟩ + · intro x mem + exact h.inbox x (by + have : x ∈ before ++ after := mem + rw [inbox]; simp only [List.mem_append, List.mem_cons] at this ⊢ + rcases this with b | a + · exact .inl b + · exact .inr (.inr a)) + · intro f mem + simp only [Model.react, List.mem_append, List.mem_map] at mem + rcases mem with old | ⟨p, pmem, rfl⟩ + · exact h.good f old + · exact .inr ⟨_, rfl, policies_sound h.facts p pmem _ e logged⟩ + · intro t asked + rcases h.coming t asked with ⟨x, mem, d, n, req⟩ | ⟨input, mem⟩ | begun + · rw [inbox] at mem + rcases mem_swap (fs := []) mem with same | still + · subst same + obtain ⟨seq, time, rfl⟩ := req + refine .inr (.inl ⟨⟨d, n⟩, ?_⟩) + simp only [Model.react, List.mem_append, List.mem_map] + exact .inr ⟨TransferExecution, by simp, execution_starts _ t d n seq time⟩ + · exact .inl ⟨x, (show x ∈ before ++ after from by simpa using still), d, n, req⟩ + · exact .inr (.inl ⟨input, by simp [Model.react, mem]⟩) + · exact .inr (.inr begun) + · intro t run + obtain ⟨stage, mem, id⟩ := h.running t run + exact ⟨stage, by simp [Model.react, mem], id⟩ + +/-- A change that touches nothing the invariant reads. -/ +theorem tidy_same {w w' : World BankSignature} (h : Tidy w) (record : w'.toRecorded = w.toRecorded) + (inbox : w'.inbox = w.inbox) (fibers : w'.fibers = w.fibers) (sagas : w'.sagas = w.sagas) + (signals : w'.signals = w.signals) : Tidy w' := by + refine ⟨record ▸ h.facts, ?_, ?_, ?_, ?_, ?_, ?_⟩ + · intro e mem; rw [inbox] at mem; show e ∈ w'.toRecorded.log; rw [record]; exact h.inbox e mem + · intro f mem; rw [fibers] at mem; rw [record]; exact h.good f mem + · intro t; rw [record, signals]; exact h.signals t + · intro t asked + have : w'.log = w.log := congrArg Recorded.log record + rw [this] at asked + rw [inbox, fibers, sagas] + exact h.coming t asked + · intro t run; rw [sagas] at run; rw [fibers]; exact h.running t run + · intro t done; rw [sagas] at done; rw [record]; exact h.ended t done + +theorem policy_not_stage (p : Program BankSignature Unit) (stage : Stage) : + ({ owner := none, program := p, undo := [] } : Fiber BankSignature) ≠ stage.fiber := by + intro eq + have owner := congrArg Fiber.owner eq + rw [Stage.owner] at owner + cases owner + +/-- A saga's run moves to its next stage after sending a command. -/ +theorem tidy_next_after {w : World BankSignature} (h : Tidy w) (s : Send BankAggregates) + {before after : List (Fiber BankSignature)} {f : Fiber BankSignature} + (fibers : w.fibers = before ++ f :: after) (stage stage' : Stage) (at_ : f = stage.fiber) + (same : stage'.id = stage.id) (ok : StageOk (w.toRecorded.dispatch w.now s) stage') : + Tidy { w.dispatch s with fibers := before ++ [stage'.fiber] ++ after } := + tidy_next (tidy_dispatch h s) (w := w.dispatch s) fibers stage stage' at_ same ok rfl rfl rfl rfl + (tidy_dispatch h s).signals + +/-- A saga's run ends, with its transfer ended. -/ +theorem tidy_finish {w : World BankSignature} (h : Tidy w) + {before after : List (Fiber BankSignature)} {f : Fiber BankSignature} + (fibers : w.fibers = before ++ f :: after) (stage : Stage) (at_ : f = stage.fiber) + (ended : EndedAt w.toRecorded stage.id) (status : SagaStatus BankSignature) + (isEnd : status = .completed ∨ ∃ x, status = .failed x) : + Tidy { w.finish (some stage.id) status with fibers := before ++ [] ++ after } := by + have notStart : status ≠ .notStarted := by rcases isEnd with rfl | ⟨x, rfl⟩ <;> simp + have notRunning : status ≠ .running := by rcases isEnd with rfl | ⟨x, rfl⟩ <;> simp + refine tidy_swap h fibers rfl rfl rfl ?_ ?_ ?_ ?_ ?_ ?_ + · intro g mem; cases mem + · exact h.signals + · intro t input eq + exact absurd (at_ ▸ eq) (stage_not_starter stage t input) + · intro t begun + show update w.sagas stage.id status t ≠ .notStarted + unfold update + split + · exact notStart + · exact begun + · intro t run + have run' : update w.sagas stage.id status t = .running := run + unfold update at run' + split at run' + · exact absurd run' notRunning + · next ne => exact .inr ⟨run', fun other eq id => ne (id ▸ (same_run (at_ ▸ eq)).symm ▸ rfl)⟩ + · intro t done + have done' : update w.sagas stage.id status t = .completed ∨ + ∃ x, update w.sagas stage.id status t = .failed x := done + unfold update at done' + split at done' + · next here => exact .inl (here ▸ ended) + · exact .inr done' + +/-- A policy's reaction takes a step that leaves the sagas and signals alone. -/ +theorem tidy_policy {w w' : World BankSignature} (h : Tidy w) + {before after : List (Fiber BankSignature)} {p p' : Program BankSignature Unit} + (fibers : w.fibers = before ++ ⟨none, p, []⟩ :: after) + (notStart : ∀ t input, p ≠ .start t input (.pure ())) + (sound : Sound w.toRecorded p') + (record : w'.toRecorded = w.toRecorded) (inbox : w'.inbox = w.inbox) + (fibers' : w'.fibers = before ++ [⟨none, p', []⟩] ++ after) + (sagas : w'.sagas = w.sagas) (signals : w'.signals = w.signals) : Tidy w' := by + refine tidy_swap h fibers record inbox fibers' ?_ ?_ ?_ ?_ ?_ ?_ + · intro g mem + simp only [List.mem_singleton] at mem + exact .inr ⟨p', mem, sound⟩ + · intro t; rw [signals]; exact h.signals t + · intro t input eq + exact absurd (congrArg Fiber.program eq) (notStart t input) + · intro t; rw [sagas]; exact id + · intro t run + rw [sagas] at run + exact .inr ⟨run, fun stage eq => absurd eq (policy_not_stage p stage)⟩ + · intro t done + rw [sagas] at done + exact .inr done + +/-- Completing a transfer that is past its request leaves it ended. -/ +theorem complete_world (r : Recorded BankAggregates) (now : Time) (id : TransferId) + (past : PastAt r id) : EndedAt (r.dispatch now (completeSend id)) id := by + have after := transfer_state_after r now sagaActor (.complete ⟨id⟩) + show EndedState ((r.dispatch now (completeSend id)).state .transfer id) + rw [show (r.dispatch now (completeSend id)).state .transfer id = _ from after] + exact complete_ends ⟨id⟩ past + +/-- Recording a failure on a transfer that is past its request leaves it ended. -/ +theorem fail_world (r : Recorded BankAggregates) (now : Time) (id : TransferId) + (failure : TransferFailure) (past : PastAt r id) : + EndedAt (r.dispatch now (finalizer id failure)) id := by + have after := transfer_state_after r now sagaActor (.fail ⟨id, reasonOf failure⟩) + show EndedState ((r.dispatch now (finalizer id failure)).state .transfer id) + rw [show (r.dispatch now (finalizer id failure)).state .transfer id = _ from after] + exact fail_ends ⟨id, reasonOf failure⟩ past + +/-- One step of any fiber keeps the bank tidy. -/ +theorem tidy_advance {w w' : World BankSignature} (h : Tidy w) + {before after : List (Fiber BankSignature)} {f : Fiber BankSignature} + {fs : List (Fiber BankSignature)} (fibers : w.fibers = before ++ f :: after) + (adv : Bank.advance w f = some (w', fs)) : + Tidy { w' with fibers := before ++ fs ++ after } := by + have forward := fun s => forward_dispatch w.toRecorded w.now s + rcases h.good f (by rw [fibers]; simp) with ⟨stage, at_, ok⟩ | ⟨p, at_, sound⟩ + · subst at_ + cases stage with + | «begin» id input => + simp only [Stage.fiber, Model.advance, executeTransfer_eq] at adv + cases adv + exact tidy_next h fibers (.begin id input) (.gate id input) rfl rfl ok rfl rfl rfl rfl h.signals + | gate id input => + cases approval : input.needsApproval with + | false => + have past : PastAt w.toRecorded id := ok approval + simp only [Stage.fiber, Model.advance, gate_goes id input approval, debit_eq] at adv + cases adv + cases outcome : w.toRecorded.outcome w.now (debitSend id input.details) with + | ok es => + have := tidy_next_after h (debitSend id input.details) fibers (.gate id input) + (.debited id input.details) rfl rfl ((forward _ id).1 past) + simpa [Stage.fiber, outcome] using this + | error e => + have := tidy_next_after h (debitSend id input.details) fibers (.gate id input) + (.failing id (whyNotDebited e)) rfl rfl ((forward _ id).1 past) + simpa [Stage.fiber, outcome] using this + | true => + simp only [Stage.fiber, Model.advance, gate_waits id input approval] at adv + split at adv + · cases adv + · next signal rest waiting => + cases adv + have took : ∀ t, ∀ x, x ∈ update w.signals id rest t → x ∈ w.signals t := by + intro t x mem + unfold update at mem + split at mem + · next here => subst here; rw [waiting]; exact List.mem_cons_of_mem _ mem + · exact mem + have head : signal ∈ w.signals id := by rw [waiting]; exact List.mem_cons_self + have sigs : ∀ t, (Approval.approved ∈ update w.signals id rest t → PastAt w.toRecorded t) ∧ + (Approval.expired ∈ update w.signals id rest t → FailedAt w.toRecorded t) := + fun t => ⟨fun mem => (h.signals t).1 (took t _ mem), fun mem => (h.signals t).2 (took t _ mem)⟩ + cases signal with + | approved => + exact tidy_next h fibers (.gate id input) (.debit id input.details) rfl rfl + ((h.signals id).1 head) rfl rfl rfl rfl sigs + | expired => + exact tidy_next h fibers (.gate id input) (.finished id [finalizer id]) rfl rfl + ((h.signals id).2 head).ended rfl rfl rfl rfl sigs + | debit id d => + have past : PastAt w.toRecorded id := ok + simp only [Stage.fiber, Model.advance, debit_eq] at adv + cases adv + cases outcome : w.toRecorded.outcome w.now (debitSend id d) with + | ok es => + have := tidy_next_after h (debitSend id d) fibers (.debit id d) (.debited id d) rfl rfl + ((forward _ id).1 past) + simpa [Stage.fiber, outcome] using this + | error e => + have := tidy_next_after h (debitSend id d) fibers (.debit id d) + (.failing id (whyNotDebited e)) rfl rfl ((forward _ id).1 past) + simpa [Stage.fiber, outcome] using this + | debited id d => + simp only [Stage.fiber, Model.advance, debited_eq] at adv + cases adv + exact tidy_next h fibers (.debited id d) (.credit id d) rfl rfl ok rfl rfl rfl rfl h.signals + | credit id d => + have past : PastAt w.toRecorded id := ok + simp only [Stage.fiber, Model.advance, credit_eq] at adv + cases adv + cases outcome : w.toRecorded.outcome w.now (creditSend id d) with + | ok es => + have := tidy_next_after h (creditSend id d) fibers (.credit id d) (.completing id d) rfl rfl + ((forward _ id).1 past) + simpa [Stage.fiber, outcome] using this + | error e => + have := tidy_next_after h (creditSend id d) fibers (.credit id d) + (.refunding id d .destinationClosed) rfl rfl ((forward _ id).1 past) + simpa [Stage.fiber, outcome] using this + | completing id d => + simp only [Stage.fiber, Model.advance, Program.tell] at adv + cases adv + exact tidy_next_after h (completeSend id) fibers (.completing id d) + (.finished id [refunder id d, finalizer id]) rfl rfl (complete_world _ _ id ok) + | finished id undo => + simp only [Stage.fiber, Model.advance] at adv + cases adv + exact tidy_finish h fibers (.finished id undo) rfl ok .completed (.inl rfl) + | refunding id d failure => + simp only [Stage.fiber, Model.advance] at adv + cases adv + exact tidy_next_after h (refunder id d failure) fibers (.refunding id d failure) + (.failing id failure) rfl rfl ((forward _ id).1 ok) + | failing id failure => + simp only [Stage.fiber, Model.advance] at adv + cases adv + exact tidy_next_after h (finalizer id failure) fibers (.failing id failure) + (.failed id failure) rfl rfl (fail_world _ _ id failure ok) + | failed id failure => + simp only [Stage.fiber, Model.advance] at adv + cases adv + exact tidy_finish h fibers (.failed id failure) rfl ok (.failed failure) (.inr ⟨failure, rfl⟩) + · subst at_ + cases sound with + | pure => + simp only [Model.advance] at adv + cases adv + refine tidy_swap h fibers rfl rfl rfl (fs := []) ?_ h.signals ?_ (fun _ begun => begun) ?_ (fun _ => .inr) + · intro g mem; cases mem + · intro t input eq; cases eq + · intro t run + exact .inr ⟨run, fun stage eq => absurd eq (policy_not_stage _ stage)⟩ + | send s k next => + simp only [Model.advance] at adv + cases adv + exact tidy_policy (tidy_dispatch h s) (w := w.dispatch s) fibers (fun _ _ eq => nomatch eq) + ((next _).forward (forward s)) rfl rfl rfl rfl rfl + | call c k next => + simp only [Model.advance] at adv + cases adv + | start t input k past next => + simp only [Model.advance] at adv + split at adv + · next fresh => + cases adv + refine tidy_swap h fibers rfl rfl rfl (fs := [_, _]) ?_ h.signals ?_ ?_ ?_ ?_ + · intro g mem + simp only [List.mem_cons, List.mem_nil_iff, or_false] at mem + rcases mem with rfl | rfl + · exact .inr ⟨k, rfl, next⟩ + · exact .inl ⟨.begin t input, rfl, past⟩ + · intro t' input' eq + cases eq + show update w.sagas t .running t ≠ .notStarted + simp [update] + · intro t' begun + show update w.sagas t .running t' ≠ .notStarted + unfold update + split + · simp + · exact begun + · intro t' run + by_cases here : t' = t + · subst here + exact .inl ⟨.begin t' input, by simp [Stage.fiber], rfl⟩ + · have run' : update w.sagas t .running t' = .running := run + simp only [update, here, ↓reduceIte] at run' + exact .inr ⟨run', fun stage eq => absurd eq (policy_not_stage _ stage)⟩ + · intro t' done + have done' : update w.sagas t .running t' = .completed ∨ + ∃ x, update w.sagas t .running t' = .failed x := done + unfold update at done' + split at done' + · rcases done' with c | ⟨x, c⟩ <;> cases c + · exact .inr done' + · next begun => + cases adv + refine tidy_swap h fibers rfl rfl rfl (fs := [_]) ?_ h.signals ?_ (fun _ begun => begun) ?_ (fun _ => .inr) + · intro g mem + simp only [List.mem_singleton] at mem + exact .inr ⟨k, mem, next⟩ + · intro t' input' eq + cases eq + intro fresh + exact begun fresh + · intro t' run + exact .inr ⟨run, fun stage eq => absurd eq (policy_not_stage _ stage)⟩ + | signal t sig k past failed next => + simp only [Model.advance] at adv + cases adv + refine tidy_swap h fibers rfl rfl rfl (fs := [_]) ?_ ?_ ?_ (fun _ begun => begun) ?_ (fun _ => .inr) + · intro g mem + simp only [List.mem_singleton] at mem + exact .inr ⟨k, mem, next⟩ + · intro t' + have took : ∀ x, x ∈ update w.signals t (w.signals t ++ [sig]) t' → + x ∈ w.signals t' ∨ (t' = t ∧ x = sig) := by + intro x mem + unfold update at mem + split at mem + · next here => + subst here + simp only [List.mem_append, List.mem_singleton] at mem + rcases mem with old | new + · exact .inl old + · exact .inr ⟨rfl, new⟩ + · exact .inl mem + constructor + · intro mem + rcases took _ mem with old | ⟨here, eq⟩ + · exact (h.signals t').1 old + · subst here; exact past eq.symm + · intro mem + rcases took _ mem with old | ⟨here, eq⟩ + · exact (h.signals t').2 old + · subst here; exact failed eq.symm + · intro t' input' eq; cases eq + · intro t' run + exact .inr ⟨run, fun stage eq => absurd eq (policy_not_stage _ stage)⟩ + | schedule after_ s k next => + simp only [Model.advance] at adv + cases adv + exact tidy_policy h fibers (fun _ _ eq => nomatch eq) next rfl rfl rfl rfl rfl + +/-! ## The rule -/ + +theorem tidy_start : Tidy (World.start BankSignature) where + facts := facts_start + inbox := fun _ mem => nomatch mem + good := fun _ mem => nomatch mem + signals := fun _ => ⟨(fun mem => nomatch mem), (fun mem => nomatch mem)⟩ + coming := fun _ ⟨_, mem, _⟩ => nomatch mem + running := fun _ run => nomatch run + ended := fun _ done => by rcases done with c | ⟨_, c⟩ <;> cases c + +/-- The bank is tidy in every world it can reach, whatever its callers send. -/ +theorem alwaysTidy (w : World BankSignature) (reach : Bank.Reachable w) : Tidy w := by + refine Bank.worldInvariant (rule := Tidy) tidy_start ?_ w reach + intro w w' h step + cases step with + | send s _ => exact tidy_dispatch h s + | decide d actor c mem => + simp only [List.mem_singleton] at mem + subst mem + exact tidy_decide h actor c + | deliver e before after inbox => exact tidy_deliver h e before after inbox + | redeliver e logged => exact tidy_react h e logged + | advance f before after w'' fs fibers adv => exact tidy_advance h fibers adv + | answer f before after c k reply fibers program => + rcases h.good f (by rw [fibers]; simp) with ⟨stage, at_, _⟩ | ⟨p, at_, sound⟩ + · exfalso + subst at_ + cases stage with + | gate id input => + cases approval : input.needsApproval with + | false => simp [Stage.fiber, gate_goes id input approval, debit_eq] at program + | true => simp [Stage.fiber, gate_waits id input approval] at program + | _ => + simp [Stage.fiber, executeTransfer_eq, debit_eq, debited_eq, credit_eq, Program.tell] + at program + · subst at_ + cases sound with + | call c' k' next => + cases program + exact tidy_policy h fibers (fun _ _ eq => nomatch eq) (next reply) rfl rfl (by simp) rfl rfl + | _ => cases program + | tick time _ => exact tidy_same h rfl rfl rfl rfl rfl + | fire due s before after _ _ => + exact tidy_dispatch (tidy_same h (w' := { w with schedule := before ++ after }) rfl rfl rfl rfl rfl) s + +/-- +Every transfer ends. In every world the bank can reach, whatever its callers +send, in any order of delivery, with any event delivered again, whichever step +runs next, whatever the outside systems answer and whenever time passes: once +every event is delivered and no policy or saga is part-way through or waiting, +each transfer that was asked for has completed or has failed. +-/ +theorem everyTransferEnds (w : World BankSignature) (reach : Bank.Reachable w) + (delivered : w.inbox = []) (idle : w.fibers = []) (t : TransferId) + (asked : w.state .transfer t ≠ .new) : EndedState (w.state .transfer t) := by + have tidy := alwaysTidy w reach + rcases tidy.coming t (tidy.facts.known t asked) with ⟨_, mem, _⟩ | ⟨_, mem⟩ | begun + · rw [delivered] at mem; cases mem + · rw [idle] at mem; cases mem + · cases status : w.sagas t with + | notStarted => exact absurd status begun + | running => + obtain ⟨stage, mem, _⟩ := tidy.running t status + rw [idle] at mem + cases mem + | completed => exact tidy.ended t (.inl status) + | failed x => exact tidy.ended t (.inr ⟨x, status⟩) + +/-- No transfer is left pending, under the same conditions: it follows from the rule above. -/ +theorem noTransferLeftPending (w : World BankSignature) (reach : Bank.Reachable w) + (delivered : w.inbox = []) (idle : w.fibers = []) (t : TransferId) (d : TransferDetails) : + w.state .transfer t ≠ .pending d := by + intro pending + have ended := everyTransferEnds w reach delivered idle t (by rw [pending]; simp) + rw [pending] at ended + exact ended + +end Bank diff --git a/packages/alchemy-lean/examples/Bank/Processes.lean b/packages/alchemy-lean/examples/Bank/Processes.lean new file mode 100644 index 00000000000..931ba6faf59 --- /dev/null +++ b/packages/alchemy-lean/examples/Bank/Processes.lean @@ -0,0 +1,135 @@ +import Alchemy +import Bank.Views + +open Alchemy + +namespace Bank + +abbrev Step := Program BankSignature + +/-- How long a support agent has to approve a large transfer: 24 hours. -/ +def approvalWindow : Time := 86400 + +/-! ## Policies -/ + +/-- Whenever a customer registers, open their main account. -/ +def MainAccountProvisioning : Policy BankSignature := + .on "MainAccountProvisioning" .customer fun customerId event => + match event with + | .customerRegistered name _ => + Program.tell ⟨.account, .system "MainAccountProvisioning", + .openAccount ⟨mainAccountId customerId, customerId, name⟩⟩ + +/-- +Starts the ExecuteTransfer saga for every requested transfer, and passes on what +the Transfer decides about a large one: approved, or expired. +-/ +def TransferExecution : Policy BankSignature := + .on "TransferExecution" .transfer fun transferId event => + match event with + | .transferRequested details needsApproval => + Program.startSaga transferId ⟨details, needsApproval⟩ + | .transferApproved .. => Program.signalSaga transferId .approved + | .transferFailed _ => Program.signalSaga transferId .expired + | .transferCompleted => pure () + +/-- +Whenever a transfer needs approval, expire it if nobody approves it in time. The +Transfer decides the race, so exactly one of approval and expiry wins. +-/ +def TransferApprovalDeadline : Policy BankSignature := + .on "TransferApprovalDeadline" .transfer fun transferId event => + match event with + | .transferRequested _ true => + Program.later approvalWindow + ⟨.transfer, .system "TransferApprovalDeadline", .expire ⟨transferId⟩⟩ + | _ => pure () + +/-- Whenever an account's daily outflow crosses the threshold, score it and freeze the account if risky. -/ +def FraudReview : Policy BankSignature := + .onView "FraudReview" DailyOutflow fun accountId exceeded => do + let score ← Program.request (σ := BankSignature) (BankCall.fraudScore accountId exceeded.total) + if score.risk > 80 then + Program.tell ⟨.account, .system "FraudReview", + .freeze ⟨accountId, s!"fraud risk {score.risk}"⟩⟩ + +/-- Whenever money settles on a closed account, refund it. -/ +def SettlementRefund : Policy BankSignature := + .on "SettlementRefund" .account fun _ event => + match event with + | .settlementOnClosedAccount settlementId amount => do + let _ ← Program.request (σ := BankSignature) (BankCall.refund settlementId amount) + | _ => pure () + +/-! ## The ExecuteTransfer saga -/ + +/-- Why a debit was refused, as a failure of the transfer. -/ +def whyNotDebited : AccountRejection → TransferFailure + | .notOpen => .notOpen + | .notOwner => .notOwner + | .frozen reason => .frozen reason + | .insufficientFunds .. => .insufficientFunds + | _ => .refused + +/-- Why a transfer failed, in the words the Transfer records. -/ +def reasonOf : TransferFailure → String + | .notOpen => "source account not open" + | .notOwner => "not your account" + | .frozen reason => s!"source frozen: {reason}" + | .insufficientFunds => "insufficient funds" + | .destinationClosed => "destination account not open" + | .refused => "refused" + +/-- What the saga acts as. -/ +abbrev sagaActor : Actor := .system "ExecuteTransfer" + +abbrev debitSend (id : TransferId) (d : TransferDetails) : Send BankAggregates := + ⟨.account, sagaActor, .debitTransfer ⟨d.source, id, d.amount, d.requestedBy⟩⟩ + +abbrev creditSend (id : TransferId) (d : TransferDetails) : Send BankAggregates := + ⟨.account, sagaActor, .creditTransfer ⟨d.destination, id, d.amount⟩⟩ + +abbrev completeSend (id : TransferId) : Send BankAggregates := + ⟨.transfer, sagaActor, .complete ⟨id⟩⟩ + +/-- The compensation for the debit: give the money back. -/ +abbrev refunder (id : TransferId) (d : TransferDetails) : TransferFailure → Send BankAggregates := + fun _ => ⟨.account, sagaActor, .refundTransfer ⟨d.source, id, d.amount⟩⟩ + +/-- Records the failure on the Transfer. Registered first, so it runs last. -/ +abbrev finalizer (id : TransferId) : TransferFailure → Send BankAggregates := + fun failure => ⟨.transfer, sagaActor, .fail ⟨id, reasonOf failure⟩⟩ + +/-- Credit the destination, then record the outcome. -/ +def credit (id : TransferId) (d : TransferDetails) : Step Unit := do + Program.step (creditSend id d) fun _ => .destinationClosed + Program.tell (completeSend id) + +/-- Once the debit is recorded: from here on, a failure refunds it. -/ +def debited (id : TransferId) (d : TransferDetails) : Step Unit := do + Program.undoWith (refunder id d) + credit id d + +/-- Debit first: if the credit fails, the money is refunded, so it is never created. -/ +def debit (id : TransferId) (d : TransferDetails) : Step Unit := do + Program.step (debitSend id d) whyNotDebited + debited id d + +/-- A large transfer waits for the Transfer to decide: approved, or expired. -/ +def gate (id : TransferId) (input : ExecuteTransferInput) : Step Unit := do + let approval ← if input.needsApproval then Program.awaitSignal else pure .approved + match approval with + | .expired => pure () + | .approved => debit id input.details + +/-- +Moves money between two accounts on behalf of the requester: waits for the +Transfer to decide a large transfer, debits the source, credits the destination, +and refunds the debit if the credit fails. The outcome is recorded on the +Transfer either way. +-/ +def executeTransfer (transferId : TransferId) (input : ExecuteTransferInput) : Step Unit := do + Program.undoWith (finalizer transferId) + gate transferId input + +end Bank diff --git a/packages/alchemy-lean/examples/Bank/Reads.lean b/packages/alchemy-lean/examples/Bank/Reads.lean new file mode 100644 index 00000000000..5749f43b204 --- /dev/null +++ b/packages/alchemy-lean/examples/Bank/Reads.lean @@ -0,0 +1,89 @@ +import Alchemy +import Bank.Views + +open Alchemy + +namespace Bank + +/-! ## Ledger: every money movement, written to a store outside the model -/ + +structure LedgerRow where + /-- Where the event sits in the log, so a replay writes the same row. -/ + id : Nat + accountId : AccountId + kind : LineKind + amount : Cents + balanceAfter : Cents + time : Time +deriving DecidableEq, Repr + +def Ledger : Projection BankAggregates where + name := "Ledger" + Row := LedgerRow + write + | _, ⟨.account, id, event, seq, time⟩ => + (lineOf event).map fun line => ⟨seq, id, line.kind, line.amount, line.balance, time⟩ + | _, _ => [] + +/-- What a log gives the ledger: a row for each statement line of each account event. -/ +theorem ledger_go (state : States BankAggregates) (history log : List (Emitted BankAggregates)) : + (Ledger.go history log).length + = (((Recorded.mk state log).eventsOf .account).map fun event => (lineOf event).length).sum := by + induction log generalizing history with + | nil => rfl + | cons e rest ih => + obtain ⟨source, id, event, seq, time⟩ := e + rw [Projection.go, List.length_append, ih] + cases source <;> simp [Recorded.eventsOf, Ledger] + +/-- +The ledger is given every money movement the accounts record, whatever the bank +did: it has exactly one row for each statement line of each account event. +-/ +theorem ledgerIsGivenEveryMovement (r : Recorded BankAggregates) : + (Ledger.table r.log).length = (((r.eventsOf .account).map fun event => (lineOf event).length).sum) := + ledger_go r.state [] r.log + +/-- One account's ledger, oldest first. Its owner and agents read it. -/ +def AccountLedger : Query BankAggregates where + name := "AccountLedger" + Input := AccountId + Row := LedgerRow + Actor := Actor + Rejection := AccountRejection + handle := fun actor log account => + (mustOwn actor (AccountSummary.stateAt log account).customerId).map fun _ => + (Ledger.table log).filter (·.accountId = account) + +/-! ## AccountCard: a log per account that clients follow -/ + +structure CardChanged where + customerId : CustomerId + owner : String + balance : Cents + frozen : Bool +deriving DecidableEq, Repr + +def changesTheCard : AccountEvent → Bool + | .moneyDeposited .. | .moneyWithdrawn .. | .transferDebited .. | .transferCredited .. + | .transferRefunded .. | .settlementReceived .. | .accountFrozen .. => true + | _ => false + +/-- The AccountCards projection appends a card on every change to the summary. -/ +def AccountCard : Stream BankAggregates where + name := "AccountCard" + Key := AccountId + Entry := CardChanged + Actor := Actor + Rejection := AccountRejection + append + | history, e@⟨.account, id, event, _, _⟩ => + let summary := AccountSummary.stateAt (history ++ [e]) id + match changesTheCard event, summary.customerId, summary.owner with + | true, some customerId, some owner => + [(id, ⟨customerId, owner, summary.balance, summary.frozen⟩)] + | _, _, _ => [] + | _, _ => [] + validate := fun actor _ latest => mustOwn actor (latest.map (·.customerId)) + +end Bank diff --git a/packages/alchemy-lean/examples/Bank/Registration.lean b/packages/alchemy-lean/examples/Bank/Registration.lean new file mode 100644 index 00000000000..4c0fa31d121 --- /dev/null +++ b/packages/alchemy-lean/examples/Bank/Registration.lean @@ -0,0 +1,122 @@ +import Alchemy +import Bank.Shape + +open Alchemy + +namespace Bank + +/-- Sign up as a customer under a unique username. -/ +structure RegisterCustomer where + customerId : CustomerId + name : String + username : Username +deriving DecidableEq, Repr + +inductive RegistrationRejection where + | alreadyRegistered + /-- A customer may only register themselves. -/ + | notTheCustomer + /-- Someone else holds this username. -/ + | usernameTaken +deriving DecidableEq, Repr + +/-- Whether this actor may register this customer. -/ +def mayRegister : Actor → CustomerId → Bool + | .customer actor, customerId => actor = customerId + | _, _ => true + +def decideRegistration (ctx : Context Actor) (state : States BankAggregates) + (c : RegisterCustomer) : Except RegistrationRejection (List (Record BankAggregates)) := + if mayRegister ctx.actor c.customerId then + match state .customer c.customerId with + | .registered .. => .error .alreadyRegistered + | .new => + match state .usernameClaim c.username with + | .claimed _ => .error .usernameTaken + | .free => + .ok [ + ⟨.customer, c.customerId, .customerRegistered c.name c.username⟩, + ⟨.usernameClaim, c.username, .usernameClaimed c.customerId⟩ ] + else .error .notTheCustomer + +/-- +Register a customer and claim their username together. Both are recorded, or +neither is: a taken username rejects the registration, and two customers who ask +for one name can't both get it. +-/ +def Registration : Decision BankAggregates where + name := "Registration" + Command := RegisterCustomer + Rejection := RegistrationRejection + Actor := Actor + decide := decideRegistration + +/-- What a registration that is accepted found, and what it records. -/ +theorem registration_accepted {ctx : Context Actor} {state : States BankAggregates} + {c : RegisterCustomer} {rs : List (Record BankAggregates)} + (h : decideRegistration ctx state c = .ok rs) : + state .customer c.customerId = .new ∧ state .usernameClaim c.username = .free ∧ + rs = [ + ⟨.customer, c.customerId, .customerRegistered c.name c.username⟩, + ⟨.usernameClaim, c.username, .usernameClaimed c.customerId⟩ ] := by + unfold decideRegistration at h + split at h + · split at h + · simp at h + · next new => + split at h + · simp at h + · next free => simp at h; exact ⟨new, free, h.symm⟩ + · simp at h + +/-- Every state after a registration: the customer's, the username's, and the rest untouched. -/ +theorem registration_states (r : Recorded BankAggregates) (ctx : Context Actor) + (c : RegisterCustomer) (rs : List (Record BankAggregates)) + (h : decideRegistration ctx r.state c = .ok rs) : + let after := r.decide Registration ctx c + (∀ id, after.state .customer id = + if id = c.customerId then .registered c.name c.username else r.state .customer id) ∧ + (∀ id, after.state .usernameClaim id = + if id = c.username then .claimed c.customerId else r.state .usernameClaim id) ∧ + (∀ id, after.state .account id = r.state .account id) ∧ + (∀ id, after.state .transfer id = r.state .transfer id) := by + obtain ⟨_, _, records⟩ := registration_accepted h + subst records + simp only [Recorded.decide, Registration, h, Recorded.records, List.foldl] + refine ⟨?_, ?_, ?_, ?_⟩ <;> intro id <;> + simp [Recorded.record, States.set, Aggregate.apply] <;> grind + +/-! ## Rules about the decision -/ + +/-- The username goes to the customer who registered under it. -/ +theorem theNameGoesToWhoRegistered (r : Recorded BankAggregates) (ctx : Context Actor) + (c : RegisterCustomer) (rs : List (Record BankAggregates)) + (h : decideRegistration ctx r.state c = .ok rs) : + (r.decide Registration ctx c).state .customer c.customerId = .registered c.name c.username ∧ + (r.decide Registration ctx c).state .usernameClaim c.username = .claimed c.customerId := by + obtain ⟨customers, claims, _, _⟩ := registration_states r ctx c rs h + simp [customers, claims] + +/-- A name is only given while nobody holds it. -/ +theorem onlyAFreeNameIsClaimed (r : Recorded BankAggregates) (ctx : Context Actor) + (c : RegisterCustomer) (rs : List (Record BankAggregates)) + (h : decideRegistration ctx r.state c = .ok rs) : + r.state .usernameClaim c.username = .free := + (registration_accepted h).2.1 + +/-- Once somebody holds a name, no registration gives it to anybody else. -/ +theorem aClaimedNameStaysWithItsHolder (r : Recorded BankAggregates) (ctx : Context Actor) + (c : RegisterCustomer) (username : Username) (holder : CustomerId) + (held : r.state .usernameClaim username = .claimed holder) : + (r.decide Registration ctx c).state .usernameClaim username = .claimed holder := by + cases h : decideRegistration ctx r.state c with + | error _ => simpa [Recorded.decide, Registration, h] using held + | ok rs => + obtain ⟨_, claims, _, _⟩ := registration_states r ctx c rs h + have free := (registration_accepted h).2.1 + rw [claims] + split + · next same => subst same; rw [free] at held; cases held + · exact held + +end Bank diff --git a/packages/alchemy-lean/examples/Bank/Search.lean b/packages/alchemy-lean/examples/Bank/Search.lean new file mode 100644 index 00000000000..5c1b564b226 --- /dev/null +++ b/packages/alchemy-lean/examples/Bank/Search.lean @@ -0,0 +1,119 @@ +import Alchemy +import Bank.Model +import Bank.Stories + +open Alchemy + +namespace Bank + +/-! +Rules about the bank as a whole, once it has settled. These are checked in every +sequence of the moves below up to a depth, not proved for ever: `native_decide` +runs the search with compiled code. +-/ + +/-- What callers, outside systems and the clock do in the sequences searched. -/ +def moves : List (Model.Move Bank) := [ + .decide Registration sam ⟨"c-1", "Sam", "sam"⟩, + .decide Registration alex ⟨"c-2", "Alex", "alex"⟩, + .send ⟨.account, sam, .deposit ⟨"c-1-main", 30000⟩⟩, + .send ⟨.transfer, sam, .request ⟨"t-1", "c-1-main", "c-2-main", 100⟩⟩, + .send ⟨.transfer, sam, .request ⟨"t-2", "c-1-main", "c-2-main", 20000⟩⟩, + .send ⟨.transfer, support, .approve ⟨"t-2"⟩⟩, + .send ⟨.account, alex, .close ⟨"c-2-main"⟩⟩, + .pass 86400 ] + +def sum (amounts : List Cents) : Cents := amounts.foldl (· + ·) 0 + +/-- Every cent a transfer takes out of an account is paid into another, paid back, or recorded as stranded. -/ +def moneyIsAccountedFor (w : World BankSignature) : Bool := + let events := w.toRecorded.eventsOf .account + let taken := sum (events.filterMap fun + | .transferDebited _ amount _ => some amount + | _ => none) + let given := sum (events.filterMap fun + | .transferCredited _ amount _ | .transferRefunded _ amount _ | .refundStranded _ amount => + some amount + | _ => none) + taken = given + +/-- A transfer that may run has run: it completed or it failed. -/ +def nothingLeftPending (w : World BankSignature) : Bool := + (w.toRecorded.ids .transfer).all fun id => + match w.state .transfer id with + | .pending _ => false + | _ => true + +/-- The ledger is given every deposit the accounts record. -/ +def ledgerIsGivenEveryDeposit (w : World BankSignature) : Bool := + ((Ledger.table w.log).filter (·.kind = .deposit)).length = + ((w.toRecorded.eventsOf .account).filter (· matches .moneyDeposited ..)).length + +/-- Once the approval window has closed, every transfer has ended. -/ +def endsOnceTheWindowCloses (w : World BankSignature) : Bool := + let later := Bank.play 1000 w (.pass approvalWindow) + (later.toRecorded.ids .transfer).all fun id => + match later.state .transfer id with + | .completed | .failed _ => true + | _ => false + +/-- A customer has money in an account. -/ +def anAccountHoldsMoney (w : World BankSignature) : Bool := + (w.toRecorded.ids .account).any fun id => + match w.state .account id with + | .opened account => account.balance > 0 + | _ => false + +theorem transfersLoseNoMoney_checked : Bank.checked moves 4 moneyIsAccountedFor = true := by + native_decide + +theorem noTransferLeftPending_checked : Bank.checked moves 4 nothingLeftPending = true := by + native_decide + +theorem ledgerIsGivenEveryDeposit_checked : + Bank.checked moves 4 ledgerIsGivenEveryDeposit = true := by + native_decide + +/-- Eventually: no transfer waits for ever, because one nobody approves expires. -/ +theorem everyTransferEnds_checked : Bank.checked moves 4 endsOnceTheWindowCloses = true := by + native_decide + +/-- The same moves, with events delivered to the policies a second time. -/ +def movesWithRedelivery : List (Model.Move Bank) := + moves ++ [.redeliver 0, .redeliver 3, .redeliver 5] + +/-- Delivering an event twice loses no money and leaves no transfer pending. -/ +theorem redeliveryLosesNoMoney_checked : + Bank.checked movesWithRedelivery 4 + (fun w => moneyIsAccountedFor w && nothingLeftPending w) = true := by + native_decide + +/-- Sometimes: the bank can be used. -/ +theorem anAccountHoldsMoney_sometimes : Bank.sometimes moves 3 anAccountHoldsMoney = true := by + native_decide + +/-- +Sometimes, proved: there is a world the bank can reach where a customer has +money. The witness is a story: Sam registers, then deposits. +-/ +theorem anAccountCanHoldMoney : ∃ w, Bank.Reachable w ∧ anAccountHoldsMoney w = true := by + let registered := + Bank.settle 1000 ((World.start BankSignature).decide Registration sam ⟨"c-1", "Sam", "sam"⟩) + let deposited := + Bank.settle 1000 (registered.dispatch ⟨.account, sam, .deposit ⟨"c-1-main", 100⟩⟩) + refine ⟨deposited, ?_, by decide⟩ + refine Bank.settle_reachable _ _ (.step ?_ (.send _ _ trivial)) + exact Bank.settle_reachable _ _ (.step .start (.decide _ _ _ _ (by simp))) + +/-- +A rule that is false gives the shortest sequence that breaks it. "No transfer +ever waits for approval" breaks after one move: Sam asks to move 20,000. +-/ +example : + Bank.counterexample moves 4 + (fun w => (w.toRecorded.ids .transfer).all fun id => + !(w.state .transfer id matches .awaitingApproval _)) + = some [4] := by + native_decide + +end Bank diff --git a/packages/alchemy-lean/examples/Bank/Server.lean b/packages/alchemy-lean/examples/Bank/Server.lean new file mode 100644 index 00000000000..8487c4d0048 --- /dev/null +++ b/packages/alchemy-lean/examples/Bank/Server.lean @@ -0,0 +1,240 @@ +import Alchemy +import Bank.Model +import Bank.Api + +/-! +The bank over HTTP. `lake exe bank` serves it, and keeps it in a journal file, +so it is where it was after a restart. + +- `POST /commands` sends a command: `{"as": "customer:c-1", "type": "DepositMoney", ...}`. +- `GET /accounts/:id/summary`, `/statement`, `/ledger`, `/card`, `/customers/:id/dashboard` and + `/transfers/:id` read, as whoever `?as=` says. +- `GET /` is a page that does both. +-/ + +open Alchemy +open Lean (Json) + +namespace Bank + +/-- Who a request is from: `customer:c-1`, `agent:support-7`. -/ +def actorOf (text : String) : Option Actor := + match text.splitOn ":" with + | ["customer", id] => some (.customer id) + | ["agent", id] => some (.agent id) + | _ => none + +def json (status : Nat) (body : Json) : Reply := { status, body := body.compress } + +def refused (status : Nat) (why : String) : Reply := json status (Json.mkObj [("error", why)]) + +def field (body : Json) (name : String) : Option String := (body.getObjValAs? String name).toOption +def amount (body : Json) (name : String) : Option Nat := (body.getObjValAs? Nat name).toOption + +/-- What the caller is told about a command: what it recorded, or why it was rejected. -/ +def answered {Event Rejection : Type} [Repr Event] [Repr Rejection] + (answer : Except Rejection (List Event)) (reply : Json := Json.null) : Reply := + match answer with + | .ok events => + json 200 (Json.mkObj [("recorded", Json.arr (events.toArray.map fun e => reprStr e)), + ("reply", reply)]) + | .error rejection => json 409 (Json.mkObj [("rejected", reprStr rejection)]) + +def toAccount (actor : Actor) (command : AccountCommand) : Routed Bank := + let send : Send BankAggregates := ⟨.account, actor, command⟩ + let offered := match actor with + | .customer _ => CustomerApi.accepts send + | _ => SupportApi.accepts send || CustomerApi.accepts send + if offered then + .move (.send send) fun before after => + let id := keyOfAccount command + answered (decideAccount ⟨actor, before.now⟩ (before.state .account id) command) + (match replyAccount (after.state .account id) command with + | some balance => Json.mkObj [("balance", balance)] + | none => Json.null) + else .refuse (refused 403 "this Api does not offer that command") + +def toTransfer (actor : Actor) (command : TransferCommand) : Routed Bank := + let send : Send BankAggregates := ⟨.transfer, actor, command⟩ + let offered := match actor with + | .customer _ => CustomerApi.accepts send + | _ => SupportApi.accepts send || CustomerApi.accepts send + if offered then + .move (.send send) fun before _ => + answered (decideTransfer ⟨actor, before.now⟩ + (before.state .transfer (Transfer.keyOf command)) command) + else .refuse (refused 403 "this Api does not offer that command") + +/-- What a request body asks for. -/ +inductive Asked where + | register (c : RegisterCustomer) + | account (c : AccountCommand) + | transfer (c : TransferCommand) + +def asked (body : Json) : Option (Actor × Asked) := do + let actor ← actorOf (← field body "as") + let what ← match ← field body "type" with + | "RegisterCustomer" => + pure (Asked.register ⟨← field body "customerId", ← field body "name", ← field body "username"⟩) + | "DepositMoney" => pure (.account (.deposit ⟨← field body "accountId", ← amount body "amount"⟩)) + | "WithdrawMoney" => pure (.account (.withdraw ⟨← field body "accountId", ← amount body "amount"⟩)) + | "CloseAccount" => pure (.account (.close ⟨← field body "accountId"⟩)) + | "FreezeAccount" => pure (.account (.freeze ⟨← field body "accountId", ← field body "reason"⟩)) + | "ChangeOwner" => + pure (.account (.changeOwner ⟨← field body "accountId", ← field body "customerId"⟩)) + | "RequestTransfer" => + pure (.transfer (.request + ⟨← field body "transferId", ← field body "from", ← field body "to", ← amount body "amount"⟩)) + | "ApproveTransfer" => pure (.transfer (.approve ⟨← field body "transferId"⟩)) + | _ => none + pure (actor, what) + +def command (actor : Actor) : Asked → Routed Bank + | .register c => + .move (.decide Registration actor c) fun before _ => + match decideRegistration ⟨actor, before.now⟩ before.state c with + | .ok _ => json 200 (Json.mkObj [("recorded", Json.arr #["customerRegistered", "usernameClaimed"])]) + | .error rejection => json 409 (Json.mkObj [("rejected", reprStr rejection)]) + | .account c => toAccount actor c + | .transfer c => toTransfer actor c + +/-- A read that a view, a stream or a query guards. -/ +def guarded {α Rejection : Type} [Repr Rejection] (read : Except Rejection α) (show_ : α → Json) : + Reply := + match read with + | .ok value => json 200 (show_ value) + | .error rejection => refused 403 (reprStr rejection) + +def lineJson (line : StatementLine) : Json := + Json.mkObj [("kind", reprStr line.kind), ("amount", line.amount), ("balance", line.balance)] + +def page : String := "Bank + +

Bank

+

As account

+

+

+

+ + +

+

Answer

Summary

Statement


+"
+
+def route (method path body : String) : Routed Bank :=
+  let (path, query) :=
+    match path.splitOn "?" with
+    | [p, q] => (p, q.splitOn "&" |>.filterMap fun (pair : String) =>
+        match pair.splitOn "=" with
+        | [k, v] => some (k, v)
+        | _ => none)
+    | _ => (path, [])
+  let actor := (query.lookup "as").bind actorOf
+  let segments := (path.splitOn "/").filter (· ≠ "")
+  let reading (respond : Actor → World BankSignature → Reply) : Routed Bank :=
+    match actor with
+    | some actor => .read (respond actor)
+    | none => .refuse (refused 400 "say who is asking: ?as=customer:c-1")
+  match method, segments with
+  | "GET", [] => .read fun _ => { type := "text/html", body := page }
+  | "POST", ["commands"] =>
+    match (Json.parse body).toOption.bind asked with
+    | some (actor, what) => command actor what
+    | none => .refuse (refused 400 "not a command")
+  | "GET", ["accounts", id, "summary"] =>
+    reading fun actor w => guarded (Rejection := AccountRejection) (AccountSummary.read actor w.log id : Except AccountRejection Summary) fun s =>
+      Json.mkObj [("customerId", s.customerId.elim Json.null Json.str),
+        ("owner", s.owner.elim Json.null Json.str), ("balance", s.balance),
+        ("frozen", s.frozen), ("closed", s.closed)]
+  | "GET", ["accounts", id, "statement"] =>
+    reading fun actor w => guarded (Rejection := AccountRejection) (AccountSummary.read actor w.log id : Except AccountRejection Summary) fun _ =>
+      Json.arr ((Statement.emittedAt w.log id : List StatementLine).toArray.map lineJson)
+  | "GET", ["accounts", id, "ledger"] =>
+    reading fun actor w =>
+      guarded (Rejection := AccountRejection) (AccountLedger.ask actor w.log id
+          (after := ((query.lookup "after").bind String.toNat?).getD 0)
+          (take := ((query.lookup "take").bind String.toNat?).getD 50)
+          : Except AccountRejection (Page LedgerRow))
+        fun page =>
+          Json.mkObj [
+            ("entries", Json.arr (page.entries.toArray.map fun (row : LedgerRow) =>
+              Json.mkObj [("id", row.id), ("kind", reprStr row.kind), ("amount", row.amount),
+                ("balanceAfter", row.balanceAfter), ("time", row.time)])),
+            ("cursor", page.cursor.elim Json.null fun c => (c : Json))]
+  | "GET", ["accounts", id, "card"] =>
+    reading fun actor w => guarded (Rejection := AccountRejection) (AccountCard.read actor w.log id : Except AccountRejection (List CardChanged))
+      fun cards => Json.arr (cards.toArray.map fun (card : CardChanged) =>
+        Json.mkObj [("customerId", card.customerId), ("owner", card.owner),
+          ("balance", card.balance), ("frozen", card.frozen)])
+  | "GET", ["customers", id, "dashboard"] =>
+    reading fun actor w => guarded (Rejection := String) (CustomerDashboard.read actor w.log id : Except String Dashboard) fun d =>
+      Json.mkObj [("name", d.name.elim Json.null Json.str), ("totalBalance", d.totalBalance),
+        ("balances", Json.mkObj (d.balances.map fun (account, balance) => (account, (balance : Json))))]
+  | "GET", ["transfers", id] =>
+    reading fun actor w => guarded (Rejection := AccountRejection) (TransferStatus.read actor w.log id : Except AccountRejection Status) fun s =>
+      Json.mkObj [("status", reprStr s.progress), ("amount", s.amount.elim Json.null fun a => (a : Json)),
+        ("failedReason", s.failedReason.elim Json.null Json.str)]
+  | _, _ => .refuse (refused 404 "no such route")
+
+/-- Asks an outside system over HTTP: the body of its answer, or nothing when it cannot be reached. -/
+def ask (url : String) : IO (Option String) := do
+  let out ← IO.Process.output { cmd := "curl", args := #["-fsS", "--max-time", "10", url] }
+  pure (if out.exitCode = 0 then some out.stdout.trimAscii.toString else none)
+
+/--
+FraudCheck.score: asks the service at `FRAUD_URL` for a risk out of 100. With no
+`FRAUD_URL`, a stand-in finds a day's outflow of 900.00 or more risky.
+-/
+def fraudScore (accountId : AccountId) (total : Cents) : IO FraudScore := do
+  let standIn : FraudScore := ⟨if total ≥ 90000 then 95 else 10⟩
+  match ← IO.getEnv "FRAUD_URL" with
+  | none => pure standIn
+  | some url =>
+    match (← ask s!"{url}?accountId={accountId}&amount={total}").bind String.toNat? with
+    | some risk => pure ⟨risk⟩
+    | none => throw (IO.userError "the fraud service gave no score")
+
+/--
+Payments.refund: asks the service at `PAYMENTS_URL` to refund, and takes the
+refund's id from its answer. With no `PAYMENTS_URL`, a stand-in makes one up.
+-/
+def refund (settlementId : String) (amount : Cents) : IO Refunded := do
+  match ← IO.getEnv "PAYMENTS_URL" with
+  | none => pure ⟨"re_" ++ settlementId⟩
+  | some url =>
+    match ← ask s!"{url}?settlementId={settlementId}&amount={amount}" with
+    | some refundId => pure ⟨refundId⟩
+    | none => throw (IO.userError "the payment processor did not refund")
+
+/--
+The bank's server. Each answer an outside system gives is written to the
+journal, so a replay never asks again.
+-/
+def host : Host Bank where
+  route := route
+  adapter
+    | .fraudScore accountId total => fraudScore accountId total
+    | .refund settlementId amount => refund settlementId amount
+  encodeReply
+    | .fraudScore .., score => toString score.risk
+    | .refund .., refunded => refunded.refundId
+  decodeReply
+    | .fraudScore .., text => text.toNat?.map fun risk => ⟨risk⟩
+    | .refund .., text => some ⟨text⟩
+
+end Bank
diff --git a/packages/alchemy-lean/examples/Bank/Shape.lean b/packages/alchemy-lean/examples/Bank/Shape.lean
new file mode 100644
index 00000000000..0a631d537aa
--- /dev/null
+++ b/packages/alchemy-lean/examples/Bank/Shape.lean
@@ -0,0 +1,81 @@
+import Alchemy
+import Bank.Account
+import Bank.Customer
+import Bank.Transfer
+
+open Alchemy
+
+namespace Bank
+
+/-- The aggregates of the bank. -/
+inductive BankAggregate where
+  | customer
+  | usernameClaim
+  | account
+  | transfer
+deriving DecidableEq, Repr
+
+abbrev BankAggregates : Aggregates where
+  Name := BankAggregate
+  of
+    | .customer => Customer
+    | .usernameClaim => UsernameClaim
+    | .account => Account
+    | .transfer => Transfer
+
+/-! ## Outside systems -/
+
+/-- How risky the fraud-scoring system finds an account's activity, out of 100. -/
+structure FraudScore where
+  risk : Nat
+deriving DecidableEq, Repr
+
+structure Refunded where
+  refundId : String
+deriving DecidableEq, Repr
+
+/-- The calls the bank makes to systems outside it. -/
+inductive BankCall where
+  /-- FraudCheck.score -/
+  | fraudScore (accountId : AccountId) (amount : Cents)
+  /-- Payments.refund -/
+  | refund (settlementId : String) (amount : Cents)
+deriving DecidableEq, Repr
+
+abbrev BankReply : BankCall → Type
+  | .fraudScore .. => FraudScore
+  | .refund .. => Refunded
+
+/-! ## The ExecuteTransfer saga -/
+
+/-- How a large transfer's wait for approval ended. -/
+inductive Approval where
+  | approved
+  | expired
+deriving DecidableEq, Repr
+
+structure ExecuteTransferInput where
+  details : TransferDetails
+  needsApproval : Bool
+deriving DecidableEq, Repr
+
+/-- Why a transfer could not be carried out. -/
+inductive TransferFailure where
+  | notOpen
+  | notOwner
+  | frozen (reason : String)
+  | insufficientFunds
+  | destinationClosed
+  | refused
+deriving DecidableEq, Repr
+
+abbrev BankSignature : Signature where
+  aggregates := BankAggregates
+  Call := BankCall
+  Reply := BankReply
+  Saga := TransferId
+  SagaInput := ExecuteTransferInput
+  Signal := Approval
+  Failure := TransferFailure
+
+end Bank
diff --git a/packages/alchemy-lean/examples/Bank/Stories.lean b/packages/alchemy-lean/examples/Bank/Stories.lean
new file mode 100644
index 00000000000..904dbfa0975
--- /dev/null
+++ b/packages/alchemy-lean/examples/Bank/Stories.lean
@@ -0,0 +1,242 @@
+import Alchemy
+import Bank.Model
+
+open Alchemy
+
+namespace Bank
+
+/-! Stories: examples of what the bank does. The compiler runs each one. -/
+
+abbrev Story := List (Story.ModelStep Bank)
+
+def sam : Actor := .customer "c-1"
+def alex : Actor := .customer "c-2"
+def support : Actor := .agent "support-7"
+
+def opened (customerId : CustomerId := "c-1") : AccountEvent := .accountOpened customerId "Sam"
+
+def registering : Story := [
+  .decide Registration sam ⟨"c-1", "Sam", "sam"⟩,
+  .recorded .customer "c-1" [.customerRegistered "Sam" "sam"],
+  .recorded .usernameClaim "sam" [.usernameClaimed "c-1"],
+  .recorded .account "c-1-main" [.accountOpened "c-1" "Sam"],
+  .view CustomerDashboard "c-1" { name := some "Sam", balances := [("c-1-main", 0)] } ]
+
+def aTakenUsername : Story := [
+  .given .usernameClaim "sam" [.usernameClaimed "c-9"],
+  .decide Registration sam ⟨"c-1", "Sam", "sam"⟩ (some .usernameTaken),
+  .state .customer "c-1" .new ]
+
+def registeringSomeoneElse : Story := [
+  .decide Registration alex ⟨"c-1", "Sam", "sam"⟩ (some .notTheCustomer) ]
+
+def withdrawing : Story := [
+  .given .account "a-1" [opened, .moneyDeposited 100 100],
+  .replies ⟨.account, sam, .withdraw ⟨"a-1", 30⟩⟩ (some 70),
+  .when ⟨.account, sam, .withdraw ⟨"a-1", 30⟩⟩,
+  .recorded .account "a-1" [.moneyWithdrawn 30 70],
+  .view AccountSummary "a-1"
+    { customerId := some "c-1", owner := some "Sam", balance := 70 },
+  .emitted Statement "a-1" [⟨.deposit, 100, 100⟩, ⟨.withdrawal, 30, 70⟩] ]
+
+def anOverdraft : Story := [
+  .given .account "a-1" [opened, .moneyDeposited 50 50],
+  .when ⟨.account, sam, .withdraw ⟨"a-1", 80⟩⟩,
+  .rejected .account (.insufficientFunds 50 80) ]
+
+def someoneElsesAccount : Story := [
+  .given .account "a-1" [opened, .moneyDeposited 100 100],
+  .when ⟨.account, alex, .withdraw ⟨"a-1", 30⟩⟩,
+  .rejected .account .notOwner ]
+
+def theDailyLimit : Story := [
+  .given .account "a-1" [opened, .moneyDeposited 300000 300000],
+  .when ⟨.account, sam, .withdraw ⟨"a-1", 40000⟩⟩,
+  .when ⟨.account, sam, .withdraw ⟨"a-1", 40000⟩⟩,
+  .call (.fraudScore "a-1" 80000),
+  .answer (.fraudScore "a-1" 80000) ⟨10⟩,
+  .when ⟨.account, sam, .withdraw ⟨"a-1", 30000⟩⟩,
+  .rejected .account (.dailyLimitExceeded 20000),
+  .pass 86400,
+  .when ⟨.account, sam, .withdraw ⟨"a-1", 30000⟩⟩,
+  .recorded .account "a-1"
+    [.moneyWithdrawn 40000 260000, .moneyWithdrawn 40000 220000, .moneyWithdrawn 30000 190000] ]
+
+def freezingTwice : Story := [
+  .given .account "a-1" [opened, .accountFrozen "kyc" support],
+  .when ⟨.account, support, .freeze ⟨"a-1", "again"⟩⟩,
+  .recorded .account "a-1" [],
+  .holds "still frozen for the first reason" fun w =>
+    match w.state .account "a-1" with
+    | .opened account => account.frozen = some "kyc"
+    | _ => false ]
+
+def aRiskyWithdrawal : Story := [
+  .given .account "a-1" [opened, .moneyDeposited 90000 90000],
+  .when ⟨.account, sam, .withdraw ⟨"a-1", 60000⟩⟩,
+  .recorded .account "a-1" [.moneyWithdrawn 60000 30000],
+  .call (.fraudScore "a-1" 60000),
+  .answer (.fraudScore "a-1" 60000) ⟨95⟩,
+  .recorded .account "a-1" [.accountFrozen "fraud risk 95" (.system "FraudReview")],
+  .when ⟨.account, sam, .withdraw ⟨"a-1", 10⟩⟩,
+  .rejected .account (.frozen "fraud risk 95") ]
+
+def splitWithdrawals : Story := [
+  .given .account "a-1" [opened, .moneyDeposited 90000 90000],
+  .when ⟨.account, sam, .withdraw ⟨"a-1", 30000⟩⟩,
+  .when ⟨.account, sam, .withdraw ⟨"a-1", 30000⟩⟩,
+  .recorded .account "a-1" [.moneyWithdrawn 30000 60000, .moneyWithdrawn 30000 30000],
+  .emitted DailyOutflow "a-1" [⟨0, 60000⟩],
+  .call (.fraudScore "a-1" 60000),
+  .answer (.fraudScore "a-1" 60000) ⟨10⟩,
+  .recorded .account "a-1" [] ]
+
+def closedWhileTheFraudCheckIsPending : Story := [
+  .given .account "a-1" [opened, .moneyDeposited 60000 60000],
+  .when ⟨.account, sam, .withdraw ⟨"a-1", 60000⟩⟩,
+  .call (.fraudScore "a-1" 60000),
+  .when ⟨.account, sam, .close ⟨"a-1"⟩⟩,
+  .recorded .account "a-1" [.moneyWithdrawn 60000 0, .accountClosed],
+  .answer (.fraudScore "a-1" 60000) ⟨95⟩,
+  .recorded .account "a-1" [],
+  .holds "the summary shows it closed" fun w => (AccountSummary.stateAt w.log "a-1").closed ]
+
+def twoAccounts : Story := [
+  .given .account "a-1" [opened "c-1", .moneyDeposited 100 100],
+  .given .account "a-2" [opened "c-2"] ]
+
+def aTransferCompletes : Story := twoAccounts ++ [
+  .when ⟨.transfer, sam, .request ⟨"t-1", "a-1", "a-2", 40⟩⟩,
+  .recorded .transfer "t-1" [.transferRequested ⟨"a-1", "a-2", 40, sam⟩ false, .transferCompleted],
+  .recorded .account "a-1" [.transferDebited "t-1" 40 60],
+  .recorded .account "a-2" [.transferCredited "t-1" 40 40],
+  .saga "t-1" .completed,
+  .holds "the status is completed" fun w =>
+    (TransferStatus.stateAt w.log "t-1").progress = .completed,
+  .emitted AccountTransfers "a-1" [⟨"t-1", 40, .outgoing⟩],
+  .emitted AccountTransfers "a-2" [⟨"t-1", 40, .incoming⟩] ]
+
+def someoneElsesMoney : Story := twoAccounts ++ [
+  .when ⟨.transfer, alex, .request ⟨"t-1", "a-1", "a-2", 40⟩⟩,
+  .recorded .transfer "t-1"
+    [.transferRequested ⟨"a-1", "a-2", 40, alex⟩ false, .transferFailed "not your account"],
+  .recorded .account "a-1" [],
+  .saga "t-1" (.failed .notOwner) ]
+
+def aLargeTransfer : Story := [
+  .given .account "a-1" [opened "c-1", .moneyDeposited 50000 50000],
+  .given .account "a-2" [opened "c-2"],
+  .when ⟨.transfer, sam, .request ⟨"t-1", "a-1", "a-2", 20000⟩⟩,
+  .recorded .transfer "t-1" [.transferRequested ⟨"a-1", "a-2", 20000, sam⟩ true],
+  .saga "t-1" .running,
+  .recorded .account "a-1" [],
+  .when ⟨.transfer, sam, .approve ⟨"t-1"⟩⟩,
+  .rejected .transfer .notPermitted,
+  .when ⟨.transfer, support, .approve ⟨"t-1"⟩⟩,
+  .recorded .transfer "t-1"
+    [.transferApproved ⟨"a-1", "a-2", 20000, sam⟩ support, .transferCompleted],
+  .recorded .account "a-1" [.transferDebited "t-1" 20000 30000],
+  .recorded .account "a-2" [.transferCredited "t-1" 20000 20000],
+  .saga "t-1" .completed,
+  .pass 86400,
+  .recorded .transfer "t-1" [] ]
+
+def anUnapprovedTransferExpires : Story := [
+  .given .account "a-1" [opened "c-1", .moneyDeposited 50000 50000],
+  .given .account "a-2" [opened "c-2"],
+  .when ⟨.transfer, sam, .request ⟨"t-1", "a-1", "a-2", 20000⟩⟩,
+  .recorded .transfer "t-1" [.transferRequested ⟨"a-1", "a-2", 20000, sam⟩ true],
+  .pass 86400,
+  .recorded .transfer "t-1" [.transferFailed "not approved in time"],
+  .recorded .account "a-1" [],
+  .saga "t-1" .completed,
+  .when ⟨.transfer, support, .approve ⟨"t-1"⟩⟩,
+  .rejected .transfer .notAwaitingApproval ]
+
+def aTransferToAClosedAccount : Story := [
+  .given .account "a-1" [opened "c-1", .moneyDeposited 100 100],
+  .given .account "a-2" [opened "c-2", .accountClosed],
+  .when ⟨.transfer, sam, .request ⟨"t-1", "a-1", "a-2", 40⟩⟩,
+  .recorded .account "a-1" [.transferDebited "t-1" 40 60, .transferRefunded "t-1" 40 100],
+  .recorded .account "a-2" [],
+  .recorded .transfer "t-1"
+    [.transferRequested ⟨"a-1", "a-2", 40, sam⟩ false,
+     .transferFailed "destination account not open"],
+  .saga "t-1" (.failed .destinationClosed) ]
+
+def aSettlementOnAClosedAccount : Story := [
+  .given .account "a-1" [opened, .accountClosed],
+  .when ⟨.account, .system "Payments", .recordSettlement ⟨"a-1", "st_1", 500⟩⟩,
+  .recorded .account "a-1" [.settlementOnClosedAccount "st_1" 500],
+  .call (.refund "st_1" 500),
+  .answer (.refund "st_1" 500) ⟨"re_st_1"⟩ ]
+
+def reassigning : Story := [
+  .given .account "a-1" [opened "c-1", .moneyDeposited 100 100],
+  .when ⟨.account, sam, .changeOwner ⟨"a-1", "c-2"⟩⟩,
+  .rejected .account .notPermitted,
+  .when ⟨.account, support, .changeOwner ⟨"a-1", "c-2"⟩⟩,
+  .recorded .account "a-1" [.ownerChanged "c-1" "c-2" support],
+  .view CustomerDashboard "c-1" { balances := [] },
+  .view CustomerDashboard "c-2" { balances := [("a-1", 100)] },
+  .emitted AccountActivity "a-1" [.ownerChanged "c-1" "c-2" support] ]
+
+def theLedgerIsPrivate : Story := [
+  .given .account "a-1" [opened "c-1", .moneyDeposited 100 100],
+  .when ⟨.account, sam, .withdraw ⟨"a-1", 30⟩⟩,
+  .recorded .account "a-1" [.moneyWithdrawn 30 70],
+  .holds "the owner reads two rows" fun w =>
+    match AccountLedger.ask sam w.log "a-1" with
+    | .ok page => page.entries.map (fun row => (row.kind, row.amount, row.balanceAfter))
+        = [(.deposit, 100, 100), (.withdrawal, 30, 70)]
+    | .error _ => false,
+  .holds "an agent reads it" fun w => (AccountLedger.ask support w.log "a-1").isOk,
+  .holds "another customer does not" fun w =>
+    AccountLedger.ask alex w.log "a-1" matches .error .notOwner,
+  .holds "a page of one row says where the next starts" fun w =>
+    match AccountLedger.ask sam w.log "a-1" (take := 1) with
+    | .ok page => page.entries.length = 1 ∧ page.cursor = some 1
+    | .error _ => false ]
+
+def theAccountCard : Story := [
+  .given .account "a-1" [opened "c-1", .moneyDeposited 100 100],
+  .when ⟨.account, sam, .withdraw ⟨"a-1", 30⟩⟩,
+  .recorded .account "a-1" [.moneyWithdrawn 30 70],
+  .holds "a card for every change" fun w =>
+    AccountCard.entries w.log "a-1" = [⟨"c-1", "Sam", 100, false⟩, ⟨"c-1", "Sam", 70, false⟩],
+  .holds "another customer cannot follow it" fun w =>
+    AccountCard.read alex w.log "a-1" matches .error .notOwner ]
+
+/-- Leaves the refund call unanswered. -/
+def anUnansweredCall : Story := [
+  .given .account "a-1" [opened, .accountClosed],
+  .when ⟨.account, .system "Payments", .recordSettlement ⟨"a-1", "st_1", 500⟩⟩,
+  .recorded .account "a-1" [.settlementOnClosedAccount "st_1" 500] ]
+
+/-! Each story is run when this file compiles. `#eval Bank.story aStory` says why one fails. -/
+
+example : Bank.passes registering = true := by decide
+example : Bank.passes aTakenUsername = true := by decide
+example : Bank.passes registeringSomeoneElse = true := by decide
+example : Bank.passes withdrawing = true := by decide
+example : Bank.passes anOverdraft = true := by decide
+example : Bank.passes someoneElsesAccount = true := by decide
+example : Bank.passes theDailyLimit = true := by decide
+example : Bank.passes freezingTwice = true := by decide
+example : Bank.passes aRiskyWithdrawal = true := by decide
+example : Bank.passes splitWithdrawals = true := by decide
+example : Bank.passes closedWhileTheFraudCheckIsPending = true := by decide
+example : Bank.passes aTransferCompletes = true := by decide
+example : Bank.passes someoneElsesMoney = true := by decide
+example : Bank.passes aLargeTransfer = true := by decide
+example : Bank.passes anUnapprovedTransferExpires = true := by decide
+example : Bank.passes aTransferToAClosedAccount = true := by decide
+example : Bank.passes aSettlementOnAClosedAccount = true := by decide
+example : Bank.passes reassigning = true := by decide
+example : Bank.passes theLedgerIsPrivate = true := by decide
+example : Bank.passes theAccountCard = true := by decide
+
+/-- A story that leaves a call unanswered fails. -/
+example : Bank.passes anUnansweredCall = false := by decide
+
+end Bank
diff --git a/packages/alchemy-lean/examples/Bank/Transfer.lean b/packages/alchemy-lean/examples/Bank/Transfer.lean
new file mode 100644
index 00000000000..de80550a641
--- /dev/null
+++ b/packages/alchemy-lean/examples/Bank/Transfer.lean
@@ -0,0 +1,190 @@
+import Alchemy
+import Bank.Types
+
+open Alchemy
+
+namespace Bank
+
+/-- Transfers of at least this many cents wait for a support agent's approval. -/
+def approvalThreshold : Cents := 10000
+
+/-- What a transfer moves, and for whom. -/
+structure TransferDetails where
+  source : AccountId
+  destination : AccountId
+  amount : Cents
+  requestedBy : Actor
+deriving DecidableEq, Repr
+
+structure RequestTransfer where
+  transferId : TransferId
+  source : AccountId
+  destination : AccountId
+  amount : Cents
+deriving DecidableEq, Repr
+
+/-- A support agent approves a large transfer before its approval window closes. -/
+structure ApproveTransfer where
+  transferId : TransferId
+deriving DecidableEq, Repr
+
+/-- The approval window closed. It reports a fact, so it is never rejected. -/
+structure ExpireTransfer where
+  transferId : TransferId
+deriving DecidableEq, Repr
+
+/-- Reports an outcome, so it is never rejected. -/
+structure CompleteTransfer where
+  transferId : TransferId
+deriving DecidableEq, Repr
+
+/-- Reports an outcome, so it is never rejected. -/
+structure FailTransfer where
+  transferId : TransferId
+  reason : String
+deriving DecidableEq, Repr
+
+inductive TransferCommand where
+  | request (c : RequestTransfer)
+  | approve (c : ApproveTransfer)
+  | expire (c : ExpireTransfer)
+  | complete (c : CompleteTransfer)
+  | fail (c : FailTransfer)
+deriving DecidableEq, Repr
+
+inductive TransferEvent where
+  | transferRequested (details : TransferDetails) (needsApproval : Bool)
+  | transferApproved (details : TransferDetails) (approvedBy : Actor)
+  | transferCompleted
+  | transferFailed (reason : String)
+deriving DecidableEq, Repr
+
+inductive TransferRejection where
+  | alreadyRequested
+  | sameAccount
+  | notPermitted
+  | notAwaitingApproval
+deriving DecidableEq, Repr
+
+inductive TransferState where
+  | new
+  | awaitingApproval (details : TransferDetails)
+  | pending (details : TransferDetails)
+  | completed
+  | failed (reason : String)
+deriving DecidableEq, Repr
+
+def decideTransfer (ctx : Context Actor) (s : TransferState) :
+    TransferCommand → Except TransferRejection (List TransferEvent)
+  | .request c =>
+    match s with
+    | .new =>
+      if c.source = c.destination then .error .sameAccount
+      else
+        .ok [.transferRequested ⟨c.source, c.destination, c.amount, ctx.actor⟩
+          (decide (c.amount ≥ approvalThreshold))]
+    | _ => .error .alreadyRequested
+  | .approve _ =>
+    match ctx.actor with
+    | .agent _ =>
+      match s with
+      | .awaitingApproval details => .ok [.transferApproved details ctx.actor]
+      | _ => .error .notAwaitingApproval
+    | _ => .error .notPermitted
+  | .expire _ =>
+    match s with
+    | .awaitingApproval _ => .ok [.transferFailed "not approved in time"]
+    | _ => .ok []
+  | .complete _ =>
+    match s with
+    | .pending _ => .ok [.transferCompleted]
+    | _ => .ok []
+  | .fail c =>
+    match s with
+    | .pending _ => .ok [.transferFailed c.reason]
+    | _ => .ok []
+
+def evolveTransfer (_ : TransferState) (e : TransferEvent) (_ : Time) : TransferState :=
+  match e with
+  | .transferRequested details needsApproval =>
+    if needsApproval then .awaitingApproval details else .pending details
+  | .transferApproved details _ => .pending details
+  | .transferCompleted => .completed
+  | .transferFailed reason => .failed reason
+
+/--
+A transfer between two accounts. Large transfers wait for approval until their
+window closes; approval and expiry are commands on this one instance, so exactly
+one of them wins.
+-/
+abbrev Transfer : Aggregate where
+  name := "Transfer"
+  Id := TransferId
+  State := TransferState
+  Command := TransferCommand
+  Event := TransferEvent
+  Rejection := TransferRejection
+  Actor := Actor
+  initial := .new
+  keyOf
+    | .request c => c.transferId
+    | .approve c => c.transferId
+    | .expire c => c.transferId
+    | .complete c => c.transferId
+    | .fail c => c.transferId
+  decide := decideTransfer
+  evolve := evolveTransfer
+
+/-! ## Rules -/
+
+/-- Whether a transfer has ended. -/
+def Ended : TransferState → Prop
+  | .completed | .failed _ => True
+  | _ => False
+
+/-- A transfer that ended stays as it ended: nothing completes a failed one, or fails a completed one. -/
+theorem anEndedTransferStaysAsItEnded :
+    Transfer.Transition fun _ before _ after => Ended before → after = before := by
+  intro ctx s c es eq ended
+  cases s <;> cases c <;> grind [decideTransfer, evolveTransfer, Aggregate.apply, Ended]
+
+/-- A transfer moves between two different accounts. -/
+def BetweenTwoAccounts : TransferState → Prop
+  | .awaitingApproval details | .pending details => details.source ≠ details.destination
+  | _ => True
+
+/-- No command a transfer accepts makes it a transfer from an account to itself. -/
+theorem betweenTwoAccounts_kept : Transfer.Keeps BetweenTwoAccounts := by
+  intro ctx s c es h eq
+  cases s <;> cases c <;>
+    grind [decideTransfer, evolveTransfer, Aggregate.apply, BetweenTwoAccounts]
+
+def betweenTwoAccounts : Aggregate.Invariant Transfer where
+  name := "BetweenTwoAccounts"
+  holds := BetweenTwoAccounts
+  initially := trivial
+  kept := betweenTwoAccounts_kept
+
+/-- Only an agent approves a transfer. -/
+theorem onlyAnAgentApproves :
+    Transfer.Transition fun ctx before _ after =>
+      ∀ details, before = .awaitingApproval details → after = .pending details →
+        ∃ agentId, ctx.actor = .agent agentId := by
+  intro ctx s c es eq
+  cases s <;> cases c <;> grind [decideTransfer, evolveTransfer, Aggregate.apply]
+
+/-- Approval and expiry race, and exactly one wins: once expired, approval is refused. -/
+theorem expiryBeatsALateApproval (ctx ctx' : Context Actor) (details : TransferDetails)
+    (expire : ExpireTransfer) (approve : ApproveTransfer) :
+    let expired := Transfer.step ctx (.awaitingApproval details) (.expire expire)
+    (∃ r, Transfer.decide ctx' expired (.approve approve) = .error r) := by
+  cases h : ctx'.actor <;> simp [Aggregate.step, decideTransfer, evolveTransfer, Aggregate.apply, h]
+
+/-- No transfer waits for ever: one that waits for approval can always be expired, whoever asks. -/
+theorem anUnapprovedTransferCanAlwaysExpire (ctx : Context Actor) (details : TransferDetails)
+    (expire : ExpireTransfer) :
+    Transfer.step ctx (.awaitingApproval details) (.expire expire)
+      = .failed "not approved in time" := by
+  simp [Aggregate.step, decideTransfer, evolveTransfer, Aggregate.apply]
+
+end Bank
diff --git a/packages/alchemy-lean/examples/Bank/Types.lean b/packages/alchemy-lean/examples/Bank/Types.lean
new file mode 100644
index 00000000000..9c0e564356c
--- /dev/null
+++ b/packages/alchemy-lean/examples/Bank/Types.lean
@@ -0,0 +1,25 @@
+import Alchemy
+
+namespace Bank
+
+abbrev AccountId := String
+abbrev CustomerId := String
+abbrev TransferId := String
+abbrev Username := String
+/-- Money, in cents. It cannot be negative, so no balance is ever overdrawn. -/
+abbrev Cents := Nat
+
+/-- Who is acting. -/
+inductive Actor where
+  | customer (customerId : CustomerId)
+  | agent (agentId : String)
+  | system (name : String)
+deriving DecidableEq, Repr
+
+/-- The day a moment falls on. Time is counted in seconds. -/
+def dayOf (time : Alchemy.Time) : Nat := time / 86400
+
+/-- The account opened for a customer when they register. -/
+def mainAccountId (customerId : CustomerId) : AccountId := customerId ++ "-main"
+
+end Bank
diff --git a/packages/alchemy-lean/examples/Bank/Views.lean b/packages/alchemy-lean/examples/Bank/Views.lean
new file mode 100644
index 00000000000..9fb77752ec9
--- /dev/null
+++ b/packages/alchemy-lean/examples/Bank/Views.lean
@@ -0,0 +1,316 @@
+import Alchemy
+import Bank.Shape
+
+open Alchemy
+
+namespace Bank
+
+abbrev Recorded' := Emitted BankAggregates
+
+/-- Customers read what is theirs; agents read anything. Nobody owns what nobody opened. -/
+def mustOwn (actor : Actor) (owner : Option CustomerId) : Except AccountRejection Unit :=
+  match actor, owner with
+  | .agent _, _ => .ok ()
+  | _, none => .ok ()
+  | .customer customerId, some owner => if customerId = owner then .ok () else .error .notOwner
+  | _, some _ => .error .notOwner
+
+/-! ## AccountSummary -/
+
+structure Summary where
+  customerId : Option CustomerId := none
+  owner : Option String := none
+  balance : Cents := 0
+  frozen : Bool := false
+  closed : Bool := false
+deriving DecidableEq, Repr
+
+def summarize (v : Summary) : AccountEvent → Summary
+  | .accountOpened customerId owner => { v with customerId := some customerId, owner := some owner }
+  | .ownerChanged _ customerId _ => { v with customerId := some customerId }
+  | .moneyDeposited _ balance => { v with balance }
+  | .moneyWithdrawn _ balance => { v with balance }
+  | .transferDebited _ _ balance => { v with balance }
+  | .transferCredited _ _ balance => { v with balance }
+  | .transferRefunded _ _ balance => { v with balance }
+  | .settlementReceived _ _ balance => { v with balance }
+  | .accountFrozen .. => { v with frozen := true }
+  | .accountClosed => { v with closed := true }
+  | _ => v
+
+/-- An account at a glance. Its owner and agents read it. -/
+def AccountSummary : View BankAggregates where
+  name := "AccountSummary"
+  Key := AccountId
+  State := Summary
+  Event := Empty
+  Actor := Actor
+  Rejection := AccountRejection
+  initial := {}
+  on
+    | _, ⟨.account, id, event, _, _⟩ => [{ key := id, evolve := fun v => summarize v event }]
+    | _, _ => []
+  validate := fun actor _ summary => mustOwn actor summary.customerId
+
+/-! ## Statement -/
+
+inductive LineKind where
+  | deposit | withdrawal | transferIn | transferOut | refund | settlement
+deriving DecidableEq, Repr
+
+structure StatementLine where
+  kind : LineKind
+  amount : Cents
+  balance : Cents
+deriving DecidableEq, Repr
+
+def lineOf : AccountEvent → List StatementLine
+  | .moneyDeposited amount balance => [⟨.deposit, amount, balance⟩]
+  | .moneyWithdrawn amount balance => [⟨.withdrawal, amount, balance⟩]
+  | .transferCredited _ amount balance => [⟨.transferIn, amount, balance⟩]
+  | .transferDebited _ amount balance => [⟨.transferOut, amount, balance⟩]
+  | .transferRefunded _ amount balance => [⟨.refund, amount, balance⟩]
+  | .settlementReceived _ amount balance => [⟨.settlement, amount, balance⟩]
+  | _ => []
+
+def ownerAfter (owner : Option CustomerId) : AccountEvent → Option CustomerId
+  | .accountOpened customerId _ => some customerId
+  | .ownerChanged _ customerId _ => some customerId
+  | _ => owner
+
+/-- An account's money events as statement lines. -/
+def Statement : View BankAggregates where
+  name := "Statement"
+  Key := AccountId
+  State := Option CustomerId
+  Event := StatementLine
+  Actor := Actor
+  Rejection := AccountRejection
+  initial := none
+  on
+    | _, ⟨.account, id, event, _, _⟩ =>
+      [{ key := id, evolve := fun owner => ownerAfter owner event, emit := fun _ _ => lineOf event }]
+    | _, _ => []
+  validate := fun actor _ owner => mustOwn actor owner
+
+/-! ## AccountActivity -/
+
+def activityOf : AccountEvent → List AccountEvent
+  | e@(.accountFrozen ..) | e@(.accountClosed) | e@(.ownerChanged ..) | e@(.refundStranded ..)
+  | e@(.settlementOnClosedAccount ..) => [e]
+  | _ => []
+
+/-- What support needs to see about an account. Agents only. -/
+def AccountActivity : View BankAggregates where
+  name := "AccountActivity"
+  Key := AccountId
+  State := Unit
+  Event := AccountEvent
+  Actor := Actor
+  Rejection := String
+  initial := ()
+  on
+    | _, ⟨.account, id, event, _, _⟩ =>
+      [{ key := id, evolve := fun u => u, emit := fun _ _ => activityOf event }]
+    | _, _ => []
+  validate := fun actor _ _ =>
+    match actor with
+    | .agent _ => .ok ()
+    | _ => .error "account activity is for agents"
+
+/-! ## CustomerDashboard -/
+
+structure Dashboard where
+  name : Option String := none
+  balances : List (AccountId × Cents) := []
+deriving DecidableEq, Repr
+
+def Dashboard.without (d : Dashboard) (id : AccountId) : Dashboard :=
+  { d with balances := d.balances.filter (·.1 ≠ id) }
+
+def Dashboard.withBalance (d : Dashboard) (id : AccountId) (balance : Cents) : Dashboard :=
+  { d with balances := (d.without id).balances ++ [(id, balance)] }
+
+def Dashboard.totalBalance (d : Dashboard) : Cents :=
+  (d.balances.map (·.2)).sum
+
+/--
+A customer's accounts and balances, built from the customer's events and from
+AccountSummary after each account event. An ownership change moves the account
+between dashboards.
+-/
+def CustomerDashboard : View BankAggregates where
+  name := "CustomerDashboard"
+  Key := CustomerId
+  State := Dashboard
+  Event := Empty
+  Actor := Actor
+  Rejection := String
+  initial := {}
+  on
+    | _, ⟨.customer, id, .customerRegistered name _, _, _⟩ =>
+      [{ key := id, evolve := fun d => { d with name := some name } }]
+    | history, e@⟨.account, id, event, _, _⟩ =>
+      let summary := AccountSummary.stateAt (history ++ [e]) id
+      match event, summary.customerId with
+      | .ownerChanged previous current _, _ =>
+        [ { key := previous, evolve := fun d => d.without id },
+          { key := current, evolve := fun d => d.withBalance id summary.balance } ]
+      | _, some customerId =>
+        [{ key := customerId
+           evolve := fun d =>
+             if summary.closed then d.without id else d.withBalance id summary.balance }]
+      | _, none => []
+    | _, _ => []
+  validate := fun actor key _ =>
+    match actor with
+    | .agent _ => .ok ()
+    | .customer customerId =>
+      if customerId = key then .ok () else .error "that is not your dashboard"
+    | _ => .error "that is not your dashboard"
+
+/-! ## TransferStatus -/
+
+structure Status where
+  source : Option AccountId := none
+  destination : Option AccountId := none
+  amount : Option Cents := none
+  requestedBy : Option Actor := none
+  awaitingApproval : Bool := false
+  debited : Bool := false
+  credited : Bool := false
+  refunded : Bool := false
+  completedAt : Option Time := none
+  failedReason : Option String := none
+deriving DecidableEq, Repr
+
+inductive Progress where
+  | completed | failed | inFlight | awaitingApproval | pending
+deriving DecidableEq, Repr
+
+def Status.progress (v : Status) : Progress :=
+  if v.completedAt.isSome then .completed
+  else if v.failedReason.isSome then .failed
+  else if v.debited then .inFlight
+  else if v.awaitingApproval then .awaitingApproval
+  else .pending
+
+/-- Where a transfer stands, from the transfer's events and both accounts'. -/
+def TransferStatus : View BankAggregates where
+  name := "TransferStatus"
+  Key := TransferId
+  State := Status
+  Event := Empty
+  Actor := Actor
+  Rejection := AccountRejection
+  initial := {}
+  on
+    | _, ⟨.transfer, id, event, _, time⟩ =>
+      [{ key := id
+         evolve := fun v =>
+           match event with
+           | .transferRequested details needsApproval =>
+             { v with
+               source := some details.source, destination := some details.destination,
+               amount := some details.amount, requestedBy := some details.requestedBy,
+               awaitingApproval := needsApproval }
+           | .transferApproved .. => { v with awaitingApproval := false }
+           | .transferCompleted => { v with completedAt := some time }
+           | .transferFailed reason =>
+             { v with awaitingApproval := false, failedReason := some reason } }]
+    | _, ⟨.account, _, .transferDebited id _ _, _, _⟩ =>
+      [{ key := id, evolve := fun v => { v with debited := true } }]
+    | _, ⟨.account, _, .transferCredited id _ _, _, _⟩ =>
+      [{ key := id, evolve := fun v => { v with credited := true } }]
+    | _, ⟨.account, _, .transferRefunded id _ _, _, _⟩ =>
+      [{ key := id, evolve := fun v => { v with refunded := true } }]
+    | _, _ => []
+  validate := fun actor _ status =>
+    match actor, status.requestedBy with
+    | .agent _, _ => .ok ()
+    | _, none => .ok ()
+    | .customer customerId, some (.customer requester) =>
+      if customerId = requester then .ok () else .error .notOwner
+    | _, _ => .error .notOwner
+
+/-! ## AccountTransfers -/
+
+inductive Direction where
+  | incoming | outgoing
+deriving DecidableEq, Repr
+
+structure TransferMoved where
+  transferId : TransferId
+  amount : Cents
+  direction : Direction
+deriving DecidableEq, Repr
+
+/-- The transfers in and out of an account: one transfer shows on both accounts. -/
+def AccountTransfers : View BankAggregates where
+  name := "AccountTransfers"
+  Key := AccountId
+  State := Option CustomerId
+  Event := TransferMoved
+  Actor := Actor
+  Rejection := AccountRejection
+  initial := none
+  on
+    | _, ⟨.account, id, event, _, _⟩ =>
+      [{ key := id, evolve := fun owner => ownerAfter owner event }]
+    | _, ⟨.transfer, id, .transferRequested details _, _, _⟩ =>
+      [ { key := details.source, evolve := fun owner => owner,
+          emit := fun _ _ => [⟨id, details.amount, .outgoing⟩] },
+        { key := details.destination, evolve := fun owner => owner,
+          emit := fun _ _ => [⟨id, details.amount, .incoming⟩] } ]
+    | _, _ => []
+  validate := fun actor _ owner => mustOwn actor owner
+
+/-! ## DailyOutflow -/
+
+/-- Daily outflow above which an account's activity is reviewed, in cents. -/
+def reviewThreshold : Cents := 50000
+
+structure Outflow where
+  day : Nat := 0
+  total : Cents := 0
+deriving DecidableEq, Repr
+
+/-- An account's money out today crossed the review threshold. -/
+structure DailyOutflowExceeded where
+  day : Nat
+  total : Cents
+deriving DecidableEq, Repr
+
+def Outflow.add (s : Outflow) (amount : Cents) (time : Time) : Outflow :=
+  { day := dayOf time, total := (if s.day = dayOf time then s.total else 0) + amount }
+
+def crossed (before after : Outflow) : List DailyOutflowExceeded :=
+  if before.total < reviewThreshold ∧ after.total ≥ reviewThreshold then
+    [⟨after.day, after.total⟩]
+  else []
+
+def outflowOf : AccountEvent → Option Cents
+  | .moneyWithdrawn amount _ => some amount
+  | .transferDebited _ amount _ => some amount
+  | _ => none
+
+/--
+Money out of an account per day. It emits an event when the day's total crosses
+the threshold, so split withdrawals are caught too.
+-/
+def DailyOutflow : View BankAggregates where
+  name := "DailyOutflow"
+  Key := AccountId
+  State := Outflow
+  Event := DailyOutflowExceeded
+  Actor := Actor
+  Rejection := Empty
+  initial := {}
+  on
+    | _, ⟨.account, id, event, _, time⟩ =>
+      match outflowOf event with
+      | some amount => [{ key := id, evolve := fun s => s.add amount time, emit := crossed }]
+      | none => []
+    | _, _ => []
+
+end Bank
diff --git a/packages/alchemy-lean/examples/Bank/Web.lean b/packages/alchemy-lean/examples/Bank/Web.lean
new file mode 100644
index 00000000000..84f8bdf3adb
--- /dev/null
+++ b/packages/alchemy-lean/examples/Bank/Web.lean
@@ -0,0 +1,134 @@
+import Alchemy
+import Bank.Server
+
+/-!
+The bank's pages. Each page is a function of the bank and of who is looking,
+through the same guarded views the Api serves; each form sends a command through
+the same Apis. `/app?as=customer:c-1` is a customer's page, `/app?as=agent:support-7`
+an agent's. A page stays live: it loads again when anything is recorded.
+-/
+
+open Alchemy
+open Alchemy.Html
+
+namespace Bank
+
+def actorText : Actor → String
+  | .customer id => s!"customer:{id}"
+  | .agent id => s!"agent:{id}"
+  | .system name => s!"system:{name}"
+
+def money (cents : Cents) : String :=
+  let pennies := cents % 100
+  s!"{cents / 100}.{if pennies < 10 then "0" else ""}{pennies}"
+
+def lineKind : LineKind → String
+  | .deposit => "deposit" | .withdrawal => "withdrawal" | .transferIn => "transfer in"
+  | .transferOut => "transfer out" | .refund => "refund" | .settlement => "settlement"
+
+def progressText : Progress → String
+  | .completed => "completed" | .failed => "failed" | .inFlight => "in flight"
+  | .awaitingApproval => "awaiting approval" | .pending => "pending"
+
+/-- A form that sends a command as this actor. -/
+def commandForm (actor : Actor) (type : String) (fixed : List (String × String))
+    (inputs : List (String × String)) (button : String) : Html :=
+  form "/app" (("as", actorText actor) :: ("type", type) :: fixed) inputs button
+
+/-- One account, as its owner or an agent sees it. -/
+def accountSection (actor : Actor) (w : World BankSignature) (id : AccountId) : List Html :=
+  match AccountSummary.read actor w.log id with
+  | .error _ => [h2 id, p [.text "You may not see this account."]]
+  | .ok (summary : Summary) =>
+    let lines : List StatementLine := Statement.emittedAt w.log id
+    let moved : List TransferMoved := AccountTransfers.emittedAt w.log id
+    [ h2 s!"Account {id}",
+      p [.text s!"Balance {money summary.balance}"
+        , .text (if summary.frozen then " · frozen" else "")
+        , .text (if summary.closed then " · closed" else "")],
+      commandForm actor "DepositMoney" [("accountId", id)] [("amount", "cents")] "Deposit",
+      commandForm actor "WithdrawMoney" [("accountId", id)] [("amount", "cents")] "Withdraw",
+      commandForm actor "RequestTransfer" [("from", id)]
+        [("transferId", "transfer id"), ("to", "to account"), ("amount", "cents")] "Transfer",
+      commandForm actor "CloseAccount" [("accountId", id)] [] "Close",
+      table ["Statement", "Amount", "Balance"]
+        (lines.map fun line => [lineKind line.kind, money line.amount, money line.balance]),
+      table ["Transfer", "Direction", "Amount", "Status"]
+        (moved.map fun m =>
+          [m.transferId, (if m.direction = .incoming then "in" else "out"), money m.amount,
+            progressText (TransferStatus.stateAt w.log m.transferId).progress]) ]
+
+/-- The page for whoever is looking, with what the last command answered. -/
+def view (actor : Actor) (note : Option String) (w : World BankSignature) : String :=
+  let noted := match note with
+    | some words => [Html.element "p" [("class", "note")] [.text words]]
+    | none => []
+  match actor with
+  | .customer id =>
+    let dashboard : Dashboard := CustomerDashboard.stateAt w.log id
+    Html.page "Bank" ([h1 "Bank"] ++ noted ++
+      (match dashboard.name with
+        | some name =>
+          [p [.text s!"{name}, your accounts hold {money dashboard.totalBalance}."]] ++
+            (dashboard.balances.flatMap fun (account, _) => accountSection actor w account)
+        | none =>
+          [p [.text "You are not registered yet."],
+            commandForm actor "RegisterCustomer" [("customerId", id)]
+              [("name", "name"), ("username", "username")] "Register"]) ++
+      [p [link "/app?as=agent:support-7" "Look as a support agent"], live "/version"])
+  | _ =>
+    let waiting := (w.toRecorded.ids .transfer).filter fun id =>
+      w.state .transfer id matches .awaitingApproval _
+    let accounts := w.toRecorded.ids .account
+    Html.page "Bank: support" ([h1 "Bank: support"] ++ noted ++
+      [h2 "Transfers waiting for approval",
+        table ["Transfer"] (waiting.map fun id => [id])] ++
+      (waiting.map fun id =>
+        commandForm actor "ApproveTransfer" [("transferId", id)] [] s!"Approve {id}") ++
+      [h2 "Accounts",
+        table ["Account", "Owner", "Balance", "Frozen", "Closed"]
+          (accounts.map fun id =>
+            let s : Summary := AccountSummary.stateAt w.log id
+            [id, s.owner.getD "", money s.balance, toString s.frozen, toString s.closed])] ++
+      (accounts.map fun id =>
+        commandForm actor "FreezeAccount" [("accountId", id)] [("reason", "reason")] s!"Freeze {id}")
+      ++ [live "/version"])
+
+/-- The command a posted form asks for: the same commands the Api takes as JSON. -/
+def formCommand (body : String) : Option (Actor × Asked) :=
+  asked (Lean.Json.mkObj ((fields body).map fun (k, v) =>
+    (k, if k = "amount" then (match v.toNat? with | some n => (n : Lean.Json) | none => v) else v)))
+
+/-- What the command did, in a sentence. -/
+def said (reply : Reply) : String :=
+  if reply.status = 200 then "Done." else s!"Refused: {reply.body}"
+
+/-- The pages' routes, over the Api's. -/
+def routeWithPages (method path body : String) : Routed Bank :=
+  let (base, query) :=
+    match path.splitOn "?" with
+    | [p, q] => (p, q)
+    | _ => (path, "")
+  if base = "/version" then
+    -- How much has been recorded: a page that watches this stays live.
+    .read fun w => { type := "text/plain", body := toString w.log.length }
+  else if base = "/app" then
+    if method = "POST" then
+      match formCommand body with
+      | some (actor, what) =>
+        match command actor what with
+        | .move move respond => .move move fun before after =>
+          { type := "text/html", body := view actor (some (said (respond before after))) after }
+        | .refuse reply => .read fun w => { type := "text/html", body := view actor (some (said reply)) w }
+        | .read _ => .refuse (refused 400 "not a command")
+      | none => .refuse (refused 400 "not a command")
+    else
+      match ((fields query).lookup "as").bind actorOf with
+      | some actor => .read fun w => { type := "text/html", body := view actor none w }
+      | none => .read fun w => { type := "text/html", body := view (.customer "c-1") none w }
+  else route method path body
+
+/-- The bank's server: its Api, its pages, and its stand-ins for the outside systems. -/
+def hostWithPages : Host Bank := { host with route := routeWithPages }
+
+end Bank
diff --git a/packages/alchemy-lean/examples/BankMain.lean b/packages/alchemy-lean/examples/BankMain.lean
new file mode 100644
index 00000000000..ca4ec920d71
--- /dev/null
+++ b/packages/alchemy-lean/examples/BankMain.lean
@@ -0,0 +1,10 @@
+import Bank.Web
+
+/--
+`lake exe bank [journal] [port] [public]`: serves the bank, kept in the journal
+file. With `public`, it listens on every address, as a container has to.
+-/
+def main (args : List String) : IO Unit :=
+  let journal := args.getD 0 "bank.journal"
+  let port := (args[1]?.bind String.toNat?).getD 8787
+  Bank.hostWithPages.serve journal port.toUInt16 (everyone := args[2]? == some "public")
diff --git a/packages/alchemy-lean/examples/Inbox.lean b/packages/alchemy-lean/examples/Inbox.lean
new file mode 100644
index 00000000000..bd5fa6f79db
--- /dev/null
+++ b/packages/alchemy-lean/examples/Inbox.lean
@@ -0,0 +1,196 @@
+import Alchemy
+
+/-!
+# An inbox, on Cloudflare Workers
+
+A Worker written as one `do` block: it consumes a queue, and ends with what it
+serves, a `fetch` handler and methods another Worker calls. Nobody lists its
+bindings: they are read off the calls in its code.
+-/
+
+open Alchemy Cloud Cloudflare
+
+namespace Inbox
+
+/-! ## What the Inbox Worker offers other Workers -/
+
+inductive Method where
+  | count
+  | read (id : Nat)
+deriving DecidableEq, Repr, Lean.ToJson, Lean.FromJson
+
+abbrev Api : Rpc where
+  Method := Method
+  Reply
+    | .count => Nat
+    | .read _ => Option String
+
+/-! ## The Workers -/
+
+/-- Stores a message under the next number. -/
+effect def store {role : Access Kind} (mail : Bucket) (message : String) : Run role Never Unit := do
+  let stored ← R2.list mail
+  R2.put mail (toString stored.length) message
+
+/--
+Accepts messages over HTTP and puts them on a queue; consumes the queue and
+stores each message; tells other Workers what is stored.
+-/
+def Inbox (mail : Bucket) (incoming : Queue) : Construct Kind (Worker Api) :=
+  Workers.Worker "Inbox" {} Api do
+    Queues.consume incoming fun message => store mail message
+
+    return {
+      fetch := fun request => do
+        match request.method, request.path with
+        | "POST", "/messages" =>
+          if request.body.isEmpty then return { status := 400, body := "a message needs a body" }
+          Queues.send incoming request.body
+          return { status := 202 }
+        | _, _ => return { status := 404 }
+      rpc := fun
+        | .count => return (← R2.list mail).length
+        | .read id => R2.get mail (toString id) }
+
+/-- A page that says what is in the inbox. It holds no data: it asks the Inbox. -/
+def Web (inbox : Worker Api) : Construct Kind (Worker .none) :=
+  Workers.Worker "Web" {} .none do
+    return {
+      fetch := fun request => do
+        match request.path with
+        | "/" =>
+          match ← (Workers.call inbox .count).result with
+          | .ok count => return { body := s!"{count} messages" }
+          | .error (_ : Workers.RpcError) => return { status := 502, body := "the inbox did not answer" }
+        | "/latest" =>
+          match ← (do
+              let count ← Workers.call inbox .count
+              Workers.call inbox (.read (count - 1))).result with
+          | .ok (some message) => return { body := message }
+          | .ok none => return { status := 404, body := "the inbox is empty" }
+          | .error (_ : Workers.RpcError) => return { status := 502, body := "the inbox did not answer" }
+        | _ => return { status := 404 } }
+
+/-! ## The stack -/
+
+structure Outputs where
+  inbox : Worker Api
+  web : Worker .none
+
+def InboxStack : Stack Kind Outputs where
+  name := "Inbox"
+  body := do
+    let mail ← R2.Bucket "Mail"
+    let incoming ← Queues.Queue "Incoming"
+    let inbox ← Inbox mail incoming
+    let web ← Web inbox
+    return { inbox, web }
+
+def prod : Graph Kind := InboxStack.graph "prod"
+
+def mail : Bucket := ⟨"Mail"⟩
+def incoming : Queue := ⟨"Incoming"⟩
+def inbox : Ref Kind.worker := ⟨"Inbox"⟩
+def web : Ref Kind.worker := ⟨"Web"⟩
+
+example : InboxStack.problem "prod" = none ∧ prod.deployable = true := by decide
+
+/-- The edges: the Inbox uses the bucket and the queue, and consumes the queue; the Web calls the Inbox. -/
+example : prod.edges = [
+    ("Inbox", "Mail"), ("Inbox", "Incoming"), ("Web", "Inbox")] := by decide
+
+/-! ## Tests of the stack, run in memory -/
+
+abbrev Test := List (Graph.Step Kind (InMemory prod))
+
+def post (body : String) : Incoming := .fetch { method := "POST", path := "/messages", body }
+def get (path : String) : Incoming := .fetch { path }
+
+def aMessage : Test := [
+  .request web (get "/") (responds { body := "0 messages" }),
+  .request web (get "/latest") (responds { status := 404, body := "the inbox is empty" }),
+  .request inbox (post "hello") (responds { status := 202 }),
+  .holds "the consumer stored it" (·.object mail "0" == some "hello"),
+  .request inbox (post "") (responds { status := 400, body := "a message needs a body" }),
+  .request inbox (post "again") (responds { status := 202 }),
+  .request web (get "/") (responds { body := "2 messages" }),
+  .request web (get "/latest") (responds { body := "again" }) ]
+
+example : prod.passes aMessage = true := by native_decide
+
+/-! ## What is proved about access -/
+
+/--
+Least privilege. No Worker holds a binding it does not need: for each one,
+there is a run in which that Worker makes a call only that binding permits.
+Bind something a Worker never uses and this fails.
+-/
+theorem leastPrivilege : prod.LeastPrivilege (InMemory prod) :=
+  .of_tests [aMessage] (by native_decide)
+
+/-- Only the Inbox can touch the mail, to read it or to write it. -/
+theorem onlyTheInboxTouchesTheMail :
+    prod.only [inbox] (R2.reading mail) ∧ prod.only [inbox] (R2.writing mail) := by
+  constructor <;> stack_rule in prod using [mail, inbox]
+
+/-- Nothing but the Web can call the Inbox, and nothing can call the Web. -/
+theorem whoCallsWhom :
+    prod.whoCan ⟨.worker, inbox, WorkerOp.call⟩ = ["Web"] ∧
+      prod.whoCan ⟨.worker, web, WorkerOp.call⟩ = [] := by
+  constructor <;> rfl
+
+/-! ## What the consumer does, for every message -/
+
+/--
+Given whatever mail is stored, when a message is consumed, then it is stored
+under the next number: one more than the mail already there.
+-/
+theorem aConsumedMessageIsStoredNext {role : Access Kind} [store.Needs role mail]
+    (message : String) (cloud : Memory) :
+    ((store (role := role) mail message).eval (InMemory prod) cloud).2.object mail
+        (toString (cloud.keys mail).length)
+      = some message := by
+  show (Run.eval (InMemory prod) (Run.bind _ _) cloud).2.object mail _ = _
+  rw [Run.eval_bind, R2.list_eval]
+  show (Run.eval (InMemory prod) (R2.put mail (toString (cloud.keys mail).length) message) cloud).2.object
+    mail _ = _
+  rw [R2.put_eval]
+  exact Memory.object_written cloud mail _ message
+
+/-! ## Deploying it -/
+
+/-- The first deploy creates everything, each resource after what it needs. -/
+example : plan Control.providers prod (⟨.empty, {}⟩ : Cloud.World Kind Control.Service).state = [
+    ("Mail", .create), ("Incoming", .create), ("Inbox", .create), ("Web", .create)] := by
+  native_decide
+
+/--
+Deploying this stack to a fresh account leaks nothing, whatever fails: every
+resource in the account is one the engine's state knows about. It is the same
+guarantee an AWS stack has, from the same engine.
+-/
+theorem deployLeaksNothing :
+    Tracked Control.lawful
+      (apply Control.providers Control.Service prod (⟨.empty, {}⟩ : Cloud.World Kind Control.Service)).1 :=
+  apply_tracked Control.lawful prod _ (by
+    intro y present
+    simp [Control.lawful] at present)
+
+/-- An account where somebody else already has the bucket's name. -/
+def nameTaken : Cloud.World Kind Control.Service :=
+  ⟨.empty, { taken := fun name => name == ⟨"Mail", 0⟩ }⟩
+
+/--
+There, the deploy fails at the bucket, and carries on with what does not need
+it: the queue exists. The state says the bucket is still to be created, so the
+next deploy picks it up, and nothing was leaked.
+-/
+example :
+    let after := apply Control.providers Control.Service prod nameTaken
+    after.2 = false ∧
+      after.1.cloud.exists_ ⟨.queue, "Incoming", 0⟩ = true ∧
+      after.1.cloud.exists_ ⟨.bucket, "Mail", 0⟩ = false ∧
+      (plan Control.providers prod after.1.state).head? = some ("Mail", .create) := by
+  native_decide
+
+end Inbox
diff --git a/packages/alchemy-lean/examples/InboxMain.lean b/packages/alchemy-lean/examples/InboxMain.lean
new file mode 100644
index 00000000000..d2652990eeb
--- /dev/null
+++ b/packages/alchemy-lean/examples/InboxMain.lean
@@ -0,0 +1,4 @@
+import Inbox
+
+/-- `lake exe inbox graph [stage] [--why]`, `lake exe inbox plan [stage]` -/
+def main (args : List String) : IO UInt32 := Alchemy.Cloudflare.cli Inbox.InboxStack args
diff --git a/packages/alchemy-lean/examples/Jobs.lean b/packages/alchemy-lean/examples/Jobs.lean
new file mode 100644
index 00000000000..f07d31ea91b
--- /dev/null
+++ b/packages/alchemy-lean/examples/Jobs.lean
@@ -0,0 +1,381 @@
+import Alchemy
+
+/-!
+# Jobs
+
+One program: the resources, the code that runs on them, and what is proved
+about both. An Api stores jobs in a bucket; every stored job is forwarded to a
+queue; a Worker takes jobs off the queue; an Auditor may list jobs and nothing
+else.
+-/
+
+open Alchemy Cloud AWS
+
+namespace Jobs
+
+/-! ## A service, and a layer that gives it -/
+
+/-- There is no job of this id. -/
+structure JobNotFound where
+  id : String
+deriving DecidableEq, Repr
+
+/-- Where jobs are kept. Code that uses it does not know where that is. -/
+structure JobStorage (access : Access Kind) where
+  put : String → String → Run access Never Unit
+  get : String → Run access JobNotFound String
+
+variable {R : Service Kind} {ε : Type}
+
+def putJob [Uses R JobStorage] (id content : String) : Effect R ε Unit :=
+  use JobStorage (·.put id content)
+
+def getJob [Uses R JobStorage] [Raises ε JobNotFound] (id : String) : Effect R ε String :=
+  use JobStorage (·.get id)
+
+/--
+Jobs kept as objects under `jobs/`. Built from the two S3 services it calls,
+so it needs what they need: read and write under that prefix. S3's error
+becomes the service's own.
+-/
+def JobStorageS3 (bucket : Bucket) : Layer Nothing JobStorage :=
+  .from (S3.GetObjectLive bucket ["jobs"] ++ S3.PutObjectLive bucket ["jobs"]) do
+    let objects ← S3.GetObject bucket ["jobs"]
+    let store ← S3.PutObject bucket ["jobs"]
+    return {
+      put := fun id content => store.call id content
+      get := fun id =>
+        (objects.call id).mapError fun
+          | S3.GetObjectError.noSuchKey _ => JobNotFound.mk id }
+
+/-! ## The functions -/
+
+/--
+Answers a request for a job. It names the service it needs, and no resource.
+It handles the one error it can meet, so its type says it cannot fail.
+-/
+def jobs [Uses R JobStorage] (request : Request) : Effect R Never Response := do
+  match request.method, request.path with
+  | .get, [id] =>
+    match ← (getJob id).result with
+    | .ok content => return { status := 200, body := content }
+    | .error (missing : JobNotFound) =>
+      return { status := 404, body := s!"Job {missing.id} not found" }
+  | .post, [id] =>
+    if request.body.isEmpty then return { status := 400, body := "Job content is required" }
+    putJob id request.body
+    return { status := 201, body := id }
+  | _, _ => return { status := 404, body := "Not found" }
+
+/-- How forwarding a stored job can fail. -/
+inductive ForwardError where
+  | notAJob (key : Path)
+  | missing (job : JobNotFound)
+deriving DecidableEq, Repr
+
+instance : Raises ForwardError JobNotFound := ⟨.missing⟩
+
+/-- Sends a stored job to the queue. -/
+def forward (queue : Queue) [Uses R JobStorage] [Uses R (SQS.SendMessage.Client queue)] (key : Path) :
+    Effect R ForwardError Unit := do
+  let some id := key.getLast? | throw (.notAJob key)
+  let content ← getJob id
+  SQS.sendMessageE queue content
+
+def Api (bucket : Bucket) (queue : Queue) : Construct Kind Function := do
+  let stage ← stage
+  Lambda.FunctionWith "Api" { url := true, memory := if stage = "prod" then 1024 else 512 } do
+    serve (JobStorageS3 bucket ++ SQS.SendMessageLive queue) jobs
+      [S3.onObjectCreated bucket (forward queue)]
+
+def Worker (queue : Queue) : Construct Kind Function :=
+  Lambda.FunctionWith "Worker" {} do
+    serve (SQS.ReceiveMessageLive queue) fun _ => do
+      match ← SQS.receiveMessage queue with
+      | some job => return { status := 200, body := job }
+      | none => return { status := 204 }
+
+def Auditor (bucket : Bucket) : Construct Kind Function :=
+  Lambda.FunctionWith "Auditor" {} do
+    serve (S3.ListObjectsLive bucket) fun _ => do
+      let keys ← S3.listObjects bucket
+      return { status := 200, body := toString keys.length }
+
+/-! ## The stack -/
+
+structure Outputs where
+  api : Function
+  worker : Function
+  auditor : Function
+
+def JobStack : Stack Kind Outputs where
+  name := "Jobs"
+  body := do
+    let stage ← stage
+    let bucket ← S3.Bucket "JobsBucket"
+    let queue ← SQS.Queue "JobsQueue" { visibilityTimeout := if stage = "prod" then 120 else 30 }
+    let api ← Api bucket queue
+    let worker ← Worker queue
+    let auditor ← Auditor bucket
+    return { api, worker, auditor }
+
+/-! ## The graph it builds -/
+
+def prod : Graph Kind := JobStack.graph "prod"
+
+def bucket : Bucket := ⟨"JobsBucket"⟩
+def queue : Queue := ⟨"JobsQueue"⟩
+def api : Function := ⟨"Api"⟩
+def worker : Function := ⟨"Worker"⟩
+def auditor : Function := ⟨"Auditor"⟩
+
+/-- The stack builds, and every resource it names exists. -/
+example : JobStack.problem "prod" = none ∧ prod.deployable = true := by decide
+
+/-- The resources, in an order they can be created in. -/
+example : prod.order = ["JobsBucket", "JobsQueue", "Api", "Worker", "Auditor"] := by decide
+
+/-- The edges: who needs what. -/
+example : prod.edges = [
+    ("Api", "JobsBucket"), ("Api", "JobsQueue"),
+    ("Worker", "JobsQueue"),
+    ("Auditor", "JobsBucket")] := by decide
+
+/-! ## What is proved about access -/
+
+/-- Only the Api can write an object, whatever the key. -/
+theorem onlyTheApiWrites : prod.only [api] (S3.writing bucket) := by
+  stack_rule in prod using [bucket, api]
+
+/-- And it can write nowhere but under `jobs/`. -/
+theorem theApiWritesOnlyJobs (key : Path) (elsewhere : ¬["jobs"] <+: key) :
+    prod.can "Api" ⟨.bucket, bucket, BucketOp.put key⟩ = false := by
+  have roles : prod.roles = computed% prod.roles := rfl
+  simp [Graph.can, roles, Access.permits, permitsOn, Kinds.covers, BucketOp.covers, bucket]
+  constructor
+  · intro same
+    cases same
+    exact elsewhere (List.prefix_refl _)
+  · cases prefixed : ["jobs"].isPrefixOf key with
+    | false => rfl
+    | true => exact absurd (List.isPrefixOf_iff_prefix.mp prefixed) elsewhere
+
+/-- Nothing but the Worker takes jobs off the queue. -/
+theorem onlyTheWorkerReceives : prod.only [worker] (SQS.receiving queue) := by
+  stack_rule in prod using [queue, worker]
+
+/-- The Auditor can count jobs, and can read none of them. -/
+theorem theAuditorReadsNothing : prod.never auditor (S3.reading bucket) := by
+  stack_rule in prod using [bucket, auditor]
+
+/-- No function can invoke another. -/
+theorem noFunctionInvokesAnother (target : Function) : prod.nobody (Lambda.invoking target) := by
+  stack_rule in prod
+
+/-! ## What is proved about the code -/
+
+/--
+Whatever the Api is asked, in whatever state the cloud is in, every call it
+makes is one its role allows. It holds for any host, because a call that the
+role does not permit does not type check.
+-/
+theorem theApiStaysInItsRole (request : Request) (memory : Memory) :
+    match prod.handler api request with
+    | some ⟨access, run⟩ => ∀ t ∈ (run.exec InMemory memory).attempts, access.permits t = true
+    | none => True := by
+  split
+  · exact Run.exec_permitted _ _ _
+  · trivial
+
+/-- The same code with jobs kept in memory of its own needs no access at all. -/
+def JobStorageNowhere : Layer Nothing JobStorage :=
+  .make fun _ => { put := fun _ _ => pure (), get := fun id => .fail ⟨id⟩ }
+
+example : JobStorageNowhere.needs = ∅ := rfl
+
+/-- And so makes no call, whatever it is asked. -/
+theorem jobsWithoutACloudTouchNothing (request : Request) (memory : Memory) :
+    (((jobs request).provide JobStorageNowhere).exec InMemory memory).attempts = [] := by
+  have permitted := Effect.provide_permitted InMemory (jobs request) JobStorageNowhere memory
+  cases attempts : (((jobs request).provide JobStorageNowhere).exec InMemory memory).attempts with
+  | nil => rfl
+  | cons t _ =>
+    have := permitted t (by rw [attempts]; exact List.mem_cons_self)
+    simp [JobStorageNowhere, Layer.make] at this
+
+/-! ## Layers that ask for their dependencies
+
+`JobStorageS3` brings its own S3 clients. A layer can instead ask for them, and
+be given them where the application is wired, so two services that read the same
+objects share one client.
+-/
+
+section Shared
+variable {In : Service Kind}
+
+/-- Jobs kept as objects, on whatever S3 clients it is given. -/
+def JobStorageOnS3 (bucket : Bucket) [Uses In (S3.GetObject.Client bucket ["jobs"])]
+    [Uses In (S3.PutObject.Client bucket ["jobs"])] : Layer In JobStorage :=
+  .make do
+    let objects ← S3.GetObject bucket ["jobs"]
+    let store ← S3.PutObject bucket ["jobs"]
+    return {
+      put := fun id content => store.call id content
+      get := fun id =>
+        (objects.call id).mapError fun
+          | S3.GetObjectError.noSuchKey _ => JobNotFound.mk id }
+
+/-- Whether a job exists. -/
+structure JobIndex (access : Access Kind) where
+  has : String → Run access Never Bool
+
+/-- Answered from the same objects. -/
+def JobIndexOnS3 (bucket : Bucket) [Uses In (S3.GetObject.Client bucket ["jobs"])] :
+    Layer In JobIndex :=
+  .make do
+    let objects ← S3.GetObject bucket ["jobs"]
+    return { has := fun id => do
+      match ← (objects.call id).result with
+      | .ok _ => return true
+      | .error (_ : S3.GetObjectError) => return false }
+
+/-- Both services, with S3 provided once. -/
+def JobServices (bucket : Bucket) : Layer Nothing (Both JobStorage JobIndex) :=
+  (JobStorageOnS3 bucket ++ JobIndexOnS3 bucket).provide
+    (S3.GetObjectLive bucket ["jobs"] ++ S3.PutObjectLive bucket ["jobs"])
+
+end Shared
+
+/-! ## Tests of the stack, run when this file compiles -/
+
+abbrev Test := List (Graph.Step Kind InMemory)
+
+def storingAJob : Test := [
+  .request api { method := .post, path := ["j-1"], body := "resize the logo" }
+    (responds { status := 201, body := "j-1" }),
+  .holds "the job is stored" (·.object bucket ["jobs", "j-1"] == some "resize the logo"),
+  .holds "and forwarded to the queue" (·.queued queue == ["resize the logo"]),
+  .request api { path := ["j-1"] } (responds { status := 200, body := "resize the logo" }),
+  .request api { path := ["j-2"] } (responds { status := 404, body := "Job j-2 not found" }) ]
+
+def workingAJob : Test := storingAJob ++ [
+  .request worker {} (responds { status := 200, body := "resize the logo" }),
+  .holds "the queue is empty" (·.queued queue == []),
+  .request worker {} (responds { status := 204 }) ]
+
+def auditing : Test := storingAJob ++ [
+  .request auditor {} (responds { status := 200, body := "1" }) ]
+
+example : prod.passes storingAJob = true := by native_decide
+example : prod.passes workingAJob = true := by native_decide
+example : prod.passes auditing = true := by native_decide
+
+/--
+Least privilege: no function holds a grant it does not need. For each one there
+is a run in which that function makes a call the grant is what permits. Give a
+function a grant it never uses and this fails.
+-/
+theorem leastPrivilege : prod.LeastPrivilege InMemory :=
+  .of_tests [workingAJob, auditing] (by native_decide)
+
+/-! ## Deploying it -/
+
+open Control in
+/-- An account with nothing in it, and an engine that has deployed nothing. -/
+def fresh : World Kind Service := ⟨.empty, {}⟩
+
+def deploy (g : Graph Kind) (w : World Kind Control.Service) : World Kind Control.Service × Bool :=
+  apply Control.providers Control.Service g w
+
+def planned (g : Graph Kind) (w : World Kind Control.Service) : List (String × Action) :=
+  plan Control.providers g w.state
+
+/-- The first deploy creates everything, each resource after what it needs. -/
+example : planned prod fresh = [
+    ("JobsBucket", .create), ("JobsQueue", .create),
+    ("Api", .create), ("Worker", .create), ("Auditor", .create)] := by native_decide
+
+/-- It succeeds, and deploying again has nothing to do. -/
+example : (deploy prod fresh).2 = true ∧
+    planned prod (deploy prod fresh).1 = [
+      ("JobsBucket", .noop), ("JobsQueue", .noop),
+      ("Api", .noop), ("Worker", .noop), ("Auditor", .noop)] := by native_decide
+
+/-- Moving from dev to prod changes the queue's timeout and the Api's memory in place. -/
+example : planned prod (deploy (JobStack.graph "dev") fresh).1 = [
+    ("JobsBucket", .noop), ("JobsQueue", .update),
+    ("Api", .update), ("Worker", .noop), ("Auditor", .noop)] := by native_decide
+
+/-- The same stack with a first-in-first-out queue and no Auditor. -/
+def Reworked : Stack Kind Unit where
+  name := "Jobs"
+  body := do
+    let bucket ← S3.Bucket "JobsBucket"
+    let queue ← SQS.Queue "JobsQueue" { fifo := true, visibilityTimeout := 120 }
+    let _ ← Api bucket queue
+    let _ ← Worker queue
+
+/-- A queue cannot become first-in-first-out, so it is replaced; the Auditor is deleted. -/
+example : planned (Reworked.graph "prod") (deploy prod fresh).1 = [
+    ("JobsBucket", .noop), ("JobsQueue", .replace), ("Api", .noop), ("Worker", .noop),
+    ("Auditor", .delete)] := by native_decide
+
+/-- After that deploy the old queue and the Auditor are gone from the account, and the new queue is there. -/
+example :
+    let after := (deploy (Reworked.graph "prod") (deploy prod fresh).1).1.cloud
+    (after.queues ⟨"JobsQueue", 0⟩).isNone ∧ (after.queues ⟨"JobsQueue", 1⟩).isSome ∧
+      (after.functions ⟨"Auditor", 0⟩).isNone := by native_decide
+
+/-- An account where somebody else already has the bucket's name. -/
+def nameTaken : World Kind Control.Service :=
+  ⟨.empty, { taken := fun name => name == ⟨"JobsBucket", 0⟩ }⟩
+
+/--
+The deploy fails at the bucket, but carries on with what does not need it
+directly: the queue exists. The state says the bucket is still being created, so
+the next deploy picks it up.
+-/
+example :
+    (deploy prod nameTaken).2 = false ∧
+      ((deploy prod nameTaken).1.cloud.queues ⟨"JobsQueue", 0⟩).isSome ∧
+      planned prod (deploy prod nameTaken).1 = [
+        ("JobsBucket", .create), ("JobsQueue", .noop),
+        ("Api", .noop), ("Worker", .noop), ("Auditor", .noop)] := by native_decide
+
+/-! ## What is proved about deploying it -/
+
+theorem fresh_tracked : Tracked Control.lawful fresh := by
+  intro y present
+  obtain ⟨_ | _ | _, id, generation⟩ := y <;>
+    simp [Control.lawful, Control.present, fresh] at present
+
+/--
+Deploying any graph to a fresh account leaks nothing, whatever fails and
+wherever it stops: every resource in the account is one the state knows about.
+-/
+theorem deployLeaksNothing (g : Graph Kind) : Tracked Control.lawful (deploy g fresh).1 :=
+  apply_tracked Control.lawful g fresh fresh_tracked
+
+/-- And so does every deploy after it, of any other graph. -/
+theorem redeployLeaksNothing (first second : Graph Kind) :
+    Tracked Control.lawful (deploy second (deploy first fresh).1).1 :=
+  apply_tracked Control.lawful second _ (deployLeaksNothing first)
+
+/--
+When a deploy of this stack succeeds, from any earlier deploy of anything, the
+account holds only this stack's resources.
+-/
+theorem deployLeavesOnlyTheStack (earlier : Graph Kind) (y : Physical Kind)
+    (ok : (deploy prod (deploy earlier fresh).1).2 = true)
+    (exists_ : Control.present y (deploy prod (deploy earlier fresh).1).1.cloud = true) :
+    y.id ∈ ["JobsBucket", "JobsQueue", "Api", "Worker", "Auditor"] := by
+  obtain ⟨node, found, _⟩ := apply_exact Control.lawful prod _ (deployLeaksNothing earlier)
+    (by decide) ok y exists_
+  have listed : y.id ∈ prod.ids := by
+    have mem := List.mem_of_find?_eq_some found
+    have id := find_id found
+    exact id ▸ List.mem_map_of_mem (f := Node.id) mem
+  have ids : prod.ids = ["JobsBucket", "JobsQueue", "Api", "Worker", "Auditor"] := by decide
+  rw [← ids]; exact listed
+
+end Jobs
diff --git a/packages/alchemy-lean/examples/Linked.lean b/packages/alchemy-lean/examples/Linked.lean
new file mode 100644
index 00000000000..6c66c204ebd
--- /dev/null
+++ b/packages/alchemy-lean/examples/Linked.lean
@@ -0,0 +1,357 @@
+import Accounts
+
+/-!
+# Two models, linked
+
+The bank calls a compliance check. Here that check is another domain model,
+with rules of its own, and a `Link` says how the bank's call becomes a command
+for it. Everything proved of each model alone holds of the two together.
+-/
+
+open Alchemy Cloud
+
+/-! ## The compliance model -/
+
+/-- Who sends compliance a command: the bank's systems, or a compliance officer. -/
+inductive Watch.Who where
+  | system
+  | officer (name : String)
+deriving DecidableEq, Repr, Inhabited
+
+derive_tokens Watch.Who
+
+aggregate Watch where
+  actor : Who
+
+  command
+    | assess (account : String) (amount : Nat)
+        records cleared, flagged
+        rejects nothingToAssess
+    | dismiss (account : String)
+        records dismissed
+        rejects notAnOfficer, nothingFlagged
+
+  event
+    | cleared (amount : Nat)
+    | flagged (amount : Nat)
+    | dismissed (by_ : String)
+
+  rejection
+    | nothingToAssess
+    | notAnOfficer
+    | nothingFlagged
+
+  -- what compliance knows about one account: how often it looked, and how often it objected
+  state
+    assessed : Nat := 0
+    flagged : Nat := 0
+
+  decide
+    | _, _, .assess _ amount =>
+      if amount = 0 then .error .nothingToAssess
+      else if amount ≥ 50000 then .ok [.flagged amount]
+      else .ok [.cleared amount]
+    | .officer name, s, .dismiss _ =>
+      if s.flagged = 0 then .error .nothingFlagged else .ok [.dismissed name]
+    | .system, _, .dismiss _ => .error .notAnOfficer
+
+  evolve
+    | s, .cleared _ => { s with assessed := s.assessed + 1 }
+    | s, .flagged _ => { assessed := s.assessed + 1, flagged := s.flagged + 1 }
+    | s, .dismissed _ => { s with flagged := s.flagged - 1 }
+
+model Compliance where
+  aggregate Watch
+
+namespace Compliance
+
+/-- Compliance never objects more often than it looked. -/
+def FlagsAreAssessments (s : Watch.State) : Prop := s.flagged ≤ s.assessed
+
+theorem flagsAreAssessments_kept : Watch.Keeps FlagsAreAssessments := by
+  aggregate_rule
+
+/-- Only an officer dismisses a flag: whatever the account holds, the bank's systems are refused. -/
+theorem onlyAnOfficerDismisses (account : String) (s : Watch.State) :
+    Watch.decide .system s (.dismiss account) = .error .notAnOfficer := by
+  simp [Watch.decide]
+
+theorem everyWatchIsSound (w : Alchemy.World Signature) (reach : Compliance.Reachable w)
+    (account : String) : FlagsAreAssessments (w.state .Watch account) :=
+  Watch.always (by simp [FlagsAreAssessments]) flagsAreAssessments_kept w reach account
+
+end Compliance
+
+/-! ## The link -/
+
+/-- The bank's screening call is answered by the compliance model. -/
+def screening : Link Bank Compliance where
+  ask
+    | .screen account amount => some ⟨.Watch, .system, .assess account amount⟩
+    | .wire .. => none
+  reply
+    | .screen .., ⟨.Watch, _, _⟩, .ok [.flagged _] => .flagged "over the reporting threshold"
+    | .screen .., _, _ => .clear
+    | .wire .., _, _ => .bounced
+
+/-! ## What holds of the two together -/
+
+/--
+In every world the bank and compliance can reach together: every account is
+balanced, no transfer has created money, and compliance never objected more
+often than it looked. Each was proved of one model alone; none is proved again.
+-/
+theorem bothAreSound (w : screening.Worlds) (reach : screening.Reachable w) (account : String) :
+    Bank.Balanced (w.1.state .Account account) ∧
+      Bank.Conserved w.1.toRecorded ∧
+      Compliance.FlagsAreAssessments (w.2.state .Watch account) :=
+  ⟨Bank.everyAccountBalanced _ (screening.reachable_left reach) account,
+    Bank.noTransferCreatesMoney _ (screening.reachable_left reach),
+    Compliance.everyWatchIsSound _ (screening.reachable_right reach) account⟩
+
+/-! ## Behaviour across both models
+
+These are about the two models together: what one does because of what the
+other answered. Each holds for every account and amount.
+-/
+
+/--
+Given an open account, when a deposit over the reporting threshold arrives,
+then compliance flags it and the bank freezes the account.
+-/
+theorem aReportableDepositFreezesTheAccount (id owner : String) (amount : Nat)
+    (reportable : amount ≥ 50000) :
+    let both := screening.run [
+      .send ⟨.Account, (), .open id owner⟩,
+      .send ⟨.Account, (), .deposit id amount⟩]
+    (both.1.state .Account id).status = .frozen "over the reporting threshold" ∧
+      both.2.state .Watch id = { assessed := 1, flagged := 1 } := by
+  behaviour [screening]
+
+/--
+Given an open account, when a large deposit under the reporting threshold
+arrives, then compliance looks at it, has no objection, and the account stays open.
+-/
+theorem aLargeDepositIsLookedAtAndLeftAlone (id owner : String) (amount : Nat)
+    (large : amount ≥ 10000) (unremarkable : amount < 50000) :
+    let both := screening.run [
+      .send ⟨.Account, (), .open id owner⟩,
+      .send ⟨.Account, (), .deposit id amount⟩]
+    (both.1.state .Account id).status = .open ∧
+      both.2.state .Watch id = { assessed := 1, flagged := 0 } := by
+  behaviour [screening]
+
+/--
+Given an open account, when a small deposit arrives, then compliance is never
+asked at all.
+-/
+theorem aSmallDepositIsNotScreened (id owner : String) (amount : Nat)
+    (some : amount ≠ 0) (small : amount < 10000) :
+    let both := screening.run [
+      .send ⟨.Account, (), .open id owner⟩,
+      .send ⟨.Account, (), .deposit id amount⟩]
+    (both.1.state .Account id).status = .open ∧ both.2.state .Watch id = {} := by
+  behaviour [screening]
+
+/-! ## A run of the two together -/
+
+/-- A large deposit: compliance flags it, and the bank freezes the account. -/
+def aLargeDeposit : screening.Worlds := screening.run [
+  .send ⟨.Account, (), .open "a-1" "Sam"⟩,
+  .send ⟨.Account, (), .deposit "a-1" 60000⟩ ]
+
+example : (aLargeDeposit.1.state .Account "a-1").status = .frozen "over the reporting threshold" ∧
+    aLargeDeposit.2.state .Watch "a-1" = { assessed := 1, flagged := 1 } := by
+  native_decide
+
+/-- A deposit compliance has no objection to: it looks, and the account stays open. -/
+def anOrdinaryLargeDeposit : screening.Worlds := screening.run [
+  .send ⟨.Account, (), .open "a-1" "Sam"⟩,
+  .send ⟨.Account, (), .deposit "a-1" 20000⟩ ]
+
+example : (anOrdinaryLargeDeposit.1.state .Account "a-1").status = .open ∧
+    anOrdinaryLargeDeposit.2.state .Watch "a-1" = { assessed := 1, flagged := 0 } := by
+  native_decide
+
+/-! ## Three models: a network
+
+The bank's wires are sent by a third model, the wire desk, with a rule of its
+own. A `Network` joins any number of models. Each model's theorems hold of all
+of them together, and a run goes through all three.
+-/
+
+/-- What names a wire: not a string, so a wire's id cannot be mistaken for an account's. -/
+structure WireId where
+  payout : String
+deriving DecidableEq, Repr, Lean.ToJson, Lean.FromJson
+
+derive_tokens WireId
+
+aggregate Transfer where
+  id : WireId
+
+  command
+    | send (wire : WireId) (account : String) (amount : Nat)
+        records sent
+        rejects alreadySent, tooLarge
+
+  event
+    | sent (account : String) (amount : Nat)
+
+  rejection
+    | alreadySent
+    | tooLarge
+
+  state
+    sent : Nat := 0
+    count : Nat := 0
+
+  decide
+    | s, .send _ account amount =>
+      if s.count ≠ 0 then .error .alreadySent
+      else if amount > 100000 then .error .tooLarge
+      else .ok [.sent account amount]
+
+  evolve
+    | s, .sent _ amount => { sent := s.sent + amount, count := s.count + 1 }
+
+model Wires where
+  aggregate Transfer
+
+namespace Wires
+
+/-- A wire is sent at most once, and never for more than the desk's limit. -/
+def SentOnce (s : Transfer.State) : Prop :=
+  (s.count = 0 → s.sent = 0) ∧ s.count ≤ 1 ∧ s.sent ≤ 100000
+
+theorem sentOnce_kept : Transfer.Keeps SentOnce := by aggregate_rule
+
+theorem everyWireSentOnce (w : Alchemy.World Signature) (reach : Wires.Reachable w)
+    (payout : WireId) : SentOnce (w.state .Transfer payout) :=
+  Transfer.always (by simp [SentOnce]) sentOnce_kept w reach payout
+
+/-- One step of the wire desk, when nothing is part-way through: an event is taken off the inbox. -/
+theorem step_idle {w w' : Alchemy.World Signature} (idle : w.fibers = [])
+    (step : Wires.stepOnce w = some w') : w'.fibers = [] ∧ w'.inbox.length < w.inbox.length := by
+  unfold Model.stepOnce at step
+  split at step
+  · next event rest inbox =>
+    cases step
+    simp [Model.react, idle, inbox]
+  · simp [idle, Model.tryFibers] at step
+
+/--
+The wire desk comes to rest. From any world with nothing part-way through, it
+stops within as many steps as there are events to deliver: a measure that every
+step lowers.
+-/
+theorem comesToRest (w : Alchemy.World Signature) (idle : w.fibers = []) :
+    Wires.AtRest (Wires.settle w.inbox.length w) :=
+  Wires.comesToRestWithin (fun w => w.fibers = []) (fun w => w.inbox.length)
+    (fun _ _ idle step => (step_idle idle step).1) (fun _ _ idle step => (step_idle idle step).2)
+    _ w idle (Nat.le_refl _)
+
+/-- So eventually the desk is at rest with every wire sent at most once. -/
+theorem eventuallyEveryWireSentOnce (w : Alchemy.World Signature) (reach : Wires.Reachable w)
+    (idle : w.fibers = []) (payout : WireId) :
+    Wires.Eventually w fun rested => SentOnce (rested.state .Transfer payout) :=
+  ⟨w.inbox.length, comesToRest w idle,
+    everyWireSentOnce _ (Wires.settle_reachable _ w reach) payout⟩
+
+end Wires
+
+/-- The three models. -/
+inductive Part where
+  | bank
+  | compliance
+  | wires
+deriving DecidableEq, Repr
+
+abbrev part : Part → Model
+  | .bank => Bank
+  | .compliance => Compliance
+  | .wires => Wires
+
+/-- The bank's screening goes to compliance, and its wires to the wire desk. -/
+def institution : Network Part part where
+  ask
+    | .bank, .screen account amount =>
+      some ⟨.compliance, ⟨.Watch, .system, .assess account amount⟩⟩
+    | .bank, .wire payout account amount =>
+      some ⟨.wires, ⟨.Transfer, (), .send ⟨payout⟩ account amount⟩⟩
+    | .compliance, call => nomatch call
+    | .wires, call => nomatch call
+  reply
+    | .bank, .screen .., .compliance, ⟨.Watch, _, _⟩, .ok [.flagged _] =>
+      .flagged "over the reporting threshold"
+    | .bank, .screen .., _, _, _ => .clear
+    | .bank, .wire .., .wires, ⟨.Transfer, _, _⟩, .ok _ => .sent
+    | .bank, .wire .., _, _, _ => .bounced
+    | .compliance, call, _, _, _ => nomatch call
+    | .wires, call, _, _, _ => nomatch call
+  offered := by intro i c j s _; cases j <;> trivial
+  parts := [.bank, .compliance, .wires]
+
+/--
+In every world the three can reach together: every account is balanced, no
+transfer has created money, compliance never objected more often than it
+looked, and every wire was sent at most once. Each was proved of one model
+alone; none is proved again.
+-/
+theorem allThreeAreSound (w : institution.Worlds) (reach : institution.Reachable w)
+    (account : String) (payout : WireId) :
+    Bank.Balanced ((w .bank).state .Account account) ∧
+      Bank.Conserved (w .bank).toRecorded ∧
+      Compliance.FlagsAreAssessments ((w .compliance).state .Watch account) ∧
+      Wires.SentOnce ((w .wires).state .Transfer payout) :=
+  ⟨Bank.everyAccountBalanced _ (institution.reachable_each reach .bank) account,
+    Bank.noTransferCreatesMoney _ (institution.reachable_each reach .bank),
+    Compliance.everyWatchIsSound _ (institution.reachable_each reach .compliance) account,
+    Wires.everyWireSentOnce _ (institution.reachable_each reach .wires) payout⟩
+
+/-- A payout through all three: the bank takes the money out, and the wire desk sends it. -/
+def aPayout : institution.Worlds := institution.run [
+  ⟨.bank, .send ⟨.Account, (), .open "a-1" "Sam"⟩⟩,
+  ⟨.bank, .send ⟨.Account, (), .deposit "a-1" 500⟩⟩,
+  ⟨.bank, .send ⟨.Account, (), .requestPayout "a-1" "p-1" 200⟩⟩ ]
+
+example : ((aPayout .bank).state .Account "a-1").balance = 300 ∧
+    (aPayout .bank).sagas (.Payout, "p-1") = .completed ∧
+    (aPayout .wires).state .Transfer ⟨"p-1"⟩ = { sent := 200, count := 1 } := by
+  native_decide
+
+/--
+A payout over the desk's limit: the wire desk refuses, and the bank puts the
+money back. The refund is itself a large deposit, so compliance screens it, and
+flags it: the account ends up frozen. Nobody wrote that down; it is what the
+three models do together.
+-/
+def aPayoutTooLarge : institution.Worlds := institution.run [
+  ⟨.bank, .send ⟨.Account, (), .open "a-1" "Sam"⟩⟩,
+  ⟨.bank, .send ⟨.Account, (), .deposit "a-1" 40000⟩⟩,
+  ⟨.bank, .send ⟨.Account, (), .deposit "a-1" 40000⟩⟩,
+  ⟨.bank, .send ⟨.Account, (), .deposit "a-1" 40000⟩⟩,
+  ⟨.bank, .send ⟨.Account, (), .requestPayout "a-1" "p-1" 110000⟩⟩ ]
+
+example : ((aPayoutTooLarge .bank).state .Account "a-1").balance = 120000 ∧
+    ((aPayoutTooLarge .bank).state .Account "a-1").status = .frozen "over the reporting threshold" ∧
+    (aPayoutTooLarge .bank).sagas (.Payout, "p-1") = .failed (.Payout .bounced) ∧
+    (aPayoutTooLarge .compliance).state .Watch "a-1" = { assessed := 4, flagged := 1 } ∧
+    (aPayoutTooLarge .wires).state .Transfer ⟨"p-1"⟩ = {} := by
+  native_decide
+
+/--
+The run above is one the network can reach, so everything proved of every
+reachable world holds of it, in whatever order its calls were answered.
+-/
+theorem thePayoutRunIsSound :
+    Bank.Balanced ((aPayout .bank).state .Account "a-1") ∧
+      Bank.Conserved (aPayout .bank).toRecorded ∧
+      Compliance.FlagsAreAssessments ((aPayout .compliance).state .Watch "a-1") ∧
+      Wires.SentOnce ((aPayout .wires).state .Transfer ⟨"p-1"⟩) :=
+  allThreeAreSound _
+    (institution.run_reachable _ (by
+      intro move mem
+      simp only [List.mem_cons, List.mem_nil_iff, or_false] at mem
+      rcases mem with rfl | rfl | rfl <;> trivial))
+    "a-1" ⟨"p-1"⟩
diff --git a/packages/alchemy-lean/examples/Loop.lean b/packages/alchemy-lean/examples/Loop.lean
new file mode 100644
index 00000000000..7f781cf390e
--- /dev/null
+++ b/packages/alchemy-lean/examples/Loop.lean
@@ -0,0 +1,43 @@
+import Alchemy
+
+/-!
+# A model that never comes to rest
+
+A counter whose policy reacts to every bump by bumping again. `comes_to_rest`
+refuses it, and says which event keeps feeding itself.
+-/
+
+open Alchemy
+
+aggregate Counter where
+  command
+    | bump (id : String)
+        records bumped
+
+  event
+    | bumped
+
+  rejection
+    | never
+
+  state
+    count : Nat := 0
+
+  decide
+    | _, .bump _ => .ok [.bumped]
+
+  evolve
+    | s, .bumped => { s with count := s.count + 1 }
+
+model Loop where
+  aggregate Counter
+
+  -- whenever the counter is bumped, bump it again
+  policy Again on Counter
+    | id, .bumped => Counter.send (.bump id)
+
+/--
+error: Loop may never come to rest: no weights hold together, because some reaction leads back to the event it reacts to. These kept growing: [Counter.Event.bumped]
+-/
+#guard_msgs in
+comes_to_rest Loop
diff --git a/packages/alchemy-lean/examples/Shop.lean b/packages/alchemy-lean/examples/Shop.lean
new file mode 100644
index 00000000000..1a1b6dc76c1
--- /dev/null
+++ b/packages/alchemy-lean/examples/Shop.lean
@@ -0,0 +1,792 @@
+import Alchemy
+
+/-!
+# A shop
+
+One program, end to end: a domain model, the stack that hosts it, the rules
+proved about both, and stories and tests the compiler runs.
+-/
+
+open Alchemy Cloud AWS
+
+/-! ## The domain -/
+
+inductive Order.Status where
+  | new
+  | awaitingPayment
+  | paid (charge : String)
+  | declined (reason : String)
+deriving DecidableEq, Repr
+
+aggregate Order where
+  command
+    | place (id item : String) (amount : Nat)
+        records placed
+        rejects alreadyPlaced, nothingToCharge
+    | settle (id charge : String)
+        records paid
+        rejects notAwaitingPayment
+    | decline (id reason : String)
+        records declined
+        rejects notAwaitingPayment
+
+  event
+    | placed (item : String) (amount : Nat)
+    | paid (charge item : String) (amount : Nat)
+    | declined (reason : String)
+
+  rejection
+    | alreadyPlaced
+    | nothingToCharge
+    | notAwaitingPayment
+
+  state
+    status : Status := .new
+    item : String := ""
+    amount : Nat := 0
+    charged : Nat := 0
+
+  decide
+    | s, .place _ item amount =>
+      if s.status ≠ .new then .error .alreadyPlaced
+      else if amount = 0 then .error .nothingToCharge
+      else .ok [.placed item amount]
+    | s, .settle _ charge =>
+      if s.status = .awaitingPayment then .ok [.paid charge s.item s.amount]
+      else .error .notAwaitingPayment
+    | s, .decline _ reason =>
+      if s.status = .awaitingPayment then .ok [.declined reason]
+      else .error .notAwaitingPayment
+
+  evolve
+    | s, .placed item amount => { s with status := .awaitingPayment, item, amount }
+    | s, .paid charge _ amount => { s with status := .paid charge, charged := s.charged + amount }
+    | s, .declined reason => { s with status := .declined reason }
+
+  -- what a caller is told: where the order stands once the command is applied
+  reply : Status
+    | s, _ => s.status
+
+aggregate Shipment where
+  command
+    | schedule (id item : String)
+        records scheduled
+        rejects alreadyScheduled
+
+  event
+    | scheduled (item : String)
+
+  rejection
+    | alreadyScheduled
+
+  state
+    item : Option String := none
+
+  decide
+    | s, .schedule _ item =>
+      if s.item.isSome then .error .alreadyScheduled else .ok [.scheduled item]
+
+  evolve
+    | s, .scheduled item => { s with item := some item }
+
+/-- What the payment gateway answers. -/
+inductive Charge where
+  | approved (id : String)
+  | refused (reason : String)
+deriving DecidableEq, Repr
+
+derive_tokens Charge
+
+model Shop where
+  aggregate Order
+  -- nobody asks for a shipment: one is scheduled because an order was paid
+  internal aggregate Shipment
+
+  call charge (order : String) (amount : Nat) : Charge
+  call ship (order item : String) : Unit
+
+  -- whenever an order is placed, charge for it, and record what the gateway said
+  policy Payment on Order
+    | id, .placed _ amount => do
+      match ← charge id amount with
+      | .approved chargeId => Order.send (.settle id chargeId)
+      | .refused reason => Order.send (.decline id reason)
+
+  -- whenever an order is paid, schedule its shipment: one aggregate tells another
+  policy Fulfilment on Order
+    | id, .paid _ item _ => Shipment.send (.schedule id item)
+
+  -- whenever a shipment is scheduled, have the warehouse ship it
+  policy Dispatch on Shipment
+    | id, .scheduled item => ship id item
+
+  view Revenue on Order : Nat := 0
+    | total, .paid _ _ amount => total + amount
+
+  projection Packing on Shipment : String × String
+    | id, .scheduled item => [(id, item)]
+
+namespace Shop
+
+/-! ## Behaviour, proved for every order
+
+Each of these reads like a story: given what was recorded, when a command
+arrives, then this happens. Unlike a story it holds for every id, item, amount
+and charge, not for the one case written down.
+-/
+
+/-- Given a new order, when it is placed for a price, then it is recorded as placed. -/
+theorem aNewOrderIsPlaced (id item : String) (amount : Nat) (priced : amount ≠ 0) :
+    Order.decide (Order.after []) (.place id item amount) = .ok [.placed item amount] := by
+  simp [Aggregate.after, Aggregate.apply, Order.decide, priced]
+
+/-- Given a placed order, when it is placed again, then it is refused. -/
+theorem anOrderIsPlacedOnce (id item again : String) (amount more : Nat) :
+    Order.decide (Order.after [.placed item amount]) (.place id again more)
+      = .error .alreadyPlaced := by
+  simp [Aggregate.after, Aggregate.apply, Order.decide, Order.evolve]
+
+/-- Given a placed order, when the gateway approves, then it is paid for exactly what it costs. -/
+theorem settlingChargesWhatTheOrderCosts (id item charge : String) (amount : Nat) :
+    Order.decide (Order.after [.placed item amount]) (.settle id charge)
+      = .ok [.paid charge item amount] := by
+  simp [Aggregate.after, Aggregate.apply, Order.decide, Order.evolve]
+
+/-- Given a paid order, when a second charge arrives, then it is refused. -/
+theorem aPaidOrderIsNeverChargedAgain (id item charge again : String) (amount : Nat) :
+    Order.decide (Order.after [.placed item amount, .paid charge item amount]) (.settle id again)
+      = .error .notAwaitingPayment := by
+  simp [Aggregate.after, Aggregate.apply, Order.decide, Order.evolve]
+
+/-- Given a declined order, when a charge arrives late, then it is refused. -/
+theorem aDeclinedOrderIsNeverCharged (id item reason charge : String) (amount : Nat) :
+    Order.decide (Order.after [.placed item amount, .declined reason]) (.settle id charge)
+      = .error .notAwaitingPayment := by
+  simp [Aggregate.after, Aggregate.apply, Order.decide, Order.evolve]
+
+/-! ## General properties
+
+Some facts are not about one scenario but about the shape of the aggregate.
+-/
+
+/--
+Every order command is idempotent: sent twice in a row, it leaves what it
+leaves sent once. So a caller who is not sure a command arrived can send it again.
+-/
+theorem everyOrderCommandIsIdempotent : Order.Idempotent := by
+  command_law
+
+theorem schedulingIsIdempotent : Shipment.Idempotent := by
+  command_law
+
+/-! ## Behaviour across the model
+
+The same shape, but the "when" is now a run of the whole shop: commands sent,
+policies reacting, and the outside systems answering.
+-/
+
+/--
+Given a new order, when it is placed and the gateway approves the charge, then
+it is paid and the warehouse is asked to ship it.
+-/
+theorem anApprovedOrderIsPaidAndShipped (id item charge : String) (amount : Nat)
+    (priced : amount ≠ 0) :
+    let shop := Shop.run [
+      .send ⟨.Order, (), .place id item amount⟩,
+      .answer (.charge id amount) (.approved charge)]
+    (shop.state .Order id).status = .paid charge ∧
+      (shop.state .Shipment id).item = some item ∧
+      Shop.waiting shop = [.ship id item] := by
+  behaviour
+
+/--
+Given a new order, when it is placed and the gateway refuses the charge, then
+it is declined and nothing is shipped.
+-/
+theorem aRefusedOrderIsDeclinedAndNotShipped (id item reason : String) (amount : Nat)
+    (priced : amount ≠ 0) :
+    let shop := Shop.run [
+      .send ⟨.Order, (), .place id item amount⟩,
+      .answer (.charge id amount) (.refused reason)]
+    (shop.state .Order id).status = .declined reason ∧
+      (shop.state .Shipment id).item = none ∧
+      Shop.waiting shop = [] := by
+  behaviour
+
+/-! ## Eventually
+
+The theorems above say where a flow stands. These say it ends: left to run, the
+shop comes to rest, with nothing in flight, and with the order where it should be.
+-/
+
+/--
+Given a new order, when it is placed, the gateway approves and the warehouse
+answers, then eventually the shop is at rest with nothing in flight, the order
+paid and its shipment scheduled.
+-/
+theorem anApprovedOrderEventuallyShips (id item charge : String) (amount : Nat)
+    (priced : amount ≠ 0) :
+    Shop.Eventually
+      (Shop.run [
+        .send ⟨.Order, (), .place id item amount⟩,
+        .answer (.charge id amount) (.approved charge),
+        .answer (.ship id item) ()])
+      fun shop => shop.Settled ∧ (shop.state .Order id).status = .paid charge ∧
+        (shop.state .Shipment id).item = some item := by
+  refine Shop.eventually_now _ ?_ ?_ <;> behaviour
+
+/-- And when the gateway refuses, eventually the shop is at rest with the order declined. -/
+theorem aRefusedOrderEventuallyEnds (id item reason : String) (amount : Nat)
+    (priced : amount ≠ 0) :
+    Shop.Eventually
+      (Shop.run [
+        .send ⟨.Order, (), .place id item amount⟩,
+        .answer (.charge id amount) (.refused reason)])
+      fun shop => shop.Settled ∧ (shop.state .Order id).status = .declined reason := by
+  refine Shop.eventually_now _ ?_ ?_ <;> behaviour
+
+/-! ### From any world
+
+Those two are about one flow. This is about every world the shop can reach:
+whatever was sent and answered, in any order, the shop left to run comes to rest.
+`comes_to_rest` proves it: it finds a weight for each event, more than the
+reactions to it, and for each command, at least what it records, so every step
+lowers the total. Nobody chooses the weights.
+-/
+
+end Shop
+
+comes_to_rest Shop
+
+namespace Shop
+
+/--
+The shop comes to rest. From any world it can reach, left to run, it stops:
+nothing more can happen without a caller, an outside answer or the clock.
+-/
+theorem theShopComesToRest (w : Alchemy.World Signature) (reach : Shop.Reachable w) :
+    ∃ steps, Shop.AtRest (Shop.settle steps w) :=
+  Shop.comesToRest w reach
+
+/--
+And how many steps: the shop's reactions only call outside, tell an aggregate
+and end, so it is at rest after as many steps as the world weighs.
+-/
+theorem theShopComesToRestIn (w : Alchemy.World Signature) (reach : Shop.Reachable w) :
+    Shop.AtRest (Shop.settle ((ranking.weights reacts).measure w) w) :=
+  Shop.comesToRestIn w reach
+
+/-- The weights it found, to read: a paid order weighs more than the shipment it leads to. -/
+example : ranking.event .Order (.paid "ch-1" "kettle" 20) > ranking.event .Shipment (.scheduled "kettle") := by
+  decide
+
+/-! ## Rules about the domain -/
+
+/-- An order is charged at most once, and never more than it costs. -/
+def ChargedOnce (s : Order.State) : Prop :=
+  (s.status = .new ∨ s.status = .awaitingPayment → s.charged = 0) ∧ s.charged ≤ s.amount
+
+/-- No command an order accepts breaks the rule. -/
+theorem chargedOnce : Order.Keeps ChargedOnce := by
+  aggregate_rule
+
+/--
+So it holds for every order in every world the shop can reach: whatever callers
+send, whatever the gateway answers, in any order of delivery, with any event
+delivered twice.
+-/
+theorem everyOrderChargedOnce (w : Alchemy.World Signature) (reach : Shop.Reachable w)
+    (id : String) : ChargedOnce (w.state .Order id) :=
+  Order.always (by simp [ChargedOnce]) chargedOnce w reach id
+
+/-- And of the shop as deployed: whatever its journal holds. -/
+theorem deployedOrdersChargedOnce (journal : List Journal.Line) (id : String) :
+    ChargedOnce ((served.replay journal).state .Order id) :=
+  Order.deployed (by simp [ChargedOnce]) chargedOnce journal id
+
+/-! These came with the model: nobody proved them here. -/
+
+example (log : List (Emitted Aggregates)) :
+    Revenue.stateAt log () = log.foldl Revenue.step 0 := Revenue.exact log
+
+example (log : List (Emitted Aggregates)) :
+    Packing.table log = log.flatMap Packing.rows := Packing.exact log
+
+/-! ## What an order's history says
+
+Rules about a state alone are lifted by `Order.always`. These tie a state to
+the events its order recorded, and are lifted the same way.
+-/
+
+/-- What an event adds to what an order was charged. -/
+def Order.worth : Order.Event → Int
+  | .paid _ _ amount => amount
+  | _ => 0
+
+/-- Every command moves `charged` by exactly what its events are worth. -/
+theorem chargesAreTallied : Order.Tallies (fun s => s.charged) Order.worth := by
+  history_rule
+
+/-- So what any order was charged is the sum of the payments it recorded: no more, no less. -/
+theorem chargedIsWhatWasPaid (w : Alchemy.World Signature) (reach : Shop.Reachable w) (id : String) :
+    ((w.state .Order id).charged : Int)
+      = ((w.toRecorded.eventsAt .Order id).map Order.worth).sum := by
+  simpa using Order.tallied chargesAreTallied w reach id
+
+def Order.isPlaced : Order.Event → Prop
+  | .placed .. => True
+  | _ => False
+
+def Order.isPaid : Order.Event → Prop
+  | .paid .. => True
+  | _ => False
+
+/-- An order records a payment only once it shows it was placed. -/
+theorem paymentNeedsAPlacedOrder :
+    Order.Precedes Order.isPlaced Order.isPaid (fun s => s.status ≠ .new) := by
+  history_rule
+
+/-- So in every order's history, in every world the shop can reach, a payment comes after a placement. -/
+theorem noOrderIsPaidBeforeItIsPlaced (w : Alchemy.World Signature) (reach : Shop.Reachable w)
+    (id : String) :
+    Aggregate.Follows Order.isPlaced Order.isPaid (w.toRecorded.eventsAt .Order id) :=
+  Order.follows paymentNeedsAPlacedOrder w reach id
+
+/-! ## Across aggregates: nothing ships unless it was paid
+
+Shipments are internal: no caller can ask for one. So a shipment is only ever
+scheduled by a policy, and the only policy that schedules one reacts to a payment.
+-/
+
+/-- An event a shipment recorded. -/
+def isShipment : Emitted Aggregates → Prop
+  | ⟨.Shipment, _, _, _, _⟩ => True
+  | _ => False
+
+/-- The payment a shipment needs: the same order, paid. -/
+def paidFor : Emitted Aggregates → Emitted Aggregates → Prop
+  | ⟨.Shipment, id, _, _, _⟩, ⟨.Order, id', .paid .., _, _⟩ => id = id'
+  | _, _ => False
+
+/--
+Nothing ships unless it was paid. In every world the shop can reach, whatever
+callers send and the gateway answers, every shipment recorded is for an order
+whose payment is recorded.
+-/
+theorem nothingShipsUnlessPaid (w : Alchemy.World Signature) (reach : Shop.Reachable w) :
+    Model.Backed isShipment paidFor w.log := by
+  caused_by reach
+
+/-- One story, in the shop's words: a kettle is ordered, paid for and shipped, and cannot be ordered twice. -/
+def aKettle : List (Story.ModelStep Shop) := [
+  .when ⟨.Order, (), .place "o-1" "kettle" 40⟩,
+  .call (.charge "o-1" 40),
+  .answer (.charge "o-1" 40) (.approved "ch_o-1"),
+  .recorded .Order "o-1" [.placed "kettle" 40, .paid "ch_o-1" "kettle" 40],
+  .recorded .Shipment "o-1" [.scheduled "kettle"],
+  .call (.ship "o-1" "kettle"),
+  .answer (.ship "o-1" "kettle") (),
+  .view Revenue () 40,
+  .when ⟨.Order, (), .place "o-1" "kettle" 40⟩,
+  .rejected .Order .alreadyPlaced ]
+
+/-- Told to the domain by itself, with the story playing the outside systems. -/
+example : Shop.passes aKettle = true := by decide
+
+/-! ## The shop, kept in stores
+
+Nothing above says where an order's state is kept. `Shop.Services` is what the
+shop asks of a host: a store for its aggregates, delivery of what they record,
+its calls. The engine is written once against them: it loads an order, decides,
+and commits the state the events leave. It replays nothing.
+-/
+
+/-- A payment gateway that approves anything up to a limit. It touches no resource. -/
+def sandboxCharge (order : String) (amount : Nat) (limit : Nat := 1000) : Charge :=
+  if amount ≤ limit then .approved s!"ch_{order}" else .refused "over the limit"
+
+/-- The shop on services held in memory: what its stories and tests run on. -/
+def inMemory : Shop.Stored (StateM (Held Signature reads)) where
+  services := InMemory.services _ _ fun
+    | .charge order amount => sandboxCharge order amount
+    | .ship _ _ => ()
+
+/-- What the stores hold once a kettle is ordered, and what the caller was told. -/
+def aKettleOrdered :=
+  (inMemory.ask ⟨.Order, (), .place "o-1" "kettle" 40⟩).run (Held.start _ _)
+
+/-- The caller is told it is paid, the shipment is scheduled, and the Revenue view is kept up. -/
+example :
+    ((aKettleOrdered.1.toOption, (aKettleOrdered.2.state .Shipment "o-1").item,
+        Revenue.held aKettleOrdered.2.read ()) : Option Order.Status × Option String × Nat)
+      = (some (.paid "ch_o-1"), some "kettle", 40) := by
+  native_decide
+
+section AnyStores
+
+variable {μ : Type → Type} [Monad μ] {S : Type} {acts : Acts μ S}
+  {held : S → Held Signature reads} {sound : S → Prop}
+
+/--
+An order is charged at most once, wherever it is kept. For any services that
+keep their laws, whatever commands the host is sent and however often it wakes,
+every order the store holds satisfies the rule.
+-/
+theorem storedOrdersChargedOnce (shop : Shop.Stored μ) (lawful : shop.services.Lawful acts held sound)
+    {fresh now : S} (ok : sound fresh) (empty : held fresh = Held.start _ _)
+    (ran : shop.Runs acts fresh now) (id : String) :
+    ChargedOnce ((held now).state .Order id) :=
+  (ran.stands lawful Shop.plain ok (empty ▸ Model.Stands.start Shop)).1.holds
+    (Q := fun states => ChargedOnce (states .Order id))
+    fun w reach => everyOrderChargedOnce w reach id
+
+/--
+And the Revenue a store answers, once nothing is waiting to be delivered, is
+the Revenue of everything recorded in a world the shop can reach.
+-/
+theorem storedRevenueIsExact (shop : Shop.Stored μ) (lawful : shop.services.Lawful acts held sound)
+    {fresh now : S} (ok : sound fresh) (empty : held fresh = Held.start _ _)
+    (ran : shop.Runs acts fresh now) (delivered : (held now).pending = []) :
+    ∃ w, Shop.Reachable w ∧ Revenue.held (held now).read () = Revenue.stateAt w.log () := by
+  obtain ⟨w, reach, _, read⟩ :=
+    (ran.stands lawful Shop.plain ok (empty ▸ Model.Stands.start Shop)).1.read delivered
+  exact ⟨w, reach, by rw [read]; exact Revenue.stored w.log ()⟩
+
+end AnyStores
+
+/-- In memory is one such: the services keep their laws, so both hold of it. -/
+example (now : Held Signature reads) (ran : inMemory.Runs (InMemory.acts _) (Held.start _ _) now)
+    (id : String) : ChargedOnce (now.state .Order id) :=
+  storedOrdersChargedOnce inMemory (InMemory.lawful _ _ _) trivial rfl ran id
+
+/-! ## The stack -/
+
+/-- An order's status, as a response. -/
+def describe : Order.Status → Response
+  | .new => { status := 404, body := "no such order" }
+  | .awaitingPayment => { status := 202, body := "awaiting payment" }
+  | .paid charge => { status := 200, body := s!"paid {charge}" }
+  | .declined reason => { status := 402, body := reason }
+
+/-! The Api's routes, each a function of the hosted shop. -/
+
+section Routes
+variable {role : Access Kind} (shop : Hosted served role)
+
+/-- What the Api says about a command: its rejection, or the order's reply. -/
+def respond : Except Order.Rejection Order.Status → Response
+  | .ok status => describe status
+  | .error rejection => { status := 409, body := reprStr rejection }
+
+/-- `POST /orders`: the command's reply is the response. -/
+def postOrder (command : Order.Command) : Run role Never Response := do
+  return respond (← shop.ask (.Order command))
+
+/-- `GET /orders/{id}` -/
+def getOrder (id : String) : Run role Never Response := do
+  return describe ((← shop.world).state .Order id).status
+
+/-- `GET /revenue` -/
+def getRevenue : Run role Never Response := do
+  return { status := 200, body := toString (Revenue.stateAt (← shop.world).log ()) }
+
+def route (request : Request) : Run role Never Response :=
+  match request.method, request.path with
+  | .post, ["orders"] =>
+    match Text.read (α := Order.Command) request.body with
+    | some command => postOrder shop command
+    | none => pure { status := 400, body := "not a command" }
+  | .get, ["orders", id] => getOrder shop id
+  | .get, ["revenue"] => getRevenue shop
+  | _, _ => pure { status := 404, body := "not found" }
+
+end Routes
+
+-- The shop, hosted: its history is a journal in the bucket, and each call it
+-- makes to the outside is answered here. Charging goes to a sandbox gateway;
+-- shipping is a message on the queue. What it needs is read off its body.
+effect def theShop {role : Access Kind} (orders : Bucket) (shipments : Queue) : Hosted served role :=
+  served.host (S3.journal orders) fun
+    | .charge order amount => pure (sandboxCharge order amount)
+    | .ship order item => SQS.sendMessage shipments s!"{order}:{item}"
+
+/-- Takes orders. Hosts the shop: its history is in the bucket, and it ships through the queue. -/
+def Api (orders : Bucket) (shipments : Queue) : Construct Kind Function := do
+  let stage ← stage
+  Lambda.Function "Api" { url := true, memory := if stage = "prod" then 1024 else 512 } do
+    return route (theShop orders shipments)
+
+/-- Consumes the shipments queue and files a packing slip for each. -/
+def Warehouse (orders : Bucket) (shipments : Queue) : Construct Kind Function :=
+  Lambda.Function "Warehouse" {} do
+    SQS.consume shipments fun shipment => do
+      match shipment.splitOn ":" with
+      | [order, item] => S3.putObject orders ["packed"] order item
+      | _ => pure ()
+
+    return fun _ => return { status := 204 }
+
+structure Outputs where
+  orders : Bucket
+  shipments : Queue
+  api : Function
+  warehouse : Function
+deriving Inhabited
+
+def ShopStack : Stack Kind Outputs where
+  name := "Shop"
+  body := do
+    let orders ← S3.Bucket "Orders"
+    let shipments ← SQS.Queue "Shipments"
+    let api ← Api orders shipments
+    let warehouse ← Warehouse orders shipments
+    return { orders, shipments, api, warehouse }
+
+def prod : Graph Kind := ShopStack.graph "prod"
+
+/-- What the stack built, for tests and theorems to name. -/
+@[stack_facts] def out : Outputs := computed% (ShopStack.outputs "prod")
+
+example : ShopStack.problem "prod" = none ∧ prod.deployable = true := by decide
+
+example : prod.order = ["Orders", "Shipments", "Api", "Warehouse"] := by decide
+
+/-! ## Behaviour of the Api, for every request
+
+The same shape as the domain's behaviour theorems, one level out: given what the
+bucket holds, when a request arrives, then this is the response and this is what
+the bucket holds afterwards. Proved from the laws of the bindings.
+-/
+
+section ApiBehaviour
+
+variable {role : Access Kind} {orders : Bucket} {shipments : Queue}
+  [theShop.Needs role orders shipments]
+
+/-- The shop as a bucket has it: what its journal replays to. -/
+abbrev shopIn (orders : Bucket) (cloud : Memory) : Alchemy.World Signature :=
+  served.replay (S3.lines orders ["journal"] cloud)
+
+/-- A bucket whose journal is whole: every line it counts is there. -/
+abbrev Whole (orders : Bucket) (cloud : Memory) : Prop := S3.Sound orders ["journal"] cloud
+
+/--
+Given any bucket, when an order is asked for, then the Api describes that order
+as the journal has it, and changes nothing.
+-/
+theorem gettingAnOrder (id : String) (cloud : Memory) :
+    (getOrder (theShop (role := role) orders shipments) id).eval InMemory cloud
+      = (.ok (describe ((shopIn orders cloud).state .Order id).status), cloud) := by
+  show Run.eval InMemory (Run.bind _ _) cloud = _
+  rw [Run.eval_bind, Hosted.world_eval _ (S3.journal_lawful orders ["journal"])]
+  rfl
+
+/-- Given any bucket, when the revenue is asked for, then the Api answers the Revenue view, and changes nothing. -/
+theorem gettingTheRevenue (cloud : Memory) :
+    (getRevenue (theShop (role := role) orders shipments)).eval InMemory cloud
+      = (.ok { status := 200, body := toString (Revenue.stateAt (shopIn orders cloud).log ()) },
+          cloud) := by
+  show Run.eval InMemory (Run.bind _ _) cloud = _
+  rw [Run.eval_bind, Hosted.world_eval _ (S3.journal_lawful orders ["journal"])]
+  rfl
+
+/-- What a caller of an order command is told, in the order's own terms. -/
+theorem answered_order (command : Order.Command) (before after : Alchemy.World Signature) :
+    Hosted.answered (served.command (.Order command))
+        (before.toRecorded.outcome before.now (served.command (.Order command))) after
+      = (Order.decide (before.state .Order (Order.key command)) command).map
+          fun _ => Order.reply (after.state .Order (Order.key command)) command := rfl
+
+/--
+Given a bucket whose journal is whole, when a command is posted, then the Api
+answers what the order, as the journal had it, decides: a refusal as a 409, and
+otherwise the order's reply from the state the journal has now. The journal is
+whole afterwards.
+-/
+theorem postingACommand (command : Order.Command) (cloud : Memory) (whole : Whole orders cloud) :
+    ((postOrder (theShop (role := role) orders shipments) command).eval InMemory cloud).1
+      = .ok (respond
+        ((Order.decide ((shopIn orders cloud).state .Order (Order.key command)) command).map
+          fun _ => Order.reply
+            ((shopIn orders
+              ((postOrder (theShop (role := role) orders shipments) command).eval InMemory cloud).2).state
+              .Order (Order.key command)) command)) ∧
+      Whole orders
+        ((postOrder (theShop (role := role) orders shipments) command).eval InMemory cloud).2 := by
+  have asked := Hosted.ask_recorded (sim := InMemory) (lines := S3.lines orders ["journal"])
+    (sound := S3.Sound orders ["journal"]) (theShop (role := role) orders shipments)
+    (S3.journal_lawful orders ["journal"]) served.faithful
+    (by
+      intro call cloud whole
+      cases call with
+      | charge order amount => exact ⟨rfl, whole⟩
+      | ship order item =>
+        refine S3.quiet _ cloud (fun key => ?_) whole
+        show ((SQS.sendMessage (role := role) shipments s!"{order}:{item}").eval InMemory cloud).2.object
+          orders key = _
+        rw [SQS.sendMessage_eval]
+        rfl)
+    (.Order command) cloud whole
+  have evaluated : (postOrder (theShop (role := role) orders shipments) command).eval InMemory cloud
+      = (.ok (respond (Hosted.answered (served.command (.Order command))
+            ((shopIn orders cloud).toRecorded.outcome (shopIn orders cloud).now
+              (served.command (.Order command)))
+            (shopIn orders ((Hosted.ask (theShop (role := role) orders shipments)
+              (.Order command)).eval InMemory cloud).2))),
+        ((Hosted.ask (theShop (role := role) orders shipments) (.Order command)).eval InMemory cloud).2) := by
+    show Run.eval InMemory (Run.bind _ _) cloud = _
+    rw [Run.eval_bind, asked.1]
+    rfl
+  rw [evaluated]
+  exact ⟨congrArg (fun told => Except.ok (respond told)) (answered_order command _ _), asked.2⟩
+
+/--
+Given a bucket in which an order is already placed, when it is placed again,
+then the Api refuses with a 409, whatever the item and the amount.
+-/
+theorem placingAnOrderTwiceIsRefused (id item : String) (amount : Nat) (cloud : Memory)
+    (whole : Whole orders cloud)
+    (placed : ((shopIn orders cloud).state .Order id).status ≠ .new) :
+    ((postOrder (theShop (role := role) orders shipments) (.place id item amount)).eval InMemory cloud).1
+      = .ok { status := 409, body := reprStr Order.Rejection.alreadyPlaced } := by
+  have answered := (postingACommand (role := role) (shipments := shipments)
+    (.place id item amount) cloud whole).1
+  simp only [respond, Order.decide, Order.key, placed, ne_eq, not_false_eq_true, ite_true,
+    Except.map] at answered
+  exact answered
+
+/-- A posted body that reads as a command reaches the route for that command. -/
+theorem postingReachesTheCommand (body : String) (command : Order.Command)
+    (reads : Text.read (α := Order.Command) body = some command) :
+    route (theShop (role := role) orders shipments) { method := .post, path := ["orders"], body }
+      = postOrder (theShop (role := role) orders shipments) command := by
+  simp [route, reads]
+
+/-- A posted body that does not read as a command is refused, and nothing is touched. -/
+theorem aMalformedBodyIsRefused (body : String)
+    (unreadable : Text.read (α := Order.Command) body = none) (cloud : Memory) :
+    (route (theShop (role := role) orders shipments)
+        { method := .post, path := ["orders"], body }).eval InMemory cloud
+      = (.ok { status := 400, body := "not a command" }, cloud) := by
+  simp only [route, unreadable]
+  rfl
+
+/-- The routes are the requests: each request reaches the route its path names. -/
+example (id : String) :
+    route (theShop (role := role) orders shipments) { method := .get, path := ["orders", id] }
+      = getOrder (theShop (role := role) orders shipments) id := rfl
+
+end ApiBehaviour
+
+/-! ## Stories, told to the stack
+
+The same kind of story as the domain's, in the same words. Here each command
+goes in through the Api, the gateway and the queue answer the shop's calls, and
+what is recorded is read back from the journal in the bucket.
+-/
+
+/-- How the stack is told a story: commands are posted to the Api, and the shop is read from the bucket. -/
+def deployed : Telling Shop InMemory where
+  kind := .function
+  host := out.api
+  request
+    | ⟨.Order, _, command⟩ => (post out.api "/orders" command).request
+    | ⟨.Shipment, _, command⟩ => (post out.api "/shipments" command).request
+  world := shopIn out.orders
+
+/-- The same story as the domain's, word for word, told to the stack. -/
+example : prod.tells deployed aKettle = true := by native_decide
+
+/-- And one the stack decides for itself: its gateway refuses an order over its limit. -/
+example : prod.tells deployed [
+    .when ⟨.Order, (), .place "o-2" "yacht" 5000⟩,
+    .recorded .Order "o-2" [.placed "yacht" 5000, .declined "over the limit"],
+    .view Revenue () 0
+  ] = true := by native_decide
+
+/-! ## Tests of the stack
+
+These are not stories: they speak HTTP and buckets, not the shop's language.
+They check the wiring end to end, in memory.
+-/
+
+def postingAnOrder : List (Graph.Step Kind InMemory) := [
+  post out.api "/orders" (Order.Command.place "o-1" "kettle" 40) ⇒ (200, "paid ch_o-1"),
+  .holds "the warehouse filed a slip" (·.object out.orders ["packed", "o-1"] == some "kettle"),
+  .holds "and took the shipment off the queue" (·.queued out.shipments == []),
+  get out.api "/orders/o-1" ⇒ (200, "paid ch_o-1"),
+  post out.api "/orders" (Order.Command.place "o-1" "kettle" 40)
+    ⇒ (409, "Order.Rejection.alreadyPlaced"),
+  get out.api "/revenue" ⇒ (200, "40") ]
+
+def postingAnOrderTooLarge : List (Graph.Step Kind InMemory) := [
+  post out.api "/orders" (Order.Command.place "o-2" "yacht" 5000) ⇒ (402, "over the limit"),
+  .holds "nothing was packed" (·.object out.orders ["packed", "o-2"] == none) ]
+
+example : prod.passes postingAnOrder = true := by native_decide
+example : prod.passes postingAnOrderTooLarge = true := by native_decide
+
+/-! ## What is proved about access -/
+
+/-- Only the Api writes the shop's history. -/
+theorem onlyTheApiWritesHistory :
+    prod.only [out.api] (S3.writing out.orders ["journal"]) := by
+  stack_rule in prod
+
+/-- Only the Warehouse files packing slips. -/
+theorem onlyTheWarehouseFilesSlips :
+    prod.only [out.warehouse] (S3.writing out.orders ["packed"]) := by
+  stack_rule in prod
+
+/-- The Warehouse reads nothing in the bucket: no order, and none of the history. -/
+theorem theWarehouseReadsNothing :
+    prod.never out.warehouse (S3.reading out.orders) := by
+  stack_rule in prod
+
+/-- Nothing can list the bucket. -/
+theorem nobodyListsTheOrders : prod.nobody (S3.listing out.orders) := by
+  stack_rule in prod
+
+/-- Only the Api asks for a shipment, and only the Warehouse takes one. -/
+theorem shipmentsGoOneWay :
+    prod.only [out.api] (SQS.sending out.shipments) ∧
+      prod.only [out.warehouse] (SQS.receiving out.shipments) := by
+  constructor <;> stack_rule in prod
+
+/-- Neither function can invoke the other. -/
+theorem noFunctionInvokesAnother (function : Function) :
+    prod.nobody (Lambda.invoking function) := by
+  stack_rule in prod
+
+/-- The Api can read back all of the history it writes. -/
+theorem theApiReadsItsHistory :
+    prod.may out.api (S3.reading out.orders ["journal"]) := by
+  stack_rule in prod
+
+/--
+Least privilege: no function holds a grant it does not need. For each one there
+is a run in which that function makes a call the grant is what permits.
+-/
+theorem leastPrivilege : prod.LeastPrivilege InMemory :=
+  .of_tests [postingAnOrder] (by native_decide)
+
+/-! ## Deploying it -/
+
+def fresh : Cloud.World Kind Control.Service := ⟨.empty, {}⟩
+
+def deploy (g : Graph Kind) (w : Cloud.World Kind Control.Service) :
+    Cloud.World Kind Control.Service × Bool :=
+  apply Control.providers Control.Service g w
+
+/-- The first deploy creates everything, each resource after what it needs. -/
+example : plan Control.providers prod fresh.state = [
+    ("Orders", .create), ("Shipments", .create), ("Api", .create), ("Warehouse", .create)] := by
+  native_decide
+
+/-- It succeeds, and deploying again has nothing to do. -/
+example : (deploy prod fresh).2 = true ∧
+    plan Control.providers prod (deploy prod fresh).1.state = [
+      ("Orders", .noop), ("Shipments", .noop), ("Api", .noop), ("Warehouse", .noop)] := by
+  native_decide
+
+end Shop
diff --git a/packages/alchemy-lean/examples/ShopMain.lean b/packages/alchemy-lean/examples/ShopMain.lean
new file mode 100644
index 00000000000..c10a08ff44e
--- /dev/null
+++ b/packages/alchemy-lean/examples/ShopMain.lean
@@ -0,0 +1,4 @@
+import Shop
+
+/-- `lake exe shop graph [stage] [--why]`, `lake exe shop plan [stage]`, `lake exe shop plan [stage] after [stage]` -/
+def main (args : List String) : IO UInt32 := Alchemy.AWS.cli Shop.ShopStack args
diff --git a/packages/alchemy-lean/examples/Uploads.lean b/packages/alchemy-lean/examples/Uploads.lean
new file mode 100644
index 00000000000..fb4a5258e84
--- /dev/null
+++ b/packages/alchemy-lean/examples/Uploads.lean
@@ -0,0 +1,324 @@
+import Alchemy
+
+/-!
+# Uploads
+
+People upload files from the internet. A file must not reach anyone until it
+has been scanned, and an infected file must never be served.
+
+Three functions share one bucket:
+
+- `Upload` is public. It stores a file under `incoming/` and asks for a scan.
+- `Scanner` is private. It reads the file, and writes it under `clean/` or `quarantine/`.
+- `Download` is public. It serves files from `clean/`.
+
+The safety of this design is entirely in who may touch which prefix. Those
+rules are stated here as theorems about the stack, so a change that breaks one
+does not build.
+-/
+
+open Alchemy Cloud AWS
+
+namespace Uploads
+
+/--
+Whether a file is infected. It is opaque: no proof below can look inside it, so
+every theorem holds for whatever detector is put here.
+-/
+opaque infected (body : String) : Bool := (body.splitOn "EICAR").length > 1
+
+/-- Stores an upload where nothing public can read it, and asks for it to be scanned. -/
+def Upload (files : Bucket) (scans : Queue) : Construct Kind Function :=
+  Lambda.Function "Upload" { url := true } do
+    return fun request => do
+      match request.method, request.path with
+      | .post, ["files", name] =>
+        S3.putObject files ["incoming"] name request.body
+        SQS.sendMessage scans name
+        return { status := 202 }
+      | _, _ => return { status := 404 }
+
+-- Scans one upload: a clean file is published, an infected one is set aside.
+-- Nobody lists what it needs: reading `incoming/`, and writing `clean/` and
+-- `quarantine/`, are read off its body.
+effect def scan {role : Access Kind} (files : Bucket) (name : String) : Run role Never Unit := do
+  match ← (S3.getObject files ["incoming"] name).result with
+  | .ok body =>
+    if infected body then S3.putObject files ["quarantine"] name body
+    else S3.putObject files ["clean"] name body
+  | .error _ => pure ()
+
+def Scanner (files : Bucket) (scans : Queue) : Construct Kind Function :=
+  Lambda.Function "Scanner" {} do
+    SQS.consume scans fun name => scan files name
+    return fun _ => return { status := 204 }
+
+/-- Serves published files, and nothing else. -/
+def Download (files : Bucket) : Construct Kind Function :=
+  Lambda.Function "Download" { url := true } do
+    return fun request => do
+      match request.method, request.path with
+      | .get, ["files", name] =>
+        match ← (S3.getObject files ["clean"] name).result with
+        | .ok body => return { status := 200, body }
+        | .error _ => return { status := 404 }
+      | _, _ => return { status := 404 }
+
+structure Outputs where
+  files : Bucket
+  scans : Queue
+  upload : Function
+  scanner : Function
+  download : Function
+deriving Inhabited
+
+def UploadStack : Stack Kind Outputs where
+  name := "Uploads"
+  body := do
+    let files ← S3.Bucket "Files"
+    let scans ← SQS.Queue "Scans"
+    let upload ← Upload files scans
+    let scanner ← Scanner files scans
+    let download ← Download files
+    return { files, scans, upload, scanner, download }
+
+def prod : Graph Kind := UploadStack.graph "prod"
+@[stack_facts] def out : Outputs := computed% (UploadStack.outputs "prod")
+
+/-! ## What must be true of this stack -/
+
+/-- Exactly two functions face the internet. A third would have to be added here on purpose. -/
+theorem whatIsPublic : exposed prod = ["Upload", "Download"] := by decide
+
+/--
+Nothing public can read a file that has not been scanned. This is the rule the
+design exists for, and it holds for every file name.
+-/
+theorem nothingPublicReadsAnUnscannedFile :
+    nothingExposed prod (S3.reading out.files ["incoming"]) := by
+  simp only [nothingExposed, whatIsPublic]
+  stack_rule in prod
+
+/-- Nothing public can read what was quarantined, either. In fact nothing at all can. -/
+theorem nobodyReadsTheQuarantine : prod.nobody (S3.reading out.files ["quarantine"]) := by
+  stack_rule in prod
+
+/--
+Only the Scanner publishes. So every file `Download` can serve was put there by
+the Scanner: there is no way around the scan.
+-/
+theorem onlyTheScannerPublishes :
+    prod.only [out.scanner] (S3.writing out.files ["clean"]) := by
+  stack_rule in prod
+
+/-- If `Upload` is taken over, it can read nothing: not uploads, not published files. -/
+theorem uploadReadsNothing : prod.never out.upload (S3.reading out.files) := by
+  stack_rule in prod
+
+/-- If `Download` is taken over, it can change nothing: no file, and no scan request. -/
+theorem downloadChangesNothing :
+    prod.never out.download (S3.writing out.files) ∧
+      prod.only [out.upload] (SQS.sending out.scans) := by
+  constructor <;> stack_rule in prod
+
+/-- No function can invoke another, so taking one over does not lead to the others. -/
+theorem noFunctionInvokesAnother (function : Function) :
+    prod.nobody (Lambda.invoking function) := by
+  stack_rule in prod
+
+/-! ## What a function can do if it is taken over
+
+The rules above are about roles. These are about code: any code at all,
+running with a public function's role. They hold because a call the role does
+not permit cannot be written, so they cover an attacker's code as well as ours.
+-/
+
+/-- Whatever runs as `Upload`, it cannot publish or alter a published file. -/
+theorem uploadCannotPublish {ε α : Type} (code : Run (prod.roleOf "Upload") ε α) (cloud : Memory)
+    (name : String) :
+    (code.exec InMemory cloud).state.object out.files ["clean", name]
+      = cloud.object out.files ["clean", name] := by
+  refine Run.leaves code cloud _ _ ?_
+  have role : prod.roleOf "Upload" = computed% (prod.roleOf "Upload") := rfl
+  have differ : ¬BucketOp.put ["incoming"] = BucketOp.put ["clean", name] := by simp
+  simp [role, out, Access.permits, permitsOn, Kinds.covers, BucketOp.covers, List.isPrefixOf, differ]
+
+/-- Whatever runs as `Download`, it cannot either. -/
+theorem downloadCannotPublish {ε α : Type} (code : Run (prod.roleOf "Download") ε α)
+    (cloud : Memory) (name : String) :
+    (code.exec InMemory cloud).state.object out.files ["clean", name]
+      = cloud.object out.files ["clean", name] := by
+  refine Run.leaves code cloud _ _ ?_
+  have role : prod.roleOf "Download" = computed% (prod.roleOf "Download") := rfl
+  simp [role, out, Kinds.covers, BucketOp.covers]
+
+/-! ## The whole design: nothing infected is ever published -/
+
+/-- Every published file is clean. -/
+def Safe (cloud : Memory) : Prop :=
+  ∀ name body, cloud.object out.files ["clean", name] = some body → infected body = false
+
+section
+variable {role : Access Kind} [scan.Needs role out.files]
+
+/-- What a scan leaves: nothing, the file in quarantine, or the file published. -/
+theorem scan_eval (name : String) (cloud : Memory) :
+    ((scan (role := role) out.files name).eval InMemory cloud).2 =
+      match cloud.object out.files ["incoming", name] with
+      | none => cloud
+      | some body =>
+        if infected body then cloud.put out.files ["quarantine", name] body
+        else cloud.put out.files ["clean", name] body := by
+  have read := S3.getObject_eval (role := role) out.files ["incoming"] name cloud
+  show (Run.eval InMemory (Run.bind _ _) cloud).2 = _
+  rw [Run.eval_bind, Run.eval_result, read]
+  have key : (["incoming"] ++ [name] : Path) = ["incoming", name] := rfl
+  rw [key]
+  cases found : cloud.object out.files ["incoming", name] with
+  | none => rfl
+  | some body =>
+    by_cases bad : infected body = true
+    · simp only [bad, ite_true]
+      exact congrArg Prod.snd (S3.putObject_eval out.files ["quarantine"] name body cloud)
+    · simp only [bad]
+      exact congrArg Prod.snd (S3.putObject_eval out.files ["clean"] name body cloud)
+
+/-- A scan keeps every published file clean. -/
+theorem scan_safe (name : String) (cloud : Memory) (safe : Safe cloud) :
+    Safe ((scan (role := role) out.files name).eval InMemory cloud).2 := by
+  rw [scan_eval]
+  cases found : cloud.object out.files ["incoming", name] with
+  | none => exact safe
+  | some body =>
+    intro published content held
+    by_cases bad : infected body = true
+    · simp only [bad, ite_true] at held
+      rw [Memory.object_put_other _ _ _ _ _ _ (by simp)] at held
+      exact safe published content held
+    · have clean : infected body = false := by simpa using bad
+      simp only [clean, Bool.false_eq_true, ite_false] at held
+      by_cases same : published = name
+      · subst same
+        rw [Memory.object_put_self] at held
+        cases held
+        exact clean
+      · rw [Memory.object_put_other _ _ _ _ _ _ (by simp [same])] at held
+        exact safe published content held
+
+end
+
+/-! ### What the deployed Scanner runs
+
+The Scanner's role, and the code it runs for each message on the queue, written
+out. Both are checked against the stack itself, by computation: if the stack's
+Scanner ever does anything else, these two lines stop compiling.
+-/
+
+abbrev scannerRole : Access Kind :=
+  S3.Get out.files ["incoming"] ∪ S3.Put out.files ["quarantine"] ∪ S3.Put out.files ["clean"]
+    ∪ SQS.Receive out.scans
+
+/-- Take the next upload's name off the queue, and scan it. -/
+def onMessage : Run scannerRole Failure Unit := do
+  match ← (((SQS.ReceiveMessageLive out.scans).build (access := scannerRole)
+      (inferInstance : Has scannerRole (SQS.Receive out.scans)).le ⟨⟩).call).mapError
+        (fun e => nomatch e) with
+  | some name => (scan out.files name).mapError reprStr
+  | none => pure ()
+
+/-- This is what the stack's Scanner runs when a message arrives, and all it listens to. -/
+theorem theScannerRunsThis :
+    prod.listens "Scanner" ⟨.queue, out.scans, QueueEvent.messageSent⟩
+      = [⟨scannerRole, onMessage⟩] := rfl
+
+/-- Asked directly, the stack's Scanner answers and touches nothing. -/
+theorem theScannerAnswersAndTouchesNothing (request : Request) :
+    prod.handler out.scanner request = some ⟨scannerRole, pure { status := 204 }⟩ := rfl
+
+/-- Handling a message keeps every published file clean. -/
+theorem onMessage_safe (cloud : Memory) (safe : Safe cloud) :
+    Safe (onMessage.exec InMemory cloud).state := by
+  have received : Safe (cloud.receive out.scans) := by
+    intro name body held
+    rw [Memory.object_receive] at held
+    exact safe name body held
+  show Safe (onMessage.eval InMemory cloud).2
+  unfold onMessage
+  show Safe (Run.eval InMemory (Run.bind _ _) cloud).2
+  rw [Run.eval_bind, Run.eval_mapError]
+  have took := (SQS.ReceiveMessageLive.lawful out.scans (access := scannerRole)
+    (inferInstance : Has scannerRole (SQS.Receive out.scans)).le).receive cloud
+  rw [took]
+  cases (cloud.queued out.scans).head? with
+  | none => exact received
+  | some name =>
+    show Safe (Run.eval InMemory (Run.mapError _ _) _).2
+    rw [Run.eval_mapError]
+    exact scan_safe name _ received
+
+/--
+The states of the cloud this stack can reach. The Scanner runs the code the
+stack gives it, on whatever is on the queue. The two public functions run any
+code whatever under their roles: ours, or an attacker's.
+-/
+inductive Reaches : Memory → Prop where
+  | start : Reaches {}
+  | upload {cloud ε α} (code : Run (prod.roleOf "Upload") ε α) :
+      Reaches cloud → Reaches (code.exec InMemory cloud).state
+  | download {cloud ε α} (code : Run (prod.roleOf "Download") ε α) :
+      Reaches cloud → Reaches (code.exec InMemory cloud).state
+  | scan {cloud} : Reaches cloud → Reaches (onMessage.exec InMemory cloud).state
+
+/--
+No infected file is ever published. In every state this stack can reach,
+whatever is uploaded, in whatever order things run, and even if both public
+functions are taken over, every file `Download` can serve is clean.
+-/
+theorem noInfectedFileIsEverPublished (cloud : Memory) (reach : Reaches cloud) : Safe cloud := by
+  induction reach with
+  | start => intro name body held; simp [Memory.object] at held
+  | upload code _ safe =>
+    intro name body held
+    rw [uploadCannotPublish] at held
+    exact safe name body held
+  | download code _ safe =>
+    intro name body held
+    rw [downloadCannotPublish] at held
+    exact safe name body held
+  | scan _ safe => exact onMessage_safe _ safe
+
+/--
+So nothing `Download` serves is infected. In any state the stack can reach, if
+a file can be read from where `Download` reads, it is clean.
+-/
+theorem nothingServedIsInfected {role : Access Kind} [Has role (S3.Get out.files ["clean"])]
+    (cloud : Memory) (reach : Reaches cloud) (name body : String)
+    (served : ((S3.getObject (role := role) out.files ["clean"] name).eval InMemory cloud).1
+      = .ok body) : infected body = false := by
+  rw [S3.getObject_eval] at served
+  have key : (["clean"] ++ [name] : Path) = ["clean", name] := rfl
+  rw [key] at served
+  cases held : cloud.object out.files ["clean", name] with
+  | none => simp [held] at served
+  | some content =>
+    simp only [held, Except.ok.injEq] at served
+    subst served
+    exact noInfectedFileIsEverPublished cloud reach name content held
+
+/-! ## Tests of the stack -/
+
+def aCleanFile : List (Graph.Step Kind InMemory) := [
+  .request out.upload { method := .post, path := ["files", "notes.txt"], body := "hello" }
+    (responds { status := 202 }),
+  get out.download "/files/notes.txt" ⇒ (200, "hello") ]
+
+def anInfectedFile : List (Graph.Step Kind InMemory) := [
+  .request out.upload { method := .post, path := ["files", "virus.exe"], body := "xxEICARxx" }
+    (responds { status := 202 }),
+  get out.download "/files/virus.exe" ⇒ (404, ""),
+  .holds "it was set aside" (·.object out.files ["quarantine", "virus.exe"] == some "xxEICARxx") ]
+
+example : prod.passes aCleanFile = true := by native_decide
+example : prod.passes anInfectedFile = true := by native_decide
+
+end Uploads
diff --git a/packages/alchemy-lean/examples/UploadsMain.lean b/packages/alchemy-lean/examples/UploadsMain.lean
new file mode 100644
index 00000000000..bb947bcf2bd
--- /dev/null
+++ b/packages/alchemy-lean/examples/UploadsMain.lean
@@ -0,0 +1,4 @@
+import Uploads
+
+/-- `lake exe uploads graph [stage] [--why]`, `lake exe uploads plan [stage]` -/
+def main (args : List String) : IO UInt32 := Alchemy.AWS.cli Uploads.UploadStack args
diff --git a/packages/alchemy-lean/examples/Wallet.lean b/packages/alchemy-lean/examples/Wallet.lean
new file mode 100644
index 00000000000..dc356d5856f
--- /dev/null
+++ b/packages/alchemy-lean/examples/Wallet.lean
@@ -0,0 +1,84 @@
+import Alchemy
+
+/-!
+# A wallet
+
+The smallest whole example: one aggregate, one rule proved about it, and one
+story the compiler runs.
+-/
+
+open Alchemy
+
+/-- A wallet remembers what came in and what went out. -/
+aggregate Wallet where
+  command
+    | deposit (id : String) (amount : Nat)
+        records deposited
+        rejects nothingToMove
+    | spend (id : String) (amount : Nat)
+        records spent
+        rejects nothingToMove, insufficientFunds
+
+  event
+    | deposited (amount : Nat)
+    | spent (amount : Nat)
+
+  rejection
+    | insufficientFunds (balance requested : Nat)
+    | nothingToMove
+
+  state
+    received : Nat := 0
+    spent : Nat := 0
+
+  decide
+    | _, .deposit _ amount =>
+      if amount = 0 then .error .nothingToMove else .ok [.deposited amount]
+    | s, .spend _ amount =>
+      if amount = 0 then .error .nothingToMove
+      else if amount ≤ s.received - s.spent then .ok [.spent amount]
+      else .error (.insufficientFunds (s.received - s.spent) amount)
+
+  evolve
+    | s, .deposited amount => { s with received := s.received + amount }
+    | s, .spent amount => { s with spent := s.spent + amount }
+
+namespace Wallet
+
+/-! ## A rule, proved -/
+
+/-- A wallet never spends more than it received. -/
+def NeverOverspent (s : State) : Prop := s.spent ≤ s.received
+
+/-- No command a wallet accepts breaks the rule. -/
+theorem neverOverspent_kept : Wallet.Keeps NeverOverspent := by aggregate_rule
+
+/-- So it holds whatever a wallet is sent, in any order, by anyone, at any time. -/
+theorem alwaysNeverOverspent (commands : List Wallet.Sent) :
+    NeverOverspent (Wallet.replay {} commands) :=
+  (Aggregate.Invariant.mk "NeverOverspent" NeverOverspent (by simp [NeverOverspent])
+    neverOverspent_kept).always commands
+
+/-! ## Behaviour, for every amount -/
+
+/-- Given a wallet with money in it, when more than that is spent, then it is refused. -/
+theorem overspendingIsRefused (id : String) (held amount : Nat) (tooMuch : held < amount) :
+    Wallet.decide (Wallet.after [.deposited held]) (.spend id amount)
+      = .error (.insufficientFunds held amount) := by
+  have some : amount ≠ 0 := by omega
+  have short : ¬amount ≤ held := by omega
+  simp [Aggregate.after, Aggregate.apply, Wallet.decide, Wallet.evolve, some, short]
+
+/-! ## A story, run when this file compiles -/
+
+example : Wallet.story () [
+    .given [.deposited 100],
+    .when (.spend "w-1" 30),
+    .recorded [.spent 30],
+    .when (.spend "w-1" 80),
+    .rejected (.insufficientFunds 70 80),
+    .when (.deposit "w-1" 0),
+    .rejected .nothingToMove
+  ] = true := by decide
+
+end Wallet
diff --git a/packages/alchemy-lean/lake-manifest.json b/packages/alchemy-lean/lake-manifest.json
new file mode 100644
index 00000000000..b0de9ea67e6
--- /dev/null
+++ b/packages/alchemy-lean/lake-manifest.json
@@ -0,0 +1,14 @@
+{"version": "1.3.0",
+ "packagesDir": ".lake/packages",
+ "packages":
+ [{"type": "path",
+   "scope": "",
+   "name": "distilled",
+   "manifestFile": "lake-manifest.json",
+   "inherited": false,
+   "dir": "../../submodules/distilled/lean",
+   "copy": false,
+   "configFile": "lakefile.lean"}],
+ "name": "alchemy",
+ "lakeDir": ".lake",
+ "fixedToolchain": false}
diff --git a/packages/alchemy-lean/lakefile.toml b/packages/alchemy-lean/lakefile.toml
new file mode 100644
index 00000000000..b5b1f8d9f36
--- /dev/null
+++ b/packages/alchemy-lean/lakefile.toml
@@ -0,0 +1,65 @@
+name = "alchemy"
+defaultTargets = ["Alchemy", "Accounts", "Bank", "Inbox", "Jobs", "Linked", "Loop", "Shop", "Uploads", "Wallet"]
+
+[[lean_lib]]
+name = "Alchemy"
+
+[[lean_lib]]
+name = "Accounts"
+srcDir = "examples"
+
+[[lean_lib]]
+name = "Bank"
+srcDir = "examples"
+
+[[lean_lib]]
+name = "Inbox"
+srcDir = "examples"
+
+[[lean_lib]]
+name = "Linked"
+srcDir = "examples"
+
+[[lean_lib]]
+name = "Loop"
+srcDir = "examples"
+
+[[lean_lib]]
+name = "Jobs"
+srcDir = "examples"
+
+[[lean_lib]]
+name = "Shop"
+srcDir = "examples"
+
+[[lean_lib]]
+name = "Uploads"
+srcDir = "examples"
+
+[[lean_lib]]
+name = "Wallet"
+srcDir = "examples"
+
+[[lean_exe]]
+name = "bank"
+root = "BankMain"
+srcDir = "examples"
+
+[[require]]
+name = "distilled"
+path = "../../submodules/distilled/lean"
+
+[[lean_exe]]
+name = "shop"
+root = "ShopMain"
+srcDir = "examples"
+
+[[lean_exe]]
+name = "uploads"
+root = "UploadsMain"
+srcDir = "examples"
+
+[[lean_exe]]
+name = "inbox"
+root = "InboxMain"
+srcDir = "examples"
diff --git a/packages/alchemy-lean/lean-toolchain b/packages/alchemy-lean/lean-toolchain
new file mode 100644
index 00000000000..00f848359b1
--- /dev/null
+++ b/packages/alchemy-lean/lean-toolchain
@@ -0,0 +1 @@
+leanprover/lean4:v4.36.0
diff --git a/submodules/distilled b/submodules/distilled
index f0b37d720d0..e41601f3e50 160000
--- a/submodules/distilled
+++ b/submodules/distilled
@@ -1 +1 @@
-Subproject commit f0b37d720d0b567ed2563a2bc0e926b72f6fdc95
+Subproject commit e41601f3e5037f28285ab5bb83129367832a47f8