Beyond LLM-Generated Code: Hard Rule Checking with Quint and Lean
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

An in-depth, practical guide to model checking, formal proofs, and checking the rules software must never break.
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:
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.
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:
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.
There is a spectrum of ways to check software behaviour:
This is not just academic work. AWS engineers described using model checking to find subtle design bugs in critical systems. AWS has also published work on using Lean in the verification of its Cedar policy language. DeepMind's AlphaProof used Lean as part of its approach to solving mathematical problems at the 2024 International Mathematical Olympiad.
The important distinction is that Quint and Lean answer different questions:
InsightTrack is an open-source, self-hosted analytics product. Three documented features make useful teaching examples:
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.
Quint is an executable specification language based on the temporal logic of actions (TLA), the logic behind Leslie Lamport's TLA+. 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.
npm install -g @informalsystems/quint Enter fullscreen mode Exit fullscreen mode For reproducible results, use a pinned Quint version in your project and check the current installation and runtime requirements in the official documentation.
A Quint model describes three main things:
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.
Quint provides different ways to explore a model. Two important commands are quint run and quint verify.
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.
InsightTrack's team access documentation describes owner, admin, and viewer roles. For this teaching model, we use these simplified rules:
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() } Enter fullscreen mode Exit fullscreen mode 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 Enter fullscreen mode Exit fullscreen mode 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.
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), Enter fullscreen mode Exit fullscreen mode 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 Enter fullscreen mode Exit fullscreen mode 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.
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.
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) } Enter fullscreen mode Exit fullscreen mode 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 Enter fullscreen mode Exit fullscreen mode 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.
$ 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 Enter fullscreen mode Exit fullscreen mode 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.
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:
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.
The important idea is not the specific adapter. It is that the formal model and the implementation need an explicit connection.
Start with a small model: a few actors, a few actions, and two or three important invariants.
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.
A few ideas make Lean easier to understand:
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.
[ \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:
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 ) Enter fullscreen mode Exit fullscreen mode What is happening?
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.
Suppose an experiment has at least one variant. We calculate a variant index by taking a hash modulo the number of variants.
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 Enter fullscreen mode Exit fullscreen mode 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 Enter fullscreen mode Exit fullscreen mode 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.
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.
Formal methods can complement an LLM-assisted development workflow, but they should not be treated as an automatic approval step.
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.
Quint and Lean help with the second question, while tests and implementation-level checks help connect the answer back to the running software.
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.