{"slug": "beyond-llm-generated-code-hard-rule-checking-with-quint-and-lean", "title": "Beyond LLM-Generated Code: Hard Rule Checking with Quint and Lean", "summary": "A developer published a practical guide showing how to use the Quint model checker and the Lean proof assistant to verify the rules that LLM-generated code must never violate, arguing that tests alone only cover cases someone thought to write down. Using simplified teaching models drawn from the open-source analytics product InsightTrack, the guide contrasts unit tests, property-based tests, model checking and formal proofs, and notes that neither tool automatically verifies arbitrary LLM-generated production code. It cites AWS's use of model checking and Lean for its Cedar policy language, and DeepMind's AlphaProof, as evidence the approach is practical.", "body_md": "*An in-depth, practical guide to model checking, formal proofs, and checking the rules software must never break.*\n\nAn LLM can generate a feature that passes every test you wrote and still violate a requirement you never tested.\n\nA 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.\n\nThe challenge is not only generating code. It is checking the rules that must remain true.\n\nThis 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.\n\nTwo tools illustrate different approaches:\n\nA useful way to think about the workflow is:\n\nLet 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.\n\nNeither 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.\n\nA 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.\n\nMany real bugs live somewhere else: in the order of steps.\n\nImagine 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.\n\nEven 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.\n\nFormal methods change the question. Instead of asking only, “Does this example work?”, we ask:\n\nThe 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.\n\nThere is a spectrum of ways to check software behaviour:\n\n| Approach | You write | The tool gives you | What a successful result means | \n|---|---|---|---|\n| Unit tests | Examples | Pass or fail for each example | The tested examples passed | \n| Property-based tests | A property and input generators | Generated inputs that may expose a failure | No failure was found in the generated runs | \n| **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 | \n| **Formal proof (Lean)** | Definitions, assumptions, a proposition, and a proof | A machine-checked proof | The formal proposition follows from its assumptions | \n\nThis 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].\n\nThe important distinction is that Quint and Lean answer different questions:\n\nInsightTrack is an open-source, self-hosted analytics product. Three documented features make useful teaching examples:\n\nThe 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.\n\nThat 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.\n\nQuint 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.\n\nQuint is useful when correctness depends on how a system changes over time: workflows, permissions, protocols, state machines, and concurrent operations.\n\nInstall it with npm:\n\n```\nnpm install -g @informalsystems/quint\n```\n\nFor reproducible results, use a pinned Quint version in your project and check the current installation and runtime requirements in the [official documentation](https://quint.sh/docs).\n\nA Quint model describes three main things:\n\n| Part | Meaning | In the team access example | \n|---|---|---|\n| **State** | Information the system remembers | `members` : who belongs to a site and each person's role | \n| **Actions** | What can happen and how the state changes | `changeRole(by, who, role)` | \n| **Invariants** | Rules that must remain true in every reachable state | `exactlyOneOwner` | \n\nTwo ideas are especially important:\n\n`members'` means the value of `members` after an action. An action describes the relationship between the current state and the next state.`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.\nAn invariant is a rule that must hold in every state the model can reach. For example:\n\nEvery reachable workspace state must contain exactly one owner.\n\nA guard is a condition that must be true before an action can happen. For example, only an owner may change another member's role.\n\nQuint provides different ways to explore a model. Two important commands are `quint run` and `quint verify`.\n\n| Command | What it does | How to interpret a successful result | \n|---|---|---|\n| `quint run` | Simulates runs through the model and checks invariants along the way | No violation was found in the runs sampled | \n| `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 | \n\nA successful simulation is not a proof. It means the sampled traces did not expose a violation.\n\nA 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.\n\nWhen 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.\n\nQuint also supports example tests with `quint test` and an interactive REPL.\n\nInsightTrack's team access documentation describes owner, admin, and viewer roles [5]. For this teaching model, we use these simplified rules:\n\nThe central invariant is:\n\n`exactlyOneOwner`: every reachable state has exactly one owner.\n\nThe model below represents a small workspace with three possible people. The `add` action stands in for inviting someone who already has an account.\n\n```\nmodule teamAccess {\n  type Role = Owner | Admin | Viewer\n\n  pure val PEOPLE = Set(\"alice\", \"bob\", \"carol\")\n\n  var members: str -> Role\n\n  action init = all {\n    members' = Map(\"alice\" -> Owner),\n  }\n\n  def isMember(p: str): bool = members.keys().contains(p)\n  def isOwner(p: str): bool = isMember(p) and members.get(p) == Owner\n  def canAdd(p: str): bool = isMember(p) and members.get(p) != Viewer\n\n  action add(by: str, who: str, role: Role): bool = all {\n    canAdd(by),\n    not(isMember(who)),\n    role != Owner,\n    members' = members.put(who, role),\n  }\n\n  action changeRole(by: str, who: str, role: Role): bool = all {\n    isOwner(by),\n    who != by,\n    isMember(who),\n    role != Owner,\n    members' = members.set(who, role),\n  }\n\n  action remove(by: str, who: str): bool = all {\n    isOwner(by),\n    who != by,\n    isMember(who),\n    members' = members.keys().exclude(Set(who)).mapBy(p => members.get(p)),\n  }\n\n  action step = {\n    nondet by = PEOPLE.oneOf()\n    nondet who = PEOPLE.oneOf()\n    nondet role = Set(Owner, Admin, Viewer).oneOf()\n    any { add(by, who, role), changeRole(by, who, role), remove(by, who) }\n  }\n\n  val exactlyOneOwner =\n    members.keys().filter(p => members.get(p) == Owner).size() == 1\n\n  run adminCanAddTest =\n    init\n      .then(add(\"alice\", \"bob\", Admin))\n      .then(add(\"bob\", \"carol\", Viewer))\n      .expect(members.get(\"carol\") == Viewer)\n\n  run viewerCannotAddTest =\n    init\n      .then(add(\"alice\", \"bob\", Viewer))\n      .then(add(\"bob\", \"carol\", Viewer))\n      .fail()\n}\n```\n\nThis 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.\n\nRun the example tests, then simulate the model:\n\n``` bash\n$ quint test teamAccess.qnt\n  teamAccess\n    ok adminCanAddTest passed 1 test(s)\n    ok viewerCannotAddTest passed 1 test(s)\n\n  2 passing\n\n$ quint run teamAccess.qnt --invariant=exactlyOneOwner\n[ok] No violation found\n```\n\nThe 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.\n\nA useful way to understand a model checker is to introduce a bug deliberately.\n\nRemove the guard that prevents an owner from changing their own role:\n\n```\n   action changeRole(by: str, who: str, role: Role): bool = all {\n     isOwner(by),\n-    who != by,\n     isMember(who),\n```\n\nNow the owner can demote themselves. A run can produce a trace like this:\n\n``` php\n[State 0] { members: Map(\"alice\" -> Owner) }\n[State 1] { members: Map(\"alice\" -> Admin) }\n[violation] Found an issue\n  exactlyOneOwner\n```\n\nAlice changes her own role from `Owner` to `Admin`. The workspace now has no owner, so the invariant is broken.\n\nThis 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.\n\nA 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.\n\nInsightTrack 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].\n\nFor this example, we replace the real hash with a small deterministic stand-in:\n\n```\nmodule abTest {\n  type Exposure = { visitor: int, test: int, variant: int }\n\n  pure val VISITORS = 1.to(4)\n  pure val TESTS = Set(1, 2)\n  pure val VARIANTS = 2\n\n  pure def bucket(visitor: int, test: int): int =\n    (visitor * 31 + test * 17) % VARIANTS\n\n  var exposures: Set[Exposure]\n\n  action init = all {\n    exposures' = Set(),\n  }\n\n  action visit(v: int, t: int): bool = all {\n    exposures' = exposures.union(\n      Set({ visitor: v, test: t, variant: bucket(v, t) })\n    ),\n  }\n\n  action step = {\n    nondet v = VISITORS.oneOf()\n    nondet t = TESTS.oneOf()\n    visit(v, t)\n  }\n\n  val stickyVariant =\n    exposures.forall(a => exposures.forall(b =>\n      (a.visitor == b.visitor and a.test == b.test) implies\n        a.variant == b.variant))\n\n  val everyoneGetsControl =\n    exposures.forall(e => e.variant == 0)\n}\n```\n\nThe property `stickyVariant` says that if two exposures belong to the same visitor and test, they must have the same variant.\n\n``` bash\n$ quint run abTest.qnt --invariant=stickyVariant\n[ok] No violation found\n```\n\nThis 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.\n\nNow 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`.\n\nA counterexample can look like this:\n\n``` bash\n$ quint run abTest.qnt --invariant=everyoneGetsControl\n[State 0] { exposures: Set() }\n[State 1] {\n  exposures: Set({ test: 2, variant: 1, visitor: 1 })\n}\n[violation] Found an issue\n  everyoneGetsControl\n```\n\nThis trace is a **witness**: it demonstrates that the model can produce a non-control assignment.\n\nWitnesses 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.\n\nA Quint model checks a design. It does not automatically check the production code that implements that design.\n\nOne way to connect the two is **model-based testing**:\n\nFor example, Quint's model-based testing workflow can export traces in an intermediate JSON format. Consult the [Quint documentation](https://quint.sh/docs) 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].\n\nThe important idea is not the specific adapter. It is that the formal model and the implementation need an explicit connection.\n\n`quint run` samples traces; a successful result means no violation was found in those runs.`quint verify` checks the configured scope and bound, not every possible execution of an unbounded system.\nStart with a small model: a few actors, a few actions, and two or three important invariants.\n\nLean 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.\n\nQuint searches for a run that breaks a rule. Lean takes a different approach: it proves that a formal statement follows from its assumptions.\n\nLean 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].\n\nA few ideas make Lean easier to understand:\n\n`unfold`, `split`, and `omega` help construct proof terms. The resulting proof is checked by Lean's kernel.`sorry`.\nThe 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.\n\nSuppose bounce rate is defined as:\n\n[\n\n\\text{bounce rate} =\n\n\\begin{cases}\n\n0 & \\text{if sessions}=0 \\\n\n\\frac{\\text{bounces}\\times 100}{\\text{sessions}} & \\text{otherwise}\n\n\\end{cases}\n\n]\n\nFor this example, we assume that the number of bounces never exceeds the number of sessions:\n\n[\n\n\\text{bounces} \\leq \\text{sessions}\n\n]\n\nUnder that assumption, the rate cannot exceed 100.\n\nThe 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.\n\n```\ndef bounceRate (bounces sessions : Nat) : Nat :=\n  if sessions = 0 then 0 else bounces * 100 / sessions\n\ntheorem bounceRate_le_100 (bounces sessions : Nat)\n    (h : bounces ≤ sessions) :\n    bounceRate bounces sessions ≤ 100 := by\n  unfold bounceRate\n  split\n  · omega\n  · exact Nat.div_le_of_le_mul (by omega)\n```\n\nWhat is happening?\n\n`h : bounces ≤ sessions` is the assumption.`unfold bounceRate` replaces the function name with its definition.`if`.\nThe 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.\n\nSuppose an experiment has at least one variant. We calculate a variant index by taking a hash modulo the number of variants.\n\nThe desired property is:\n\nFor every hash, if the number of variants is greater than zero, the calculated index is less than the number of variants.\n\n```\ndef variantIndex (hash variants : Nat) : Nat :=\n  hash % variants\n\ntheorem variantIndex_valid (hash variants : Nat)\n    (h : variants > 0) :\n    variantIndex hash variants < variants :=\n  Nat.mod_lt hash h\n```\n\nThere are no tactics here. The proof applies the library theorem `Nat.mod_lt` to the positive-variant assumption.\n\nNotice 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.\n\nTo try the examples, create a Lean project or install Lean using [the official installation guide](https://lean-lang.org/install/), put the code in a local file such as `Main.lean`, and check it with:\n\n```\nlean Main.lean\n```\n\nUse 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.\n\n| Question | Quint | Lean | \n|---|---|---|\n| **What does it ask?** | Can a sequence of actions break this rule? | Does this proposition follow for every permitted input? | \n| **Best suited to** | Workflows, permissions, state machines, concurrency, protocols | Calculations, algorithms, parsers, and properties of functions | \n| **What does it produce?** | A counterexample, or no violation within the explored runs or bound | A machine-checked proof of a formal proposition | \n| **Main modelling task** | Define states, actions, and invariants | Define functions, assumptions, propositions, and proofs | \n| **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 | \n| **InsightTrack example** | Exactly one owner; consistent A/B assignments | Bounce rate at most 100%; variant index in range | \n\nChoose **Quint** when correctness depends on sequences of events, changing state, permissions, or interactions between actions.\n\nChoose **Lean** when you need to prove a mathematical property of a function, algorithm, or formal definition.\n\nUse 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.\n\nFormal methods can complement an LLM-assisted development workflow, but they should not be treated as an automatic approval step.\n\nA practical process looks like this:\n\nAn 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.\n\nThe goal is to separate two questions:\n\nQuint and Lean help with the second question, while tests and implementation-level checks help connect the answer back to the running software.\n\n| Term | Meaning | \n|---|---|\n| **Invariant** | A rule that must hold in every reachable state | \n| **Guard** | A condition that must hold before an action can happen | \n| **State transition** | A change from one system state to another | \n| **Nondeterminism** | Allowing a model to choose among multiple possible values or actions | \n| **Counterexample** | A trace that reaches a state where an invariant is broken | \n| **Witness** | A trace demonstrating that a particular behaviour is possible | \n| **Simulation** | Exploring sampled runs of a model | \n| **Bounded model checking** | Exploring executions within a configured finite bound | \n| **Model-based testing** | Using model-generated actions or traces to test a real implementation | \n| **Theorem** | A proposition for which a machine-checked proof has been provided | \n| **Tactic** | A proof-building command, such as `omega` ,`split` , or`simp` | \n| **Kernel** | The small trusted part of Lean that checks proof terms | \n\nLLMs can help produce code quickly, but speed does not remove the need for precise requirements.\n\nQuint 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.\n\nThe strongest approach combines clear specifications, formal checks, ordinary automated tests, and careful review of the connection between the model and the implementation.\n\n**Let AI help write the code. Make the rules explicit. Then verify what must never break.**\n\n`quint-connect`, model-based testing for Rust.", "url": "https://wpnews.pro/news/beyond-llm-generated-code-hard-rule-checking-with-quint-and-lean", "canonical_source": "https://dev.to/nishikantaray/beyond-llm-generated-code-hard-rule-checking-with-quint-and-lean-40hi", "published_at": "2026-11-29 16:12:13+00:00", "updated_at": "2026-11-29 16:15:49.602615+00:00", "lang": "en", "topics": ["ai-safety", "ai-agents", "developer-tools", "large-language-models", "ai-research"], "entities": ["Quint", "Lean", "InsightTrack", "AWS", "Cedar", "DeepMind", "AlphaProof"], "also_reported_by": [], "takeaway": "Pair LLM-generated implementations with independent formal checks: model state machines and invariants in Quint to get counterexamples for bad action sequences, and use Lean to machine-check properties, while still testing that the formal model matches the real implementation.", "recommendation": {"advice": "When LLM-written code must satisfy rules tests miss, model the states, actions and invariants in Quint to surface counterexample sequences, and prove key properties in Lean, then verify the model matches the implementation.", "playbook": "output-verification", "playbook_url": "https://wpnews.pro/playbooks/output-verification"}, "alternates": {"html": "https://wpnews.pro/news/beyond-llm-generated-code-hard-rule-checking-with-quint-and-lean", "markdown": "https://wpnews.pro/news/beyond-llm-generated-code-hard-rule-checking-with-quint-and-lean.md", "text": "https://wpnews.pro/news/beyond-llm-generated-code-hard-rule-checking-with-quint-and-lean.txt", "jsonld": "https://wpnews.pro/news/beyond-llm-generated-code-hard-rule-checking-with-quint-and-lean.jsonld"}}