Specs: a business rule that is proved
This page shows how to write a business rule as a line of a program and what the compiler proves about it. The rule stands at a function after the word обеспечивает (ensures). Change the function so that the rule no longer holds, and the check fails.
The example is a marketplace API made of three services and a gateway, in the directory docs/examples/web/marketplace/ of the repository. The ordinary command flang check checks it. The programs are written in the Russian words of flang and are quoted as they are.
The spec catalogue in the section "A second rule must not cancel the first" is experimental. Its check runs only from a clone of the repository, through flang run-script, and it fails today.
What a rule looks like
A function from the cart service (cart.flang) — "discount in percent", with the rule "the discount is only zero, five or ten percent":
тотальная функция «Скидка в процентах»
принимает сумма: число
возвращает число
для всех сумма обеспечивает «скидка бывает только нулевая, пятипроцентная или десятипроцентная» ((результат равен 0) или (результат равен 5)) или (результат равен 10)
пример «мелкая покупка без скидки»
дано сумма равно 100000
ожидается 0
пример «от пяти тысяч — пять процентов»
дано сумма равно 500000
ожидается 5
пример «от двадцати тысяч — десять процентов»
дано сумма равно 2000000
ожидается 10
если сумма не меньше 2000000
то 10
иначе (если сумма не меньше 500000 то 5 иначе 0)
| part | what it is | what checks it |
|---|---|---|
обеспечивает «name» condition | a postcondition: a rule about the result | the compiler proves it for all inputs; when it cannot, the report says so |
требует «name» condition | a precondition: a condition on the input (requires) | checked at the call; a violation is the error FLANG_PRECONDITION |
пример … ожидается … | a sample (example … expected …) | computed on every check of the file |
тотальная | the function ends on every input (total) | the compiler proves it |
The name is what a postcondition is found by in the report.
The rule is written as a list of values. The bound "the discount is at most ten" would be worse: a function that always returns zero satisfies it too.
The words обеспечивает, требует and пример are explained on the page Language reference.
How to check
$ flang check docs/examples/web/marketplace/orders.flang --proof
модуль «Orders service»: функций 7, завершение доказано у 7
постусловие «из конечного состояния переходов нет» функции «Переходы из» — доказано индукцией
постусловие «из конечного состояния не разрешён никакой переход» функции «Переход разрешён» — проверено только на тестах (примеров 4)
постусловие «у состояния есть непустое название» функции «Название состояния» — доказано индукцией
итог: постусловий и утверждений 3 — доказано 2, проверено только на тестах 1, не доказано 0
docs/examples/web/marketplace/orders.flang: доказано не всё — доказано 2, проверено только на тестах 1, не доказано 0, ложно 0 (постусловий и утверждений 3); независимая проверка повторила 2 из 2 — код возврата 3
…
The exit code is 3: one postcondition is not proved. Every postcondition in the report has one of these verdicts:
| verdict | what it means |
|---|---|
| доказано (proved) | true for all inputs |
| доказано индукцией (proved by induction) | the same; the proof took every variant of the type apart |
| проверено только на тестах (примеров N) (tested only, N examples) | computed on N of the author's examples; not a proof |
| не доказано (not proved) | neither a proof nor examples |
| ложно (false) | an input was found on which the postcondition fails |
«Независимая проверка повторила 2 из 2» means that a separate program, checker, re-checked both proofs.
Two postconditions are proved by induction over a type. The order states are declared as variants, and the proof takes each one apart:
тип «Состояние заказа»
вариант «Создан»
вариант «Оплачен»
вариант «Собран»
вариант «Отправлен»
вариант «Получен»
вариант «Отменён»
Were the state a string ("paid", "shipped"), taking every case apart would be impossible: there are infinitely many strings.
The third postcondition is tested only. The body of «Переход разрешён» (transition allowed) folds a list computed from the parameter («Переходы из» от откуда), not the parameter itself. The proof kernel does not build an induction over the parameter here.
Without --proof the command prints only the counts and returns exit code 0:
$ flang check docs/examples/web/marketplace/orders.flang
модуль «Orders service»: функций 7, из них с доказанным завершением 7; типов 2
docs/examples/web/marketplace/orders.flang: проверено — доказано 2, проверено только на тестах 1, не доказано 0 (постусловий и утверждений 3); замечаний нет
What is proved across the whole example
| file | what is in it | functions | postconditions | proved | tested only | --proof exit code |
|---|---|---|---|---|---|---|
catalog.flang | goods, price, stock | 8 | 1 | 1 | 0 | 0 |
cart.flang | items, the bill, the discount | 8 | 5 | 2 | 3 | 3 |
orders.flang | order states and transitions | 7 | 3 | 2 | 1 | 3 |
gateway.flang | routes and response codes | 17 | 2 | 2 | 0 | 0 |
Termination is proved for all 40 functions. The report counts only the postconditions of the file itself: those of the modules it uses and of the HTTP library are not in it.
The independent check repeated the proofs in catalog.flang and orders.flang. The files cart.flang and gateway.flang use other modules, and the independent check does not handle such files yet.
The gateway takes the text of an HTTP request and returns the text of the response:
тотальная функция «Обслужить»
принимает витрина: «Витрина», текст: строка
возвращает «Обслуживание»
The gateway does not open a socket: flang io accepts connections. The same scheme on a real socket is shown on the page The link shortener.
Both postconditions of the gateway are about response codes, and both are proved by induction over the type of outcomes:
тип «Исход»
вариант «Готово»
вариант «Создано»
вариант «Очищено»
вариант «Запрос негоден»
вариант «Нет такого»
вариант «Метод не тот»
вариант «Товара не хватает»
вариант «Тело велико»
вариант «Переход запрещён»
постусловие «код ответа из объявленного набора» функции «Код исхода» — доказано индукцией
постусловие «пояснение кода непусто» функции «Код исхода» — доказано индукцией
For a client of the service this means: there are exactly as many response codes as the set holds; 500 is not among them; every code has a reason phrase.
What happens if a rule is broken
Change one line in the gateway's code table: let «Товара не хватает» (not enough stock) answer 500 instead of 409.
$ flang check docs/examples/web/marketplace/gateway.flang --proof
…
FLANG_PROOF_STEP, строка 101, столбец 10: шаг 1, база «Товара не хватает» теоремы «код ответа из объявленного набора»: пример «товара не хватает — четыреста девять» не проходит: нарушено свойство «код ответа из объявленного набора» функции «Код исхода». Утверждение на этом значении неверно, значит случай им не закрывается. …
FLANG_PROOF_STEP, строка 125, столбец 10: шаг 1, база «Товара не хватает» теоремы «пояснение кода непусто»: пример «товара не хватает — четыреста девять» не проходит: нарушено свойство «код ответа из объявленного набора» функции «Код исхода». …
docs/examples/web/marketplace/gateway.flang: не проверено — ведомость не печатается у программы с замечаниями
The exit code is 1. Both errors name the variant «Товара не хватает» and the postcondition that fails on it. The last line means: the proof report («ведомость») is not printed while the program has errors. Before each error the compiler adds a line saying that the place is named without a file name; it is left out here.
A spoiled example is found the same way. Change an expected value in the catalogue: let a stock of 5 with a request for 2 give out 3.
$ flang check docs/examples/web/marketplace/catalog.flang --proof
FLANG_EXAMPLE: пример «остатка хватает» функции «Сколько выдать»: значение не совпало с ожидаемым: ожидалось 3, получено 2
docs/examples/web/marketplace/catalog.flang: не проверено — ведомость не печатается у программы с замечаниями
A second rule must not cancel the first
This part is experimental and works only in a clone of the repository.
Rules grow in number. The directory fspec/spec/ of the repository holds 43 specs of a business domain. A new spec brings in the one it rests on with a использует (uses) line. The check of the catalogue answers a question that flang check on one file does not see: did the earlier rule stay proved after the new one arrived.
flang run-script specs:check
Today the command answers бед в системе спек: 78 ("errors in the spec system: 78") and exit code 1. 69 of the 78 errors are of one kind: the check does not find the earlier spec's postcondition in the new spec. The cause is that the check --proof report does not contain the postconditions of the modules a file uses. So the error appears on every spec with a использует line, even when nobody cancelled a rule.
How the catalogue is built and what exactly it compares is described on the page The spec catalogue.
A rule in another language
A postcondition can be repeated in the language of those who read it. The language tag stands in the name:
обеспечивает «zh: 折扣不超过 30» результат не больше 30
It is a separate postcondition, proved like the others. The catalogue check compares the condition of the translation with the condition of the main postcondition. It does not read the translation itself: a wrongly translated name with the right condition passes.
Next
- The spec catalogue — how specs are gathered into a catalogue and what checks it.
- What is proved and what is not — where the boundary runs.
- The kernel refused: whose mistake is it — what to do when there is no proof.