An in-depth, practical guide to model checking, formal proofs, and checking the rules software must never break.
The problem: generated code can still break important rules
An LLM can generate a feature that passes every test you wrote and still violate a requirement you never tested.
A user might accidentally remove the only owner from a workspace. A visitor might receive inconsistent A/B test assignments. A percentage might exceed its permitted range. These bugs are not always caused by complicated algorithms. Sometimes they come from a missing condition, an unexpected sequence of actions, or an assumption that was never made explicit.
The challenge is not only generating code. It is checking the rules that must remain true.
This is where formal methods become useful. Instead of checking only a collection of examples, we describe important properties precisely and use tools to explore or prove them.
Two tools illustrate different approaches:
- Quint models how a system changes over time and searches for sequences of actions that violate rules.
- Lean lets us state mathematical properties and construct machine-checked proofs that they hold under explicit assumptions.
A useful way to think about the workflow is:
Let an LLM help propose the implementation. Make the requirements and assumptions explicit, then use independent checks to challenge the behaviour or prove properties of the formal specification.
Neither tool automatically verifies arbitrary LLM-generated production code. The model or theorem must represent the intended requirement, and the relationship between that formal description and the real implementation still needs to be tested and reviewed.
1. The gap tests leave
A unit test is a single example: given this input, expect that output. A good suite may contain hundreds or thousands of examples. But it still checks the cases someone thought to write down.
Many real bugs live somewhere else: in the order of steps.
Imagine a workspace where an owner changes a role while another member is being removed. Or an A/B test is paused while a visit arrives. Or two requests happen at nearly the same time. Each action may work correctly in isolation, but a particular sequence can still leave the system in an invalid state.
Even a small model with a few people and a few actions can have a large number of possible histories. Writing a unit test for every possible history quickly becomes impractical.
Formal methods change the question. Instead of asking only, “Does this example work?”, we ask:
- Can any permitted sequence of actions break this rule?
- Does this property hold for every input covered by the specification?
- What assumptions does the property depend on?
The answer is only as meaningful as the specification. A tool can rigorously check the model you give it; it cannot decide whether you modelled the right system.
2. Formal methods in one minute
There is a spectrum of ways to check software behaviour:
| Approach | You write | The tool gives you | What a successful result means |
|---|---|---|---|
| Unit tests | Examples | Pass or fail for each example | The tested examples passed |
| Property-based tests | A property and input generators | Generated inputs that may expose a failure | No failure was found in the generated runs |
| Model checking (Quint) | A model of states, actions, and invariants | A counterexample, or no violation within the explored scope | Depends on whether you simulated runs or checked a bounded state space |
| Formal proof (Lean) | Definitions, assumptions, a proposition, and a proof | A machine-checked proof | The formal proposition follows from its assumptions |
This is not just academic work. AWS engineers described using model checking to find subtle design bugs in critical systems [1]. AWS has also published work on using Lean in the verification of its Cedar policy language [10][11]. DeepMind's AlphaProof used Lean as part of its approach to solving mathematical problems at the 2024 International Mathematical Olympiad [12].
The important distinction is that Quint and Lean answer different questions:
- Quint asks: Can a sequence of valid actions take the system into a state where a rule is broken?
- Lean asks: Given these definitions and assumptions, can this property be proved for every permitted input?
3. The running example: InsightTrack
InsightTrack is an open-source, self-hosted analytics product. Three documented features make useful teaching examples:
- Team access: owner, admin, and viewer roles, with rules about who can do what [5].
- A/B testing: visitors are assigned to experiment variants deterministically [6].
- Bounce rate: a percentage computed from sessions.
The examples below are simplified teaching models based on InsightTrack's public documentation. They are not a formal specification of the complete product, and they do not verify the production implementation.
That distinction matters throughout this guide: we are checking a deliberately small model of a requirement, not claiming that the entire application has been proven correct.
Part 1: Quint — Explore states, actions, and invariants
4. What Quint is
Quint is an executable specification language based on the temporal logic of actions (TLA), the logic behind Leslie Lamport's TLA+ [2][3]. It uses a typed syntax designed to be approachable to software developers.
Quint is useful when correctness depends on how a system changes over time: workflows, permissions, protocols, state machines, and concurrent operations.
Install it with npm:
npm install -g @informalsystems/quint For reproducible results, use a pinned Quint version in your project and check the current installation and runtime requirements in the official documentation.
5. How Quint works
A Quint model describes three main things:
| Part | Meaning | In the team access example |
|---|---|---|
| State | Information the system remembers | members: who belongs to a site and each person's role |
| Actions | What can happen and how the state changes | changeRole(by, who, role) |
| Invariants | Rules that must remain true in every reachable state | exactlyOneOwner |
Two ideas are especially important:
- Primed variables.
members'means the value ofmembersafter an action. An action describes the relationship between the current state and the next state. - Nondeterminism.
nondet who = PEOPLE.oneOf()lets the model checker choose among possible values. This helps explore actions and sequences that a developer might not think to test manually.
An invariant is a rule that must hold in every state the model can reach. For example:
Every reachable workspace state must contain exactly one owner.
A guard is a condition that must be true before an action can happen. For example, only an owner may change another member's role.
Simulation and bounded model checking
Quint provides different ways to explore a model. Two important commands are quint run and quint verify.
| Command | What it does | How to interpret a successful result |
|---|---|---|
quint run | Simulates runs through the model and checks invariants along the way | No violation was found in the runs sampled |
quint verify | Uses symbolic model checking through Apalache to explore executions within a configured bound [13][14] | No violation was found within the explored model and bound |
A successful simulation is not a proof. It means the sampled traces did not expose a violation.
A successful bounded verification is stronger for the explored scope, but it is still bounded. It does not establish that no violation is possible at any length or outside the model's chosen state space.
When a rule breaks, Quint can produce a counterexample: a trace showing the sequence of states and actions that led to the violation. This is often more useful than a simple pass/fail result because it gives you a concrete path to investigate.
Quint also supports example tests with quint test and an interactive REPL.
6. Example: checking team roles
InsightTrack's team access documentation describes owner, admin, and viewer roles [5]. For this teaching model, we use these simplified rules:
- Owner can manage the workspace.
- Admin can add members.
- Viewer has read-only access.
- Every workspace must have exactly one owner.
- An owner can change another member's role, but cannot change their own role.
The central invariant is:
exactlyOneOwner: every reachable state has exactly one owner.
The model below represents a small workspace with three possible people. The add action stands in for inviting someone who already has an account.
module teamAccess { type Role = Owner | Admin | Viewer pure val PEOPLE = Set("alice", "bob", "carol") var members: str -> Role action init = all { members' = Map("alice" -> Owner), } def isMember(p: str): bool = members.keys().contains(p) def isOwner(p: str): bool = isMember(p) and members.get(p) == Owner def canAdd(p: str): bool = isMember(p) and members.get(p) != Viewer action add(by: str, who: str, role: Role): bool = all { canAdd(by), not(isMember(who)), role != Owner, members' = members.put(who, role), } action changeRole(by: str, who: str, role: Role): bool = all { isOwner(by), who != by, isMember(who), role != Owner, members' = members.set(who, role), } action remove(by: str, who: str): bool = all { isOwner(by), who != by, isMember(who), members' = members.keys().exclude(Set(who)).mapBy(p => members.get(p)), } action step = { nondet by = PEOPLE.oneOf() nondet who = PEOPLE.oneOf() nondet role = Set(Owner, Admin, Viewer).oneOf() any { add(by, who, role), changeRole(by, who, role), remove(by, who) } } val exactlyOneOwner = members.keys().filter(p => members.get(p) == Owner).size() == 1 run adminCanAddTest = init .then(add("alice", "bob", Admin)) .then(add("bob", "carol", Viewer)) .expect(members.get("carol") == Viewer) run viewerCannotAddTest = init .then(add("alice", "bob", Viewer)) .then(add("bob", "carol", Viewer)) .fail() } This model intentionally leaves out details such as authentication, persistence, invitation delivery, and database transactions. Its purpose is to explore a small set of role transitions and the owner invariant.
Run the example tests, then simulate the model:
$ quint test teamAccess.qnt teamAccess ok adminCanAddTest passed 1 test(s) ok viewerCannotAddTest passed 1 test(s) 2 passing $ quint run teamAccess.qnt --invariant=exactlyOneOwner [ok] No violation found The output above is illustrative; exact formatting and runtime statistics can vary by Quint version and environment. The important point is what is being checked: the invariant is evaluated across the traces explored by the command.
Break it on purpose
A useful way to understand a model checker is to introduce a bug deliberately.
Remove the guard that prevents an owner from changing their own role:
action changeRole(by: str, who: str, role: Role): bool = all { isOwner(by), - who != by, isMember(who), Now the owner can demote themselves. A run can produce a trace like this:
[State 0] { members: Map("alice" -> Owner) } [State 1] { members: Map("alice" -> Admin) } [violation] Found an issue exactlyOneOwner Alice changes her own role from Owner to Admin. The workspace now has no owner, so the invariant is broken.
This illustrates why invariants are valuable. The guard who != by may look like a small implementation detail, but it protects a business rule. A model checker can expose what happens when that condition is missing.
A seed can be used to reproduce a particular simulated run. Exact command-line options and output should be checked against the Quint version being used.
7. Example: A/B test assignment and witnesses
InsightTrack assigns a variant using a hash of the visitor ID and test ID, modulo the number of variants. This is intended to ensure that a visitor sees the same variant for a given test [6].
For this example, we replace the real hash with a small deterministic stand-in:
module abTest { type Exposure = { visitor: int, test: int, variant: int } pure val VISITORS = 1.to(4) pure val TESTS = Set(1, 2) pure val VARIANTS = 2 pure def bucket(visitor: int, test: int): int = (visitor * 31 + test * 17) % VARIANTS var exposures: Set[Exposure] action init = all { exposures' = Set(), } action visit(v: int, t: int): bool = all { exposures' = exposures.union( Set({ visitor: v, test: t, variant: bucket(v, t) }) ), } action step = { nondet v = VISITORS.oneOf() nondet t = TESTS.oneOf() visit(v, t) } val stickyVariant = exposures.forall(a => exposures.forall(b => (a.visitor == b.visitor and a.test == b.test) implies a.variant == b.variant)) val everyoneGetsControl = exposures.forall(e => e.variant == 0) } The property stickyVariant says that if two exposures belong to the same visitor and test, they must have the same variant.
$ quint run abTest.qnt --invariant=stickyVariant [ok] No violation found This result is expected for this model because every visit calculates the variant using the same deterministic bucket function. It demonstrates the property in the model; it does not independently verify that the production application uses the same calculation or stores exposures correctly.
Now consider everyoneGetsControl. This is deliberately not a real business invariant. It says every exposure must receive variant 0, which should be false if the model can assign visitors to variant 1.
A counterexample can look like this:
$ quint run abTest.qnt --invariant=everyoneGetsControl [State 0] { exposures: Set() } [State 1] { exposures: Set({ test: 2, variant: 1, visitor: 1 }) } [violation] Found an issue everyoneGetsControl This trace is a witness: it demonstrates that the model can produce a non-control assignment.
Witnesses are useful because a model that never reaches an interesting state may pass every invariant for the wrong reason. For example, an overly restrictive guard might accidentally prevent all visits. Alongside properties that must always hold, check that important behaviours can actually happen.
8. Connecting a model to the real implementation
A Quint model checks a design. It does not automatically check the production code that implements that design.
One way to connect the two is model-based testing:
- Export model runs as traces, using Quint's model-based testing support.
- Write a small driver that translates each model action into a real application operation, such as adding a member through an API or recording a visit.
- After each action, compare the application's observed state or response with the model's expected state.
- Keep the generated tests in the normal automated test suite so changes to the implementation can be checked repeatedly.
For example, Quint's model-based testing workflow can export traces in an intermediate JSON format. Consult the Quint documentation for the current command syntax and feature status before relying on it in a project. The quint-connect crate is one example of tooling for model-based testing in Rust [7].
The important idea is not the specific adapter. It is that the formal model and the implementation need an explicit connection.
Where Quint stops
- The model is not the code. A passing model shows that the explored model satisfies its invariant. It does not establish that the production implementation follows that model.
- Simulation is not exhaustive.
quint runsamples traces; a successful result means no violation was found in those runs. - Bounded verification is bounded.
quint verifychecks the configured scope and bound, not every possible execution of an unbounded system. - Modelling takes judgement. A model that omits an important action or state variable can miss a real bug. A model that includes too much detail can become difficult to explore and understand.
Start with a small model: a few actors, a few actions, and two or three important invariants.
Part 2: Lean — Prove properties of formal definitions
9. What Lean is
Lean 4 is a functional programming language and proof assistant. It lets you define functions, state propositions about those functions, and construct proofs that a small trusted kernel checks.
Quint searches for a run that breaks a rule. Lean takes a different approach: it proves that a formal statement follows from its assumptions.
Lean is used in mathematics, formal verification, and work on verified software. Its community mathematical library, Mathlib, contains a large collection of formalized mathematics [8][9].
10. How Lean works
A few ideas make Lean easier to understand:
- Propositions are types. A statement such as “the bounce rate is at most 100” can be represented as a type. A proof is a value of that type.
- Theorems are functions. A theorem with assumptions can be understood as a function that takes proofs of those assumptions and returns a proof of the conclusion.
- Tactics build proofs. Tactics such as
unfold,split, andomegahelp construct proof terms. The resulting proof is checked by Lean's kernel. - The kernel checks proofs. Lean's small trusted kernel checks that the proof term establishes the proposition that was stated.
- Watch for
sorry.sorryis a placeholder for a missing proof. It allows unfinished work to be accepted in certain contexts, so a theorem containing it should not be treated as a completed proof.
The crucial point is that Lean proves the proposition you wrote, not an informal intention in your head. Definitions and assumptions must match the property you actually care about.
11. Example: bounce rate never goes above 100%
Suppose bounce rate is defined as:
[
\text{bounce rate} =
\begin{cases}
0 & \text{if sessions}=0 \
\frac{\text{bounces}\times 100}{\text{sessions}} & \text{otherwise}
\end{cases}
]
For this example, we assume that the number of bounces never exceeds the number of sessions:
[
\text{bounces} \leq \text{sessions}
]
Under that assumption, the rate cannot exceed 100.
The zero-session case is defined as zero here as a teaching choice. A real product should document and consistently apply its own convention for this case.
def bounceRate (bounces sessions : Nat) : Nat := if sessions = 0 then 0 else bounces * 100 / sessions theorem bounceRate_le_100 (bounces sessions : Nat) (h : bounces ≤ sessions) : bounceRate bounces sessions ≤ 100 := by unfold bounceRate split · omega · exact Nat.div_le_of_le_mul (by omega) What is happening?
-
h : bounces ≤ sessionsis the assumption. -
unfold bounceRatereplaces the function name with its definition. -
splithandles the two branches of theif. - In the zero-session branch, the result is zero, which is at most 100.
- In the other branch, Lean uses the assumption and arithmetic reasoning to establish the upper bound.
The theorem proves the property for the formal function and assumption shown above. It does not prove that a production analytics service calculates bounce rate using this exact definition, or that its input data always satisfies the assumption.
12. Example: an A/B variant index is always valid
Suppose an experiment has at least one variant. We calculate a variant index by taking a hash modulo the number of variants.
The desired property is:
For every hash, if the number of variants is greater than zero, the calculated index is less than the number of variants.
def variantIndex (hash variants : Nat) : Nat := hash % variants theorem variantIndex_valid (hash variants : Nat) (h : variants > 0) : variantIndex hash variants < variants := Nat.mod_lt hash h There are no tactics here. The proof applies the library theorem Nat.mod_lt to the positive-variant assumption.
Notice the assumption: variants > 0. Without it, modulo by zero does not give the intended range guarantee. The precondition is part of the correctness statement, not an incidental detail.
To try the examples, create a Lean project or install Lean using the official installation guide, put the code in a local file such as Main.lean, and check it with:
lean Main.lean Use the current Lean toolchain and project setup recommended by the official documentation. A successful check means Lean accepted the declarations; inspect the code for unfinished placeholders such as sorry before treating the proof as complete.
13. Where Lean is used
- Verified production software. The Cedar team at AWS has described using Lean models and proofs for key properties of its policy language, while keeping the production implementation in Rust and connecting the two through extensive testing [10][11].
- Mathematics. Mathlib formalizes a broad collection of mathematical results [8][9].
- AI-assisted proof. DeepMind's AlphaProof used Lean in its approach to finding and checking mathematical proofs [12].
Where Lean stops
- Proofs take practice. Writing and maintaining formal proofs requires learning Lean's type system, libraries, and proof techniques.
- The formal statement matters. A proof can be correct while the proposition is not the property your product actually needs.
- The proof covers the formal definition. It does not automatically prove that production code implements that definition.
- Assumptions matter. A theorem is only as useful as the assumptions under which it holds. Make preconditions explicit and check that the real system satisfies them.
14. Quint or Lean?
| Question | Quint | Lean |
|---|---|---|
| What does it ask? | Can a sequence of actions break this rule? | Does this proposition follow for every permitted input? |
| Best suited to | Workflows, permissions, state machines, concurrency, protocols | Calculations, algorithms, parsers, and properties of functions |
| What does it produce? | A counterexample, or no violation within the explored runs or bound | A machine-checked proof of a formal proposition |
| Main modelling task | Define states, actions, and invariants | Define functions, assumptions, propositions, and proofs |
| How do you connect it to code? | Replay traces or build model-based tests | Test or otherwise establish that implementation behaviour matches the formal definitions |
| InsightTrack example | Exactly one owner; consistent A/B assignments | Bounce rate at most 100%; variant index in range |
Choose Quint when correctness depends on sequences of events, changing state, permissions, or interactions between actions.
Choose Lean when you need to prove a mathematical property of a function, algorithm, or formal definition.
Use both when a system has stateful behaviour as well as critical mathematical properties. Neither replaces integration tests, security review, or validation against the actual implementation.
15. A practical workflow for LLM-assisted development
Formal methods can complement an LLM-assisted development workflow, but they should not be treated as an automatic approval step.
A practical process looks like this:
- Ask the LLM to explain the requirement. Have it list the intended behaviour, edge cases, and ambiguous product decisions.
- Review the requirements. A developer or domain owner must resolve ambiguity and decide which rules are truly mandatory.
- Write explicit properties. Express the important rules as invariants, preconditions, and expected behaviours in plain language before translating them into Quint or Lean.
- Choose the right tool. Use Quint for state transitions and action ordering. Use Lean for properties that can be stated and proved mathematically.
- Challenge the model. Deliberately remove a guard, change an assumption, or introduce a faulty transition. Check that the tool exposes the problem you expect.
- Inspect the result. Read counterexamples, review proof assumptions, and check for unfinished proofs. A green result without understanding the model is not enough.
- Connect the model to the implementation. Use model-based tests, differential tests, integration tests, and code review to check that production behaviour matches the specification.
- Keep the specification current. When business rules change, update the model, proofs, and tests as part of the same change.
An LLM can help draft candidate invariants, generate model scaffolding, explain counterexamples, or suggest proof steps. Those outputs still need review. The model should be treated as an independent expression of the requirement, not as something automatically correct because an LLM generated it.
The goal is to separate two questions:
- Did we implement the feature the way we intended?
- Is what we intended actually consistent with the rules the system must preserve?
Quint and Lean help with the second question, while tests and implementation-level checks help connect the answer back to the running software.
16. Getting started
Quint: start with a small stateful feature
- Install Quint and the Quint extension for VS Code.
- Follow the official Quint documentation for the current CLI and setup.
- Start with a small model of a workflow or permission system.
- Write two or three invariants in plain language, then express them in the model.
- Run the model, inspect the traces, and deliberately remove a guard to see whether a counterexample appears.
Lean: start with a small mathematical property
- Install Lean with elan using the official installation guide.
- Play the Natural Number Game to learn tactics step by step.
- Read Theorem Proving in Lean 4 for the foundations.
- Read Functional Programming in Lean to learn the language.
- Prove one small property from your own code, such as a range, percentage, or count.
Glossary
| Term | Meaning |
|---|---|
| Invariant | A rule that must hold in every reachable state |
| Guard | A condition that must hold before an action can happen |
| State transition | A change from one system state to another |
| Nondeterminism | Allowing a model to choose among multiple possible values or actions |
| Counterexample | A trace that reaches a state where an invariant is broken |
| Witness | A trace demonstrating that a particular behaviour is possible |
| Simulation | Exploring sampled runs of a model |
| Bounded model checking | Exploring executions within a configured finite bound |
| Model-based testing | Using model-generated actions or traces to test a real implementation |
| Theorem | A proposition for which a machine-checked proof has been provided |
| Tactic | A proof-building command, such as omega, split, or simp |
| Kernel | The small trusted part of Lean that checks proof terms |
Conclusion
LLMs can help produce code quickly, but speed does not remove the need for precise requirements.
Quint helps explore whether sequences of actions can violate rules about system behaviour. Lean helps prove properties of formal definitions under explicit assumptions. Both make important requirements more precise, but neither automatically certifies an arbitrary production application.
The strongest approach combines clear specifications, formal checks, ordinary automated tests, and careful review of the connection between the model and the implementation.
Let AI help write the code. Make the rules explicit. Then verify what must never break.
Sources
- C. Newcombe et al., “How Amazon Web Services Uses Formal Methods,” Communications of the ACM 58(4), 2015. https://doi.org/10.1145/2699417
- Quint source code and documentation. https://github.com/quint-co/quint
- Quint documentation. https://quint.sh/docs
- Thoughtworks Technology Radar: Quint. https://www.thoughtworks.com/radar/languages-and-frameworks/quint
- InsightTrack documentation: Team access. https://github.com/NishikantaRay/InsightTrack/blob/main/docs/team-access.md
- InsightTrack documentation: A/B testing. https://github.com/NishikantaRay/InsightTrack/blob/main/docs/ab-testing.md
-
quint-connect, model-based testing for Rust. https://docs.rs/quint-connect - Lean FRO. https://lean-lang.org/fro/about/
- Lean and Mathlib documentation. https://leanprover-community.github.io/
- AWS Open Source Blog, “Lean into Verified Software Development.” https://aws.amazon.com/blogs/opensource/lean-into-verified-software-development
- Cedar team, “How We Built Cedar: A Verification-Guided Approach,” arXiv:2407.01688, 2024. https://arxiv.org/abs/2407.01688
- Google DeepMind, “AI achieves silver-medal standard solving International Mathematical Olympiad problems,” 2024. https://deepmind.google/discover/blog/ai-solves-imo-problems-at-silver-medal-level/
- Apalache model checker. https://github.com/apalache-mc/apalache
- I. Konnov, J. Kukovec, T.-H. Tran, “TLA+ Model Checking Made Symbolic,” Proceedings of the ACM on Programming Languages 3 (OOPSLA), 2019. https://doi.org/10.1145/3360549
- “Type Checking in Lean 4.” https://ammkrn.github.io/type_checking_in_lean4/