# Shared state by replay Several visitors share one state, with no merge logic. A single writer, the sequencer, puts messages into one ordered, append-only log on the server. Every tab replays that log with the same compiled Lean step function and shows its own unconfirmed messages on top (the optimistic view). A multi-user interleaving is then just a list of (sender, message) entries. So a rule an app has proved for every such list holds for the shared state each tab's program hands to its view, whatever the server and the network do. Section 5 says exactly what is proved, about what, and what is not. ``` tab A sequencer tab B confirmed = replay of log[0, seen) log = [(sender, message), ...] confirmed = replay of log[0, seen') view = confirmed + pending appends a message only if it view = confirmed + pending is the next one of its sender; does not run the app --- my pending messages; the log from `seen` ---> <------------- a slice of the log --------------- ``` What this version is: a library, a sample app and their proofs and tests. The log lives in the memory of the server process and is gone when the process ends. There is no login: a visitor is a tab, and a reload is a new visitor. Tabs poll once a second: as a rule a change shows in the other tabs within a second, and within about two when it had to wait for its own tab's next request (section 4). The sample app is the site's page `/together/` (section 6). | Module | What it is | Its theorems | |---|---|---| | `LeanUI.Sync` | `Machine` (the shared step), `Op`, the model sequencer `Server`, `Client` (one tab), `Codec` | `LeanUI.Proofs.Sync` | | `LeanUI.Sync.Sequencer` | the sequencer a server runs (an array and a hash map) | `LeanUI.Proofs.SyncSequencer` | | `LeanUI.Sync.Proto` | the text format of the round trips | `LeanUI.Proofs.SyncProto` | | `LeanUI.Sync.Room` | everything a server decides about a request, as pure functions: identity, epochs, limits | `LeanUI.Proofs.SyncRoom` | | `LeanUI.Sync.App` | `Shared`: a shared app as an ordinary `Program` (the tab's side of the round trips) | `LeanUI.Proofs.SyncApp` | | `LeanUI.Server.Sync` | `SyncRoom.route`: the HTTP route around the room's functions | none: tested | | `examples/Together.lean` | the sample: a sign-up sheet | `examples/TogetherProofs.lean` | ``` lake build # checks every proof (the proof modules are default targets) .lake/build/bin/leanui-sync-tests # [--long] [--seed N]: the simulation .lake/build/bin/leanui-server-tests # the route of a room, among the server's tests ``` The JavaScript runtime and the patch protocol (`docs/PROTOCOL.md`) know nothing about shared state: a shared app is a `Program` that uses `Cmd.fetch` and `Sub.every`. ## 1. Writing a shared app `examples/Together.lean` is a sign-up sheet: a few shifts with a fixed number of seats; a visitor takes a seat, leaves theirs, or clears the sheet. Its theorems are in a second module, `examples/TogetherProofs.lean`. The two start like this: ```lean module -- examples/Together.lean public import LeanUI public import LeanUI.Sync.App meta import LeanUI.Syntax -- for a view written as a template @[expose] public section open LeanUI Attr -- `Sync.Machine` below is `LeanUI.Sync.Machine` ``` ```lean module -- examples/TogetherProofs.lean public import Together public import LeanUI.Proofs.Sync -- Machine.run_inv public import LeanUI.Proofs.SyncApp -- Shared.shown_inv, Shared.after @[expose] public section namespace Together.Proofs open Together.Seats LeanUI.Sync -- `State`, `step`, `machine` of the sheet ``` The definitions must be exposed (`@[expose]`). With the plain `public section` of the guide the app builds and runs, but a proof in another module cannot unfold its `step` or its `machine`. **The machine** is the shared half of the app: a state and a step. The step is told who sent each message: the id the sequencer recorded with the log entry, after it checked the tab's secret. (Together's is in the namespace `Together.Seats`.) ```lean structure State where seats : List (Nat × Nat) := [] -- (shift, visitor), in the order the seats were taken inductive Msg where | take (shift : Nat) | leave | clear def step (who : Nat) : Msg → State → State | .take k, s => if (taken k s).length < cap k && !(holders s).contains who then { seats := s.seats ++ [(k, who)] } else s | .leave, s => { seats := s.seats.filter (·.2 != who) } | .clear, _ => {} def machine : Sync.Machine State Msg := { init := {}, step } ``` Rules for a machine, which nothing checks for you: * The step has no effects: it returns a state and no command, so a tab may replay a message any number of times. * Every tab must compute the same state from the same log. Keep the state and the step to `Nat`, `Int`, `String`, `List` and the like. No `Float`: its results can differ between builds. * The step must make sense for any message from any sender. Whoever has joined can put any string into the log under their own id. **The codec** writes a message into the log (`enc : μ → String`) and reads it back (`dec : String → Option μ`). A string that does not decode changes nothing (`Machine.wire`), so `dec` should refuse everything that is not a message. An encoded message may be any text of at most 1,000 bytes (`Proto.maxMsgBytes`); a longer one is never queued. Every tab runs `dec` on every entry of the log, whoever wrote it, so it should be cheap on any input (Together's does not read a shift number of more than three digits). Nothing proves that `dec` reads back what `enc` wrote; a message has the effect its user chose only if it does. ```lean def codec : Sync.Codec Msg := { enc, dec } -- "t 2", "l", "c" ``` **The app** adds what stays in the tab: local state `L`, the UI's messages `ι`, how a UI message changes the local state and which shared messages it sends, and the view. ```lean abbrev Msg := Sync.Msg Ui -- the program's messages: the UI's, ticks, responses def app : Sync.Shared Seats.State Seats.Msg (Option Nat) Ui := -- local: the shift last asked for { machine := Seats.machine, codec := Seats.codec, initLocal := fun _ => none, update := uiUpdate, view } def program : Program (Sync.Model Seats.State (Option Nat)) Msg := app.program ``` `update : ι → L → σ → L × List μ` sees the shared state the tab shows now. `view : L → σ → Status → Html (Sync.Msg ι)` wraps its handlers in `.ui`. `initLocal` is handed the page's flags: what the page's script passes to `LeanUI.start({ flags: ... })` (the page `tools/build-app.sh` writes passes none), or `Site.flags` for a page the server renders. `program` is built and served like any other LeanUI app. `Sync.Msg.online` is **the offline switch**: a control a view may offer (Together has a checkbox). It is not the browser's connection state. While it is off, the tab sends nothing and drops the `sync` replies that still arrive; what its user does stays pending. **The status** is what a view may show about the connection (`Sync.Status`): | Field | Meaning | |---|---| | `id : Option Nat` | the tab's id once it has joined ("Visitor 3"); `none` before | | `online` | the offline switch is on | | `lost` | the log this tab replayed is gone (the server was restarted, or the room started over at a limit); the tab has stopped (it asks nothing, and drops every `sync` reply that still arrives, a late one of the old log too), and a reload joins the new log as a new tab | | `paused` | no input for three minutes: the tab has stopped asking, until the next input | | `pending` | own messages the log has not confirmed | | `full` | the queue of unconfirmed messages is full (500): shared messages are not queued until some are confirmed | | `seen`, `syncs`, `replays`, `errors` | log entries received; replies applied; replies that put other tabs' entries under pending messages; requests that failed, whose reply could not be read, or that were given up | Before the tab has an id, after the log is lost and while the queue is full, the program drops the shared messages `update` returns (the local state it returns is kept). A view should disable its controls then, as Together does. The shared messages of one UI message are taken one by one: with room for fewer, only the first ones are queued, and one of more than 1,000 bytes is left out alone, with nothing in the status to show it. **The server** keeps a room and mounts its route in front of the app's files: ```lean let room ← SyncRoom.new -- or SyncRoom.new { maxLog := 2000 } serve {} (Route.under "/together" (Route.first [room.route, Static.route { root := "dist/together" }])) ``` The tab asks `join` and `sync` relative to its page, so the page must be served at a URL that ends in `/` (`Static.route` redirects `/together` there). A room knows nothing about the app: it orders strings. **A rule.** Prove it for the step, get it for every list of entries with `Machine.run_inv`, and for the shared state the real program hands to its view with `Shared.shown_inv`: ```lean def Ok (s : State) : Prop := (holders s).Nodup ∧ ∀ k, (taken k s).length ≤ cap k theorem step_ok (who : Nat) (m : Seats.Msg) (s : State) (h : Ok s) : Ok (step who m s) theorem run_ok (es : List (Nat × Seats.Msg)) : Ok (machine.run machine.init es) := machine.run_inv Ok ⟨List.nodup_nil, fun _ => Nat.zero_le _⟩ step_ok es theorem program_ok (flags : String) (msgs : List Together.Msg) : Ok (Together.app.shown (Together.app.after flags msgs)) := Together.app.shown_inv Ok run_ok flags msgs ``` `program_ok` reads: after every list of the program's messages (clicks, timer ticks, responses of any status and any body), the sheet the program hands to its view has no shift with more people than seats and no visitor id in two seats. "Nobody holds two seats" is about ids, which are tabs: the rule cannot know that two tabs are one person. `tests/Sync.lean` has two more apps of a few lines each (`board`, whose messages are arbitrary text, and `twice`, which has local state and sends two shared messages per event), and helpers that drive one tab of any shared app against the room's functions (`Prog.open_`, `Prog.tell`). The helpers are part of the test executable's own module: a test of another app copies them. **What a shared app cannot do in this version.** `Shared.update` returns no command and the wrapper owns the subscriptions, so a shared app cannot focus a field, use storage or run a timer of its own. `update` gets neither the tab's id nor the status; only the view does. `Sync.Msg` clashes with an app's own `Msg` when both namespaces are open. ## 2. The round trips `LeanUI.Sync.Proto` is the format, used by both sides. A body is **rows** separated by line breaks (U+000A); a row is **fields** separated by single spaces; a field is a decimal number or an escaped message. Escaping writes a backslash as `\\`, a line break as `\n` and a space as `\s`, so no message text can end a field or a row: a message with a line break stays one message. | Request | Body | Reply (200) | |---|---|---| | `POST join` | empty | one row: ` ` | | `POST sync` | ` `, then one row per pending message it carries | ` `, then one row ` ` per log entry from index `start` | One request does both directions: "my pending messages; the log from where I am". `start` is the number of log entries the tab has. The message in row `k` is the tab's own message number `firstSeq + k`, counted from 0; the sequencer appends a message only if it is the next one of its sender, so a request may be sent again, arrive twice or arrive out of order. A tab sends a prefix of its pending messages: at most 200 messages and 1,000 bytes of them (as UTF-8, before escaping) per request. The reply's first row ends with `more`: `1` if the room's log goes on beyond the last entry of the reply (the room cut the reply at `maxReply` entries), `0` if the reply reaches the end of the log. The room takes it from the log after it appended the request's own messages. It tells a tab that is behind whether to go on reading at once (section 4). ``` POST /together/sync 200 7731 3 2914...8801 40 5 7731 40 0 t\s0 1 l l 3 t\s0 3 l ``` Here tab 3 has 40 entries and sends two messages; the reply brings another tab's entry and its own two, and the log ends there. Had the log gone on beyond the reply, its first row would be `7731 40 1`. Other answers: `409` the request's epoch is over (the tab shows `lost`); `403` an id this epoch did not give out, or not its secret; `400` not a request (or not UTF-8); `413` too large. Every answer of the room has `Cache-Control: no-store`. Two answers on these paths are not the room's and do not have it: the adapter's `413` for a body over `Config.maxBody`, and the `404` for a request that is not a `POST`. The decoders refuse a body they cannot read whole. They are lenient in what counts as a number (`String.toNat?` also reads `07` and `1_0`), and a backslash before any other character stands for that character. `more` is read to the letter: a reply whose first row has two fields, or any other text in the third, is not a reply, and a tab counts it as a failed request. ## 3. The room `LeanUI.Sync.Room` is a state and one pure function per kind of request, each from a state to the new state and an answer: `Room.join`, and `Room.sync` (a gate, `Room.admit`, then the sequencer's work, `Room.accept`). `Room.step` applies one of the two. `LeanUI.Server.Sync` applies `Room.step` to the state in one atomic step (`IO.Ref.modifyGet`: that is the single writer) and writes the answer with the status and the body the room gives it (`Answer.status`, `Answer.body`). Every request is answered at once, with what the room holds when it arrives. **Identity.** `join` gives a tab the next id of the epoch and a secret of 128 bits from the operating system's random source (`IO.getRandomBytes`). Every later request carries both, the gate compares them, and what a request submits goes into the log under its own id. So a tab cannot write as another tab without that tab's secret. The secret travels in every request body: serve a room over HTTPS. **Epochs.** One life of the log is an epoch. A new room draws its first epoch at random (64 bits), so tabs of an earlier server process are refused; each time the room starts over the epoch goes up by one. Every `sync` request carries its epoch, and a request for another epoch is refused with `409`. **Limits** (`Sync.Limits`, the argument of `SyncRoom.new`). Each one is explicit, and what happens at each is crude. | Limit | Default | At the limit | |---|---|---| | `maxBytes`: bytes of a request body | 2,400 | refused with `413`; nothing changes | | `maxMsgs`: messages in a request | 200 | refused with `413`; nothing changes | | `maxMsgBytes`: bytes of a request's messages together (as UTF-8, before escaping) | 1,000 | refused with `413`; nothing changes. So no log entry is longer than this | | `maxReply`: log entries in a reply | 500 | the reply carries the first 500 from the request's `start` and says that the log goes on (`more`); a tab to which the reply brought new entries asks for the next ones at once (section 4) | | `maxIds`: ids given out in an epoch | 1,000 | the next `join` starts the room over, and is its first id | | `maxLog`: log entries in an epoch | 10,000 | a request that would make the log longer appends nothing, starts the room over and gets `409` | The products are what a server and a tab have to carry. A log holds up to `maxLog × maxMsgBytes` bytes of messages (10 MB with the defaults), which every tab that opens downloads and replays; a reply holds up to `maxReply × maxMsgBytes` (0.5 MB), which escaping at most doubles on the wire. The defaults of `maxMsgs` and `maxMsgBytes` are what a tab sends at most (`Proto.request_fits`), and the default of `maxBytes` leaves room for the largest body such a request can have (about 2,300 bytes; tested, not proved). A tab that opens reads the log in back-to-back round trips of up to 500 entries each, and shows an older sheet until it has all of it: a reply that was cut at 500 entries says that the log goes on, and the tab asks again at once; after the reply that says the log ends, a tab with nothing to send asks no more until its next tick. In Chromium on localhost a new tab had a full log of 10,000 entries 0.24 to 0.40 s after its page began to load when the entries had 3 bytes, and after 1.5 to 2.3 s when they had 1,000 bytes (10 MB in all); it had joined after 0.10 to 0.23 s (five and seven runs; CI machine, to be re-measured on the reference Mac; the slower runs were taken while other work was running on it). It made 20 `sync` requests in a row: in the six runs that recorded every reply, 19 replies of 500 entries said that the log goes on, the twentieth that it ends, and the next request was the next tick's. A room that **starts over** takes the next epoch and drops its log and its ids. Every tab of the old epoch gets `409` at its next request, shows `lost` and stops; what it had pending never reaches a log. What follows from that, and is not prevented: anyone can join; anyone can make the room start over, by joining 1,000 times or, with far fewer requests, by filling the log (fifty requests of 200 messages each fill it, and the next message starts the room over). Every `join` that reaches the room uses up an id, also when its reply is lost, and every page load is a `join`: in ordinary use too, the load after the thousandth of an epoch starts the sheet over for everybody. The HTTP adapter reads a request body of up to `Config.maxBody` (1 MiB by default) before the room sees its size, and the room reads a body of up to `maxBytes` inside its atomic step before it can refuse it (a number in it may have as many digits as the body has bytes). The limits of a room should not be set below what a tab sends (up to 200 messages and 1,000 bytes of them, in a body of up to about 2,300 bytes), or the tab's own requests are refused. ## 4. The tab `Shared.program` owns the `Client`, the requests and one timer. **The tab polls.** Once it has joined, a tab sends one `sync` request at every tick of its timer (`pollMs`: one second) and one at once when its user sends a shared message. After a reply it asks again at once only while it is behind or has more to send ("No request in a loop", below). It waits for one request at a time: what its user does while a request is in flight goes with the next one. A reply may be late or stale: the tab uses only the entries past what it has, and ignores a reply that would leave a gap. So a change that is in the log shows in another tab at that tab's next tick, up to a second later. In Chromium on localhost, 715 of 720 clicks had shown in every other tab of their room after at most 1.01 s, and the other five after 1.8 to 1.9 s (CI machine, to be re-measured on the reference Mac; "How late a change shows", at the end of this section, has the runs, why a click can take two seconds, and what a longer round trip does). A server gets one request a second from every tab that is asking, whether anything changed or not. Where it was measured (CI machine, to be re-measured on the reference Mac), the native server spent about 2 ms of CPU on a `sync` request with nothing new, and 0.5 to 0.7 ms when it was confined to one CPU: at one request a second from each tab, a quarter of a core is used up by about 105 to 135 tabs, or about 430 to 540 with the server confined ("What polling costs a server", at the end of this section). **No request in a loop.** After the `join` reply the tab sends its first `sync` request at once. After that, a request follows a reply at once if and only if the reply brought the tab log entries it did not have and there is more to do: the reply says that the log goes on (`more`), or the tab still has messages to send (the rest of a long queue, or what its user did while the request was in flight). So: * a tab that is behind reads the log in back-to-back round trips, and the reply that says the log ends is followed by a request only if the tab has messages to send; * a tab with a long queue sends it in back-to-back round trips (a room's reply to a request that carried messages holds entries the tab does not have); * a tab that only listens asks once per tick however fast the log grows, unless more than one full reply of entries arrived since its last request; * a shared message of a tab's own user costs that tab at most one request: it goes out at once, or with the tab's next request while one is in flight, and the reply that confirms it is followed by another only if the log goes on beyond it or more messages wait; * a reply that brings the tab nothing new is never followed at once, whatever it says: an empty one, a stale one or one that arrives twice, an error, entries the tab already has. The next request then waits for a tick of the timer or for the user: a shared message is sent at once, and so is a request when the user turns the offline switch on or resumes a paused tab (while a request is in flight, they wait for the next one). A message of the app's UI that stays in the tab (a keystroke in a draft field, say) starts no request. So after its first `sync` request, every request of a tab that is not paced by the timer or caused by its user is paid for by at least one new log entry, of which a room's log holds at most `maxLog`: a server that answers at once with nothing new, or with an error, is asked again at the pace of the timer, and once more for each of those inputs. A tab that is paused or switched off, or whose log is lost, issues no request at all. None of this is proved: when a request is issued is tested (section 5). **A request with no answer is given up** after 10 s (`giveUpMs`): the tab counts a failed request and asks again. The tab waits for one request at a time, so without this a connection that hangs would stall it for good. An answer that still arrives is taken like any other reply, and it ends the wait for the request that is current by then. The tab cannot abort the request it gives up (there is no command for that), so the browser keeps its connection until the browser itself ends it. **An idle tab stops asking.** After three minutes without input from its user (`idleMs`) the tab issues no request and stops its timer (`Status.paused`). The next input ends the pause, and the timer runs again: any message of the app's UI, or the offline switch turned either way. A tab whose switch is on after that input is resumed: it asks at once, unless a request of its is still in flight. A tab whose switch is off after it, as when the input was the switch turned off, asks nothing until the switch is turned back on. No input restarts a tab whose log is lost: its timer stays off, and it asks nothing. **The queue is bounded.** A tab keeps at most 500 unconfirmed messages (`maxPending`). While the queue is full, shared messages are not queued and `Status.full` says so. With room for fewer messages than a UI message sends, the first ones are queued. All these times are counted in ticks of the tab's timer. A browser that slows the timers of a background tab stretches them. ### Measured: how late a change shows, what polling costs **How late a change shows.** Measured in Chromium against the native server on localhost, with all tabs in one browser context (one profile) and clicks at random moments (CI machine, to be re-measured on the reference Mac; other work was running on it during part of the runs): with three tabs (240 clicks in five runs), the slower of the other two showed a click after 0.17 to 1.01 s (medians 0.61 to 0.75 s); with nine tabs (480 clicks in six runs), the slowest of the other eight after 0.69 to 1.01 s (medians 0.94 to 0.96 s) and the quickest after a median of 0.07 to 0.11 s. Five of these 720 clicks are left out of those ranges: they took 1.0 to 1.2 s to show in the first of the other tabs and 1.8 to 1.9 s in the last. Of 60 more clicks, between two tabs in separate contexts, none took longer than 1.00 s (medians 0.37 and 0.47 s). Nine tabs of one profile, opened one after another, each loaded in 18 to 85 ms and had joined after 85 to 238 ms. A click can take about two seconds: one that falls while its tab's own request is in flight is not sent at once but with that tab's next request, and that one waits for the next tick when the reply in between brings nothing new. One run recorded every tab's requests, and its slow click (one of 240) was such a click: it came about 3 ms after its tab's request of that tick had started, and went out with the next tick's request, 996 ms after the click. The other four were not recorded that way; their times fit the same case. On localhost a request is in flight for a few milliseconds of every second. Where a round trip takes longer, more clicks have to wait. Measured in Chromium between two tabs in separate contexts, with every `sync` request of both tabs held in the test harness before it went on to the server (120 clicks a setting, in two runs of 60; CI machine, to be re-measured on the reference Mac): held for 100 ms, 13 clicks waited 0.89 to 1.00 s for their tab's next request and showed in the other tab after 1.20 to 1.32 s; held for 300 ms, 39 clicks waited 0.69 to 1.00 s and showed after 1.14 to 1.44 s, which was the longest any click took; with no hold, one click waited. **What polling costs a server.** One request a second from every tab that is asking, whether anything changed or not, and at most one more for each shared message a user sends. Measured with three tabs of one profile (CI machine, to be re-measured on the reference Mac; the counts were the same in every round): while nobody clicked, each tab sent 30 requests in 30 s (four rounds). While the user of one tab clicked every two seconds, for 60 s, that tab sent 90 requests and each of the other two 60 (four rounds): one per tick, and one with each of the 30 clicks. With a click every second, the clicking tab sent 60 requests in 30 s and the others 30 each; with ten clicks a second, 330 and 30 (three rounds each). A tab that only listens asks once a second however fast the log grows, unless more than a full reply of entries (500) arrived since its last request. Measured on the same machine (CI machine, to be re-measured on the reference Mac): while a script appended about 170 entries a second, one per request, each of three listening tabs sent 17 or 18 requests in 17 s (two runs). While it appended as fast as the server answered, about 490 to 640 entries a second, each sent 13 to 17 requests in 8 to 10 s (nine runs): its ticks, and one more after each reply that was cut at 500 entries (6 to 8 such replies per tab in the five runs that recorded them). A tab makes more requests than these while it is behind by more than a reply, or has more to send than one request carried; the exact rule is "No request in a loop", above. With fifty clients that each asked once a second over a kept-alive connection, the native server spent 1.9 to 2.3 ms of CPU on a `sync` request with nothing new: 9 to 11 % of one core for the fifty, about a fifth of a percent per tab. With 200 such clients it spent 1.9 to 2.3 ms a request, 37 to 46 % of a core; with fifty clients whose every request opened a new connection, 3.0 to 3.7 ms. Most of this is what the server spends to answer any request: under the first load a `GET` of a line of text took 1.4 to 1.5 ms and a `GET` of a static file 1.5 to 1.9 ms, while the room's own step on such a request, timed in a loop of its own, takes about 0.005 ms. Where the rest goes is in `docs/SERVER.md`, "CPU per request". The 1.3 ms given there is for a `GET` of a line of text from one client that asks again as soon as it is answered: under that load this server spent 1.1 to 1.5 ms on such a `GET`, and 1.7 to 2.2 ms on a `sync` request. These figures are the server process's own CPU time on a machine with four CPUs, in rounds of 10 to 20 s during which other work took less than half a CPU of that machine: five to eight rounds for each figure (CI machine, to be re-measured on the reference Mac). In busier rounds the fifty clients' `sync` request tended to cost less: 1.6 to 1.9 ms in six rounds with half a CPU to one and a half CPUs of other work, 0.8 ms in one round with three and a half. With the server confined to one CPU (`taskset -c 0`) it cost 0.5 to 0.7 ms in all fourteen rounds. For a small server, at one request a second from each tab, which is what a tab sends while its user sends nothing: a quarter of a core, which is what the site's container has (`docs/DEPLOY.md`), is used up by about 105 to 135 such tabs on four CPUs as above (100 clients took 18.6 to 23.7 % of a core), and by about 430 to 540 with the server confined to one CPU (400 clients took 18.6 to 23.2 % of that CPU). How a vCPU of that container compares with a core of this machine was not measured, nor how many CPUs the container shows the process. What keeps the number down is the idle stop above: a tab that is left open stops asking. ### Left out: long poll A second transport was built, measured and left out: long poll, a waiting request that the server held until the log grew. It keeps one connection busy per tab, and over HTTP/1.1, which the native server speaks, a browser opens about six connections to a host for all tabs of a profile. Measured in Chromium on localhost (CI machine), with the code of the commit named below: with five such tabs of one profile a click showed in another tab after 30 to 105 ms; with six, every click took about 4.7 s, and with seven, every click but the first of each run; an eighth tab had not loaded after one to two minutes, in three runs of three. Three commits earlier, before a change to when a tab issued its requests, one click of 24 with seven tabs had taken 9.6 s, and an eighth tab had not loaded within two minutes, in three runs of three. The code last existed at commit `d3034869517376d1bb95a82411e7add4216cea59`. ## 5. What is proved, tested and trusted Every theorem named here is checked by `lake build`, with no `sorry`, and sits under `#guard_msgs in #print axioms` at the end of its module: the build fails if one of them ever depends on an axiom beyond `propext`, `Classical.choice` and `Quot.sound`. The names are in the namespace `LeanUI.Sync` (the proof modules add to it, so that one can write `machine.run_inv` and `app.shown_inv`); the sample's are in `Together.Proofs`. Each theorem's doc comment is its statement in words; the tables below are summaries. ### Proved about the real program These are about `Shared.program`, the `Program` a browser runs, and about **every list of its messages**: UI events, timer ticks, the offline switch, and responses of any status and any body to `join` and `sync`. They assume nothing about the server, the network, other tabs or identity. | Theorem | Statement | |---|---| | `Shared.shown_is_run` | For every shared app, every flags string and every list of the program's messages, the shared state the program hands to the app's view is the app's machine over strings (`Machine.wire`: a string that does not decode is skipped) run from `init` over some list of (sender, string) entries. | | `Shared.shown_inv` | So a property proved for the app's machine after every list of (sender, message) entries holds for that state. | | `Shared.pending_le` | After every such list the tab holds at most `maxPending` unconfirmed messages. | | `Together.Proofs.program_ok` | The sheet Together's program hands to its view never has a shift with more people than seats, and never a visitor id in two seats. | Not said by these: anything about the `Html` a view builds from that state; that two tabs show the same; that what a user did is in the state. A server that lies can break the last two. What is trusted for them: that the runtime runs a program as `Shared.after` does (`init` once, then `update` on one message at a time, and `view` of the model it has). That is `LeanUI.App`, which `tests/Sync.lean` checks on one short run in the DOM model, and in a browser `runtime/leanui.js`. ### Proved for a model with one honest log `LeanUI.Proofs.Sync` models the whole system: one sequencer, a client for every id, and any list of four kinds of events, in any order: a user acts; an op of a client reaches the sequencer (any of its ops, any number of times, or never); a client receives a slice of the log (any slice, at any time: stale, overlapping, repeated); and something else submits an op under any id, with any number and any message (`inject`). **Assumed by the model**: there is one log, it only grows and is never lost; every reply is a slice of it; a client's state changes only through `Client.act` and `Client.receive`; everybody runs the same step. "A user acts" is `Client.act`: in the real program that is a shared message the tab queued. One it did not queue (no id yet, the log lost, the queue full, a message of more than 1,000 bytes) is not an act of the model, and no theorem below is about it. | Theorem | Statement | |---|---| | `Sys.screen_eq_run` | After every list of events, what client `i` shows is the machine run from `init` over the log prefix it has received, followed by its own pending messages, each with sender `i`. | | `Sys.screen_inv`, `Sys.wire_screen_inv` | So a property proved for every list of entries holds on every screen: optimistic, stale or caught up. | | `Sys.agree` | Two clients that have both received the whole log and have nothing pending show the same state: the replay of the log. | For client `i`, and only for lists of events in which nothing but client `i` submits under id `i` (`OwnId i`): | Theorem | Statement | |---|---| | `Sys.log_once_in_order` | The messages the log holds under id `i` are the first messages user `i` did, each once, in the order they were done. How many of them there are is not part of it. | | `Sys.nothing_lost` | User `i`'s messages in the log prefix `i` has received, followed by `i`'s pending messages, are exactly what user `i` did, in order: on `i`'s own screen nothing is lost or doubled. It does not say that a pending message is ever delivered. | | `Sys.can_converge` | There is a continuation with no new user action and no injection (deliver what is outstanding, then one reply each) after which every listed client has nothing pending, has the whole log, and shows its replay. This is the existence of a schedule, not a promise that a network follows it. | `Sequencer.log_eq` and `Sequencer.slice_eq`: the sequencer a server runs holds the model's log and answers with the model's slices, after any list of submissions. ### Proved about the room and the format, each on its own `LeanUI.Proofs.SyncRoom`, for every state of a room, every body and every setting of the limits. Where a row names the room's invariant, the theorem assumes it; by `Room.inv_run` (last row) a room that started as a new one has it after every list of requests. These are about what the room's functions answer and the state they leave. The lists of requests are folds of `Room.step`, the function the route applies. | Theorem | Statement | |---|---| | `Room.sync_refuses` (with `Room.admit_ok_iff`, `Room.sync_error`) | A body that is not a request, or is one for another epoch, or one without the secret of its id, leaves the state exactly as it was, and is answered with a refusal. | | `Room.accept_eq_model` | An admitted request does what the model sequencer does, in a room that satisfies its invariant (`Room.Inv`) and for a request that leaves the log within `maxLog`: the log afterwards is the model's `submit` folded over the request's ops, and the answer is the model's slice from the request's `start`, of at most `maxReply` entries, with `more` set when that log is longer than `start + maxReply`. | | `Room.accept_more` | The reply to an accepted request says `more` exactly when the room's log, after the request's own messages were appended, is longer than the reply's `start` plus the number of entries the reply carries. For every state and every request. What a tab does with `more` is not in any theorem. | | `Room.join_fresh` | Within the limit, `join` gives the next id (one more than the number of ids given out), with the given secret, and changes nothing else. | | `Room.step_spares`, `Room.run_spares` | For as long as the epoch lasts, a request that does not carry the secret of id `j` under id `j` leaves the log entries under id `j`, and `j`'s secret, as they are, and so does every list of such requests. (Such a request can still start the room over, which drops every entry: a `join` at `maxIds`, or another tab's request at `maxLog`.) | | `Room.admit_tooLarge`, `Room.entries_le`, `Room.join_full`, `Room.accept_log_full` | The answers and the states at the limits: a body over `maxBytes`, or with more than `maxMsgs` messages or `maxMsgBytes` bytes of them, is answered "too large" (and, by `Room.sync_error`, changes nothing); no answer carries more than `maxReply` entries; at `maxIds` a `join` starts the room over, and so does, in a room that satisfies its invariant, a request that would make the log longer than `maxLog`. Not in these theorems: the status codes in the table of section 3 (the route's) and what a tab does next (the wrapper's). Those are tested. | | `Room.inv_run`, `Room.epoch_le_run` | From a new room whose limits allow at least one id, after every list of requests with any bodies, the invariant holds: the room is within `maxLog` and `maxIds`, its table of sequence numbers is right, its log holds nothing under an id that has not been given out, and no entry is longer than `maxMsgBytes`. And the epoch never goes down. | `LeanUI.Proofs.SyncProto`, for every text: | Theorem | Statement | |---|---| | `Proto.unescape_escape`, `Proto.escape_field` | An escaped message holds no space and no line break, and unescapes to itself. | | `Proto.decodeJoin_encodeJoin`, `Proto.decodeRequest_encodeRequest`, `Proto.decodeReply_encodeReply` | Decoding the encoding of any join reply, request or reply gives it back, whatever text its messages hold (a reply with `more` set or not). | | `Proto.request_ops_prefix`, `Proto.request_fits` | The ops of the request a tab builds are a prefix of what the tab has to send: its own id, its oldest pending messages, numbered from the right number. It carries at most 200 messages and 1,000 bytes of them. | `Room.inv_run` (nothing is recorded under an id before it is given out) and `Room.run_spares` (after that, only requests that carry its secret write under it) are what the model's `OwnId` comes to on a server, and `Room.accept_eq_model` is what "replies are slices of one log" comes to, for as long as an epoch lasts. **No theorem joins the pieces**: that tabs, route and network together behave like the events of the model is not proved. The route, HTTP, the browser and the runtime are in between. About Together's step alone: `step_other` (a take or a leave moves only its sender's seat), `step_clear` (a clear empties the sheet, whoever sends it), `take_full_noop` and `take_seated_noop` (a take in a full shift, or by a visitor who holds a seat, does nothing). ### Tested `leanui-sync-tests` (in CI) runs the compiled code, deterministic from a seed: * the format on 4,000 random requests, replies and join replies (texts with line breaks, spaces, backslashes, control characters, characters outside ASCII, and empty ones); * the room's functions against hostile requests (an id nobody was given, a wrong secret, an old epoch, malformed and oversized bodies, huge numbers, requests replayed and reordered, a tab far ahead or far behind) and at each limit, the ones in bytes with characters of more than one byte; what a reply says about the rest of the log, where the log ends exactly at the end of the reply and one entry beyond; * a forged request under another tab's id (when requests carried no secret, one such request made that tab's pending change vanish): it is refused, and the victim's change reaches the log; * a client with 1,100 pending messages, and the program offline for 1,100 clicks; * what the wrapper owes an app, on an app with local state that sends two shared messages per event; the wrapper's rules for when a request is issued, given up or not issued, one by one (among them: which responses are followed by a request at once and which are not, for a tab with nothing pending and for one with messages pending; a new tab that reads a log of several replies with no tick in between and asks nothing after the last; a tab that only listens while another appends an entry per round trip, counted: one request per tick; a server that repeats one reply); * the real program against the room over the text format, through a simulated network that delays and reorders, fails requests, loses responses, delivers some twice, answers with error pages and lets requests hang: a request follows a response at once exactly when the response brought the tab new entries and either says that the log goes on or leaves the tab messages to send, and after a spell of fair delivery every tab is caught up and shows the replay of the log, with everything its user did in the log once and in order; * the program fed arbitrary responses; the program under the real runtime in the DOM model (one short run); both sequencers side by side. `leanui-server-tests` (in CI) calls the route: the statuses and the `no-store` header, the first row of a reply that ends the log and of one that the room cut, the requests the route does not answer, eight tabs that write at once from eight tasks (every message is in the log once, in its tab's order), and a join and a sync over `Std.Http`'s in-memory transport. Of what Together's view renders, `leanui-sync-tests` looks at two things: that it says so when the log is lost, and that every button that sends a shared message is disabled then and while the queue is full. The page as a whole is tested in browsers: `tests/browser/together.mjs` (section 6). ### Trusted, or outside * **Delivery.** That a pending message reaches the log and that a tab catches up depends on the network. It is tested on simulated runs only. * **Durability.** There is none. When the server process ends or the room starts over, the log is gone, and so is what tabs of the old epoch had pending. * **Whether a user got what they clicked.** The rule of the sheet is not the user's intent: a take in a full shift does nothing, and anyone's clear empties the sheet. A shared message the program does not queue never reaches a log: before the tab has an id, after the log is lost, while the queue is full, or when the message is longer than 1,000 bytes (the last without anything in the status). And that an app's `dec` reads back what its `enc` wrote is not proved; for Together it is tested on examples. * **The secret.** That it is not guessed (128 bits from `IO.getRandomBytes`, which is trusted; the room compares secrets with ordinary equality, not in constant time) and not read on the way. Whoever has a tab's secret can write as that tab. * **The glue between the proved functions and HTTP**: `LeanUI.Server.Sync`, `LeanUI.Server.Run` and `Std.Http`, the browser's `fetch`, `runtime/leanui.js` and `LeanUI.App`. * **The server process under many or slow connections.** The room bounds what it keeps. What the process does with its connections is `Std.Http`'s and the runtime's, the same for every route, and none of a room's limits covers it: `LeanUI.Server.Run` keeps `Std.Http`'s limit of 1,024 connections, and a client that asks for a response and does not read it keeps its connection. In a test on localhost, 1,100 clients that asked for the app's 1.3 MB file and did not read it kept the server from answering anyone else for as long as they stayed, and its memory grew to about 880 MB; with 500 such clients it kept answering. Nothing was measured behind a proxy. Since the log lives in this process, whatever stops the process ends the log. * **The text format on bodies no encoder wrote.** The decoders are total and refuse what they cannot read whole; nothing more is specified. * **That every build computes the same step.** Tabs replay the log with the wasm64 build; the tests run the native build of the same definitions. The sequencer does not run the step at all. (Outside CI, `leanui-sync-tests` was also built to wasm64 and run under Node: on the seeds compared, it printed what the native build printed.) * **The usual base**: Lean's kernel, which checks the proofs; Lean's compiler and the C and wasm toolchains, which turn the same definitions into the code that runs; the compiled `Array` and `Std.HashMap`. ## 6. The page: `/together/` The sample app is on the site: `examples/Together.lean` as a client-side app (`tools/build-app.sh TogetherApp together`, in the page `examples/together.html`), with the route of one room in front of its files (`examples/SiteServer.lean`). The room is created when `leanui-site` starts, with the default limits, and lives as long as that process. **What the tab keeps.** The local state is the shift its visitor last asked for, until their next take, leave or clear. A take is not a promise of a seat (`take_full_noop`), and `update` runs only on UI messages, so the page cannot react when a request turns out to have done nothing. Instead the view computes it (`Together.missed`): once nothing of the tab is pending and its visitor holds no seat in the shift they last asked for, the page says so, and names the reasons there can be. **What the view decides** is in three pure functions, and the view reads the sheet through the last two only (`view_reads`): `canSend` (the tab has joined, its log is not lost and its queue has room; otherwise the program drops what a button sends, so every button that sends a shared message is disabled), `row` (of one shift: who holds its seats, how many it has, whether this visitor holds one, whether "Take a seat" and "Leave" are enabled) and `missed`. "Clear the sheet" is enabled while the tab can send and one of its rows holds a visitor. So each of these buttons is disabled by its own click, and a double click or a key that is held down writes one message. That `canSend` is the program's own rule is tested, not proved. **Proved** about those values: seven theorems in `examples/TogetherProofs.lean`, under the same axiom check as section 5. `docs/PROOFS.md`, section 7, says what each states. What they cover is the values the view is given to draw. The four `page_` theorems are about them after every list of the program's messages (clicks, ticks, responses of any status and any body); `view_reads` and `missed_spec` hold for every sheet and every status. None is about the DOM: that the DOM a browser builds holds those values is what the browser test checks. `page_take` is about the tab's own sheet; the log may hold something else by the time the request reaches it. And `take_missed` is about the step: that a tab's request is in the log it has replayed once nothing of the tab is pending is `Sys.nothing_lost`, in the model with one honest log. **Tested in browsers**: `tests/browser/together.mjs`, which `tests/browser/run-all.sh` runs in Chromium and Firefox against a `leanui-site` that the test starts, restarts once and stops. Its header says what it checks and lists its cases. In short: the tabs are in separate browser contexts. At every look, what a tab's DOM holds (the sheet, every button, every sentence that depends on the tab's state; a seat or a sentence only if the browser says that it is shown) is compared with what the sheet it shows and what the test has done in the tab require; and every control must be shown, be what a pointer at its middle would hit, and be where it was when the tab first showed the same seats: a sentence that comes or goes moves no control. The test is a visitor of the room too: it reads the whole log and replays it with the sheet's rules written a second time, in JavaScript, and each time it has waited until the tabs it compares are online, have read the whole log and have nothing pending, each of them must show that replay. It clicks each kind of control with the pointer in windows 1,280 px wide, and takes a seat with it in one of 360 px, where the page has its narrow layout. Not tested there: more than a few tabs; other window sizes, and seats that wrap onto another line (whether they do in the test's windows depends on the font); a network that fails (the test's network is localhost; `leanui-sync-tests` simulates faults); a reply that arrives after its tab was switched offline (`leanui-sync-tests` checks that the program drops it); the keyboard beyond the switch (a take, a leave or a clear turns its own button off, so the focus goes from the pressed button to the document; in Chromium the Tab key then goes on from the button's place); the page behind the Worker, but for one `join` after each deploy (`docs/DEPLOY.md`). **What the page costs a server** is what section 4 says of every shared app ("No request in a loop", with its counts under "What polling costs a server"): one request a second from each open tab, at most one more for each thing its visitor does, and more only while the tab reads a log, or sends changes, too long for one request, until it has had no input for three minutes. Counted on the page itself, where sections 3 and 4 have no count or another one (Chromium against `leanui-site`, each tab in a browser context of its own): a tab left alone made 180 `sync` requests in three minutes, said that it had stopped asking and made none in the next 30 s; one click then, on "Resume" or on "Take a seat", was one request at once and one a second after it (four tabs). A tab switched off made none; switched back on, one at once, which carried the three changes made meanwhile, and three in a row for 500 (two runs). Section 4's clicking tab made 90 requests in nine of fourteen runs, as there, 88 or 89 in four and 66 in one: a tab waits for one request at a time, so a click and a tick that fall together share a request. **How late a change shows** is measured in section 4 ("How late a change shows"); on the page itself, between two tabs in separate browser contexts, 796 of 800 clicks had shown in the other tab after at most 1.01 s and the other four after 1.20 to 1.23 s: three of them went out with their tab's next request, a second after the click, and one, by its round's record, was sent at once (CI machine, to be re-measured on the reference Mac). The log is in the server's memory: `docs/DEPLOY.md` says what that means for the site's container, and what the page can cost it at worst.