flang the compiler proves your program cannot hang 0.9.0 GitHub Try in the browserTry it Русский

The link shortener: a service and a client

This page shows an example made of two flang programs: how to run each, what it answers and what is proved about it.

The programs are written in the Russian words of flang, and their routes, messages and report lines are Russian too; they are quoted here as they are.

The files of the service

filewhat is in it
store.flangthe store: codes, addresses, the visit counter
service.flangroutes, request parsing, building the response, the postconditions
plan.flanga plan: one request from a file, the response into a file
plan-network.flanga plan: the service on the socket 127.0.0.1:39281
plan-durable.flanga plan: the service on the socket 127.0.0.1:39283 with a log on disk
server.flangthe same service as three processes under a supervisor
server-network.flangthe same processes on top of the network plan
handler-without-budget.flanga deliberately wrong program: check rejects it

HTTP is parsed by the library flang/stdlib/http.flang.

What the service answers

methodpathresponse
GET/здоровье (health)200 живой (alive)
GET/ссылки (links)200, a line per link: code, address, number of visits
POST/ссылки201 and the code; body адрес=… (address) and an optional код=… (code)
GET/с/{code}301 and Location; the visit is counted
DELETE/ссылки/{code}204

Errors: 400 — bad request, 404 — no such path or code, 405 — wrong method for a known path, 409 — the code is taken, 413 — the body is longer than 2048, 422 — the address is neither http nor https, 431 — the headers are too large.

How to run

The examples written inside the functions:

flang test docs/examples/web/shortener/server.flang
docs/examples/web/shortener/server.flang: примеров 329, прошло 329, не прошло 0

329 examples, 329 passed. The count includes the examples of the imported modules.

One request through files

The plan plan.flang reads a request from mail/request.txt and writes the response to mail/response.txt:

flang io docs/examples/web/shortener/plan.flang --in-dir --trust
на веру: доказанность не считалась — запуск по ключу --trust
{"plan":"Обслужить через файлы","result":86,"orders":2,"log":[…]}

The first line is a warning: the plan was run without checking the proofs. In the second, orders is the number of effects carried out: read a file and write a file. After the run the response file holds:

HTTP/1.1 201 Created
Content-Type: text/plain; charset=utf-8
Content-Length: 3

к1

The flag --in-dir forbids the plan any path outside the program's directory. The flag --trust is needed because not every postcondition of the service is proved. Without it flang io returns exit code 3:

не доказано: утверждений 163: доказано 92, сетка 69, на веру 2 — запуск только по явному согласию: --на-веру

Of 163 postconditions 92 are proved, 69 are checked on tests only («сетка») and 2 are accepted without proof. --на-веру is the Russian spelling of --trust. The 163 include the postconditions of every imported module, together with the HTTP library.

The service with a log, on a socket

plan-durable.flang listens on 127.0.0.1:39283. Before answering each state-changing request it appends the request to the file служба.wal next to the program. The log appears in the example directory. To avoid writing into the clone of the repository, copy docs/examples/web/shortener/, docs/examples/wal/ and flang/stdlib/ to a separate directory with the same relative paths.

cd docs/examples/web/shortener
flang io plan-durable.flang --in-dir --trust --max-orders 100000 &

A request without a body can be sent with curl:

$ curl -i http://127.0.0.1:39283/здоровье
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 10

живой

A request with a body cannot: the service counts the Content-Length of an incoming request in characters, while curl and a browser count bytes (see "What the service cannot do"). Below, the requests are sent into the socket as they are, with the length in characters:

POST /ссылки HTTP/1.1
Host: x
Content-Length: 23

адрес=https://пример.рф
HTTP/1.1 201 Created
Content-Type: text/plain; charset=utf-8
Content-Length: 3

к1

Two visits to GET /с/к1 give two responses:

HTTP/1.1 301 Moved Permanently
Content-Type: text/plain; charset=utf-8
Location: https://пример.рф
Content-Length: 0

After them, GET /ссылки:

HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 32

к1	https://пример.рф	2

Now stop the service (kill its process id) and start it with the same command. GET /ссылки answers the same: the link and the counter 2 are restored from the log. The log holds the requests themselves, one record per state-changing request:

#1:77:POST /ссылки HTTP/1.1
Host: x
Content-Length: 23

адрес=https://пример.рф;#2:31:GET /с/к1 HTTP/1.1
Host: x

;#3:31:GET /с/к1 HTTP/1.1
Host: x

;

Recovery is handling the log records again, in order. This works because the handler always terminates and does no input or output: the same request on the same store gives the same response. The log format is described on Write-ahead log.

