Practical Vericoding in Lean

Practical Vericoding in Lean

Formal methods, verification and Lean in particular have seen a massive surge in interest. The core reason is that proof has suddenly become relatively cheap. It’s still not free, but the costs have dropped by a factor which is probably well over 100.

How did I come up with that number? A proof that takes 1M lines is now feasible to do for a few hundred euros. The raw labour alone for 1M lines of proof is easily several person-years (see seL4).

This radical change in the cost of proof has seen huge and difficult mathematical theorems fall at a rate never before seen in history. But it also means that we can begin to prove properties about software — problems that are often radically simpler than the kinds of things we ask in mathematics!

But how do we leverage this work effectively? Where do I use a theorem prover in my code? How can I make Lean work for me in my day-to-day engineering work?

There are different strategies and techniques. We will describe them briefly here and then we will try to dig into some examples.

Lean as a language, and Curry–Howard

Because Lean is at its core a functional programming language (leveraging the Curry–Howard correspondence to identify proofs with programs), one of the easiest ways to write a specification against code is to write both the specification and the code in Lean directly. LLMs tend to be very good at writing Lean and quite good at writing specifications as types from detailed descriptions of a problem.

The specification is a type, and a program that meets it is a term of that type. Here is a max function that carries its own proof with it:

def max (a b : Nat) : {m : Nat // a ≤ m ∧ b ≤ m} :=
  if h : a ≤ b then
    ⟨b, ⟨h, Nat.le_refl b⟩⟩
  else
    ⟨a, ⟨Nat.le_refl a, Nat.le_of_not_le h⟩⟩

Lean makes an excellent glue language. From a technical point of view, for vericoding, there is really no need for the old human-focused glue languages like JavaScript, Go, Python, etc. The approach of dropping these in favour of Lean, however, is not always possible for external reasons.

  • Concurrency: Lean has a library, Std.Async, for working with concurrency, but its performance is absolutely appalling. It is more of a proof of concept than a usable library.
  • Libraries: Lean has nothing like the depth of library infrastructure that exists for Python, Go, JavaScript or other similar languages. This means you are likely to be writing a bunch of libraries yourself. The more people do this, the easier life is going to get, but right now it’s just not very far along.
  • Performance: Lean has a reasonably good compiler. Compared against JavaScript or Python, it generally wins handily. But these languages often turn to C or other low-level languages in libraries for the fast parts. This presents a bit of a problem when you’re trying to prove properties as you can’t just pass in a C library and know what it does.
  • Brownfield: You already have a bunch of code and you want to know what it does. Maybe you can’t get rid of it, as duplicating it, even with LLMs, is too costly. Maybe you don’t have control over this for other reasons.

So what can we do about these problems?

Concurrency

Concurrency is very important in many applications. We initially ran into the problem because we needed to write an HTTP server and client. These are going to be an absolute dog without some kind of concurrency, particularly one that can make use of modern IO.

At Scidonia we wrote LeanIn to address this problem. We built a system based on Node and Tokio, copying many of the defunctionalisation techniques which made Tokio fast and applying them in Lean.

Our current implementation has exactly one carrier thread so it is closer in some ways to Node than to Tokio. However, it also has Node-like performance, which is to say, not bad at all. You’re still out of luck if you need something more sophisticated like BEAM. Yet more places where effort would be appreciated!

Libraries

Aside from writing Lean libraries for the thing you need — which of course is what we would like you to do, because we want to use them too — you may have to use existing libraries. Sometimes this is simply necessary because it interfaces to system-level functionality. This was the case for us in using event-driven async IO.

So how do we deal with foreign libraries? The key idea here is to build a theory of how the library acts, formalise it as opaque types in Lean. Then you can use these as guarantees inside your system. Of course if these guarantees are false, all bets are off! So you’ll want to test to make sure that your guarantees are met. Luckily a specification serves as an excellent guide for testing. Differential testing against observations which would violate the spec gives us greater confidence that what we have is true. It is not perfect, but it gives a bit of a sliding scale similar to what we use in standard testing regimes.

Performance

Lean is reasonable in terms of performance compared to the dynamic languages, so for many applications this is not a problem. But if you really need best-in-class then it’s too far from the metal. So what can we do?

You can of course use the approach of writing in a language like C and then using differential testing. But perhaps there is a better way!

Proof using the LLVM

We are just finishing up our fastest-in-the-world JSON parser written in Lean. How fastest? Faster than simdjson and yyjson much of the time — at least for the documents we developed it against (you can probably find some that are slower). We do this with the following approach:

  1. Create a program in C — testing against yyjson and simdjson for speed, and testing correctness against a corpus. Just keep telling the LLM to make it faster until it is.
  2. Compile the C programme to LLVM.
  3. Specify the correctness of the LLVM against lean-llvm, carrying a full Lean specification of JSON correctness down to the LLVM level.

This works surprisingly well but there is a cost. The proofs against LLVM code are big. Like really big (think 1M lines big). This can take a long time and cost more than you might want to pay. It is, however, usable as an approach now if you really need the speed.

The external compiler: Zigolean

If you have a complete semantics of a lower-level language in Lean itself, you can use this to show correctness. C tends to be a hassle since its semantics are a bit wicked, but this would be in principle possible. At Scidonia we have been experimenting with Zig using this strategy with Lean, which has:

  • A semantics of a subset of Zig
  • Leverages the semantics of the LLVM (from lean-llvm)
  • Creates a refinement-preserving compilation from Zig to LLVM
  • Allows you to specify memory and ownership properties at the Zig level as contracts

Here is a kernel and the boundary contract that goes with it. The Zig compacts the nonzero bytes of src into dst:

fn packNonzero(src: []const u8, dst: []u8) usize {
    var i: usize = 0;
    var k: usize = 0;
    while (i < src.len) {
        const b = src[i];
        if (b != 0) {
            dst[k] = b;
            k = k + 1;
        }
        i = i + 1;
    }
    return k;
}

Zigolean states the contract over the placed views — a pointer and a length for each slice — and proves the lowering preserves it. The precondition is what the caller promises; the postcondition is what every run must establish:

def packPre (args : List Value) (mem : Mem) : Prop :=
  ∃ sp sn dp dn,
    args = [.ptr sp, .int 64 sn, .ptr dp, .int 64 dn] ∧
    Readable mem sp sn ∧ Writable mem dp dn ∧ dn ≥ sn ∧ Disjoint sp sn dp dn

def packPost (args : List Value) (mem : Mem) : Outcome → Prop
  | .ret (some v) m =>
      ∃ sp sn dp dn k,
        args = [.ptr sp, .int 64 sn, .ptr dp, .int 64 dn] ∧
        v = .int 64 (BitVec.ofNat 64 k) ∧
        k = countNonzero mem sp sn ∧
        readBytes m dp k = compacted mem sp sn ∧
        (∀ a, ¬ (dp ≤ a ∧ a < dp + sn) → readByte m a = readByte mem a)
  | _ => False

def packContract : MemContract where
  budget := fun args _ => match args with
    | [_, .int 64 n, _, _] => n + 1
    | _ => 0
  pre  := packPre
  post := packPost

The helper predicates are the theory’s. The point is that the contract is written at the Zig boundary and lifted to the generated LLVM function, rather than written in LLVM.

With these four pieces you can write Lean bindings to Zig which has strong specifications of its behaviour. And you get something very fast!

This is essentially writing a proof-carrying compiler. But it seems like this approach reduces the cost of proving the kinds of things you need for performance without tripping yourself up on the low-level details too much.

This is just the beginning for the idea of an external compiler. You’re going to see a lot more of these types of approaches in the future since we can create theories that overlay on our languages provided we have a good semantic model. I believe it will really challenge languages like Rust as well because it’s better to have something which is not particularly sophisticated, such as Zig, as you want to do all the heavy lifting in the theorem prover.

Plus you’ll be able to add all sorts of theories that might help you prove correctness. Not just ownership models, but perhaps theories of concurrency or other approaches such as custom memory layouts for structures.

Brownfield

Sometimes you are just landed with a mountain of code that does something and you can’t simply get rid of it. What do you do?

Well there are a number of strategies here so I’ll just start listing off the ones I’ve seen or used and maybe give some pointers to existing examples.

Models

In areas in which you have very difficult reasoning, such as concurrency (a place where TLA+ is now being used a lot) it can make sense to create a model of your code and then prove properties of the model. Just as in TLA+ you can write down state transition models with guards quite easily in Lean (or ask an LLM to do it) and then ask it to make an inventory of your concurrent launch sites and encode them as a transition system.

This, of course, is just one example of modelling, there are many other possibilities here! This can be pretty cheap since you’re only specifying a fragment.

The downside is, of course, a possible loss of fidelity and two sources of truth which need to both be maintained.

Shadow code

One solution is to get an LLM to write a parallel development of the existing code, copying the approach and algorithmics as closely as possible. This then acts as a model of the code you want to prove. You prove the properties of this model. If you can’t, and you find a bug, then you fix the model and show it meets the specification, and then try to lift the bug to a test against the original code, modify the original code’s algorithm and hope your tests still pass.

A minimal example. The Python distributes a payment across parts, putting the remainder in the last one:

def payout(total: int, parts: int) -> list[int]:
    share = total // parts
    return [share] * (parts - 1) + [total - share * (parts - 1)]

The shadow is the same algorithm in Lean, with the property attached:

def payout (total parts : Nat) : List Nat :=
  let share := total / parts
  List.replicate (parts - 1) share ++ [total - share * (parts - 1)]

-- Every cent must be accounted for.
example : (payout 100 3).sum = 100 := by decide

A first attempt that returned [total / parts] * parts fails this check: 100 split three ways sums to 99. The bug is visible in the model before it reaches a test.

This discipline has the downside of being a model and requiring you to maintain duplication (as with the other modelling approach). You will never get a perfectly faithful reproduction, and yet it can still help find important classes of bugs. It’s probably best to use this approach when you have problems that yield hard-to-find bugs, or possibly only on subsystems which you know are buggy.

Compilation to Lean

You can compile your code to Lean if you have a compiler for your language to Lean. No seriously! PastaLean transpiles Python into Lean 4 so the result can be verified there.

This lets you prove properties of the eventual Lean rather than the Python, and allows you to keep maintaining the code in Python but proving it in Lean. The compile-and-prove cycle and blast-radius management are a bit of a pain but it may make sense in some cases.

Microservices

If you develop your application as microservices then you can create a shim/proxy in Lean that can be used to ensure properties of the system as a whole by providing them in the proxy. This could be data-flow permissions, or other business rules. Here you can leave your code as Python, JavaScript or whatever and still know that whatever passes through the gates is correct according to your specification. We have been doing this with Zenturian.

Conclusion

There are lots of ways to get started with vericoding in Lean. I’d love to know if I’ve left out any of the important approaches!

More from the blog

View all posts →
AI-Guided Certified Program Refinement

AI-Guided Certified Program Refinement

Software's core problem is knowing what it should do. AI-guided certified program refinement — vericoding — makes specification the artefact we tinker with, and lets AI guess program transformations that a theorem prover certifies.

Vericoding Services

Prove the program correct. Then make it faster.

Models now write more code than you can review line by line. You specify what the program must do. We prove the implementation meets that specification, and where latency or compute cost is the problem, we replace it with a faster program that still does.

See the services
Code checked by a proof, then measured for speed