Skip to main content

Formal verification

LibrePhotos has a lot of code whose bugs only show up when steps happen in an unlucky order: several job workers and web processes share one database, a process can be killed at any line, clients retry on timeout, and the mobile and desktop apps sync an on-device database with the server. Tests check the orders someone thought to write. A model checker checks every order.

So every change to stateful code comes with a TLA+ model of the steps it changes, checked with everystate, a TLA+ model checker with TLC's command line, output and exit codes in one binary (no Java). The models live in verification/ at the root of the repository.

What a model is​

A model is a small description of the design, not of the code: one variable per piece of state that matters (a row's status, a lease holder, a file on disk) and one action per step that can interleave with the others. The checker explores every reachable state at small bounds (two workers, one crash) and reports the shortest sequence of steps that breaks a promise.

What it proves is the model at those bounds. It does not prove that the code is correct for every input. To keep the gap small, every model is written against the code and says which code each action stands for.

How a model maps to the code​

Take verification/jobs/QueueLease.tla, the model of the task queue in apps/backend/api/jobs/. Its promise is that a task runs on at most one worker at a time, that a group counts each member's end exactly once, and that the group's follow-up fires only after every member ended. Its actions are the steps of the code:

ActionCode
Claimstore.claim, the conditional UPDATE that takes a queued task
RenewWorker._renew calling store.renew
Succeed, Failworker.run_task ending in store.succeed or store.fail
Crasha hard kill of the worker process
Expireten minutes without a successful renew
ReaperRead, ReaperLoststore.requeue_expired: the read of expired rows, then _lost per row

What the code does as one indivisible step is one action. A read followed by a write is two actions, unless a lock or a transaction makes it one. Kills, lost replies, timeouts and retries are actions too, because that is where the bugs are.

Each area folder has a README.md with the table for every spec, the bounds of each configuration and the commit the model was last compared with. When you change that code, check the table: if an action no longer matches what the code does, change the model in the same pull request.

Configurations​

A spec has several .cfg files. Each sets the constants (how many workers, crashes, retries) and the switches that select a variant of the design:

  • current code: the design as it is today. It passes, or it fails and shows an open bug.
  • mutation: the design broken on purpose, the way the code could be broken (no lock, two steps swapped). It must fail. A check that has never failed proves nothing, so every passing model has one.
  • fix: a model of a proposed fix, which must pass.

Run it​

From the repository root, with the Node version in apps/frontend/.nvmrc:

node scripts/check-verification.mjs
node scripts/check-verification.mjs --only uploads/
node --test scripts/check-verification.test.mjs

It runs every configuration through npx everystate@0.4.1 (the version is pinned in one constant in the script) and compares each result with verification/expectations.json. EVERYSTATE=/path/to/everystate uses a local binary instead. It also fails when a .cfg has no entry in the expectations, and when a glob in verification/stateful-paths.json matches no file. All the models together take a few seconds.

To run one model by hand, from its folder:

npx everystate@0.4.1 -json -config QueueLeaseStall.cfg QueueLease.tla

Exit code 0 means every reachable state was checked and nothing was found; 12 an invariant is violated, 13 a liveness property, 11 a deadlock; 150 and 151 mean the spec or the configuration does not parse. With -json, the last line of the output is one object with status, name (the violated property) and trace, the shortest list of {action, state} steps that reaches it. Read the trace as a story in the code's words, then decide against the code whether it is a real bug or a step the code cannot take.

The expectations file​

verification/expectations.json lists every configuration with the result it must have:

{
"spec": "jobs/QueueLease.tla",
"config": "jobs/QueueLeaseStallCap.cfg",
"expect": { "status": "invariant", "name": "CapRespected" },
"bug": { "finding": 4, "description": "Lease limit: a stalled worker keeps running after its task is re-claimed (fenced, until its next checkpoint), so a heavy cap of 1 runs 2 tasks" }
}

expect is "ok" or the status and name that everystate -json reports. An expected violation is either an open bug (bug, with the number of the finding in the maintainers' verification report, or null for a lead without one) or a mutation with a line saying what is broken.

A pull request that fixes a bug changes the code and the model together. The configuration of the current code then passes, so its entry becomes "expect": "ok" and loses its bug field. Never weaken a property or a model to change a result: a counterexample on the current code is a finding to report.

The rule​

Every change to stateful code is formally verified with TLA+ in the same pull request: model the steps it changes (state, interleavings, crashes, retries) under verification/<area>/, run the checker and record the result in verification/expectations.json.

Stateful code is code that owns or changes persistent or shared state, or orders steps over time: database models and writes, jobs and queues, leases and locks, the upload and sync engines, caches with invalidation, stores and state machines, retries, and the on-device database. verification/stateful-paths.json lists it as include and exclude globs, plus gated globs for trees that mix both kinds of code: there a file counts only when its text, before or after the change, or a changed line matches the glob's contains pattern. Backend views count when they write (a post/patch/delete handler, .save(, .update(, a transaction, a job start), and the web app's and packages/api-client's query hooks when they mutate or cache (useMutation, setQueryData, invalidateQueries, storage, timers, module-level state); a hook that only reads is left out. The globs cover the backend, the web app's API layer, upload queue, editor state and selection, packages/local-db, packages/api-client's transport, the mobile sync, database, stores and upload code, and the desktop app's local database, sync, caches and Rust file operations. Components that only render, styles, translations, schemas and pure helpers (date parsing, geometry) are left out. verification/COVERAGE.md maps these areas to the models that cover them.

Two checks enforce it:

  • scripts/check-conventions.mjs (CI: conventions.yml, --only verification) fails when a pull request changes a stateful file and nothing under verification/. Tests, CI files, lockfiles, translations, Markdown and version-only dependency bumps are exempt, as for the docs rule.
  • scripts/check-verification.mjs (CI: verification.yml, on changes to verification/) runs every model and fails when a result differs from its expectation.

If a change does not alter any step a model describes, compare the model with the new code anyway and record that in the area's README.md ("Last confirmed against the code at ..."): the check stays a deliberate one.

Add a model​

  1. Pick the promise: one sentence the code must keep, where a break harms users, such as "a re-upload never answers duplicated for a photo that was never imported".
  2. Write verification/<area>/<Spec>.tla, with a comment on each action naming the file and function it stands for. Start with a TypeOK invariant, then the promise as an INVARIANT or a PROPERTY.
  3. Write the configurations: the current code, a mutation that fails, and for a bug the fix. Keep the bounds small; a few million states is the most a configuration should reach.
  4. Run each configuration, add its entry to verification/expectations.json and describe the spec in the area's README.md.
  5. Run node scripts/check-verification.mjs.

Models of unpublished security findings go into a private/ folder under the area. Git ignores it (.gitignore) and the checker skips it; the models move out when the advisory is published.

Check the real code against a model​

A pass says the model keeps the promise, not that the code behaves like the model. everystate conform closes part of that gap: record what the running code did, one JSON line per step with the model's action and variable names, and check that the recording is a behaviour the spec allows.

npx everystate@0.4.1 conform -trace run.jsonl -config QueueLease.cfg QueueLease.tla

Each line may have action (the action that happened), params (its arguments) and state (some or all variables after the step); variables left out are unconstrained. Exit code 0 means the run conforms; 20 means a step the model forbids, and the report names the first line that does not match, the closest step the spec allows and the values that differ; 12 means the spec allows the run but the run breaks an invariant. -hidden N allows up to N unlogged steps before each line, and -stutter lets a line without an action repeat the state. On a mismatch, decide against the code which side is wrong, as with a counterexample. A conformance check covers the runs recorded, so feed it from an integration test that exercises retries and failures.