If the log did not accept a record, the plan answers 503 and keeps the previous store: a 201, 204 or 301 response is built only in the branch where the host replied «Записано» (written). This is visible in the function «После записи в журнал» and its examples. It was not checked by a run with a failing disk.

What is proved

flang check docs/examples/web/shortener/service.flang --proof
docs/examples/web/shortener/service.flang: доказано не всё — доказано 5, проверено только на тестах 3, не доказано 0, ложно 0 (постусловий и утверждений 8); независимая проверка повторила 0 из 5 — код возврата 3
docs/examples/web/shortener/service.flang: независимая проверка не повторила ни одного: файл ввозит модули, а такие файлы независимая проверка пока не проверяет
…
модуль «Link service»: функций 24, завершение доказано у 24
…
итог: постусловий и утверждений 8 — доказано 5, проверено только на тестах 3, не доказано 0

Of the eight postconditions of the file five are proved and three are checked on tests only; hence exit code 3. Termination is proved for all 24 functions. The independent check replayed none of the proofs: it does not yet check files that import other modules.

Proved for all inputs:

postconditionfunction
«код ответа из объявленного набора» (the status code is from the declared set)«Код исхода»
«пояснение кода непусто» (the reason phrase is not empty)«Код исхода»
«успех исхода и успех кода — одно и то же» (a successful outcome and a successful code are the same thing)«Исход успешен»
«октетов от одного до четырёх» (one to four octets)«Октетов в знаке»
«печать ответа начинается версией, кодом и пояснением» (the response starts with the version, the code and the reason)«Напечатать ответ службы»

The first three are proved by case analysis on the type «Исход»: it has ten variants, and each one is considered.

Checked on tests only:

postconditionfunction
«урезанное не длиннее предела» (the truncated text is no longer than the limit)«Урезать»
«тело ответа не длиннее заявленного предела» (the response body is no longer than the declared limit)«Тело решения»
«в печати ответа длина тела названа в октетах» (the response gives the body length in octets)«Напечатать ответ службы»

All three are about a slice of a string and about a substring; the proof kernel has no rules for them.

The other files:

filefunctionstermination provedpostconditionsprovedreplayed by the independent check
store.flang1212111
server.flang750——
shortener-client/client.flang3232434332

The report counts only the postconditions of the file itself, without the imported modules.

What this does not prove:

A handler without a step limit

The handler of a process must either be marked тотальная (total), or the process must name a step limit with the line с запасом N витков. handler-without-budget.flang does neither:

flang check docs/examples/web/shortener/handler-without-budget.flang
FLANG_HANDLER_NOT_TOTAL в файле docs/examples/web/shortener/handler-without-budget.flang, строка 13, столбец 1: обработчик «шаг разбора» процесса «Разборщик» не помечен тотальным, и запаса витков процесс не называет: строки «с запасом N витков» нет. Оборвать такой пробег планировщику нечем

The error says that the scheduler has no way to stop such a handler. The second error is FLANG_UNCOVERED_FAILURE: a process with such a handler is not under a supervisor. The exit code is 1.

What the service cannot do

The service also understands Cyrillic paths in encoded form: GET /%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8 answers the same as GET /ссылки.

The client in a tab

client.flang is the whole application: 32 functions and 51 examples. The state is one record, «Стойка», with five fields. The handler is pure: for a reply from the host it returns the new state and the next effect — «Показать» (show), «Ждать событие» (wait for an event) or «Запросить» (request). So all the examples run without a browser and without a network:

flang test docs/examples/web/shortener-client/client.flang
docs/examples/web/shortener-client/client.flang: примеров 51, прошло 51, не прошло 0

flang check --proof on the client: termination of all 32 functions is proved; there are 43 postconditions and all 43 are proved. The independent check replayed 32 proofs out of 43; the other 11 are accepted from the kernel without re-checking.

The page is served by a stand, also written in flang. Run the commands from the root of the clone of the repository:

sh docs/examples/web/build.sh
flang io docs/examples/web/stand.flang --max-orders 100000 --trust

build.sh translates client.flang into JavaScript next to the page; the stand listens on 127.0.0.1:8908. The page is http://127.0.0.1:8908/docs/examples/web/shortener-client/index.html.

The client is not connected to the service. It requests /ссылки from the address it was loaded from, that is, from the stand, and the stand answers 404 on that path. The service listens on another port, and calling it from the page is prevented by what is listed above: no CORS, body length in characters.

One more limitation: the effect «Показать» writes text to the screen, but the program cannot write into an input field. After «очистить» (clear) the program considers the field empty, while the field still shows the old text.

Next