Formally verifying Erlang/Elixir programs with embedded Lean proofs

This article introduces Lynx, a project that allows us to formally verify Erlang/Elixir programs using Lean.

You write laws in Erlang/Elixir, which are automatically translated to Lean, and you write proofs in Lean. The laws and proofs are combined and verified by Lean’s kernel. In other words, laws state the properties you expect from your code, and the proofs are written about the actual Erlang/Elixir code, instead of a model (which may drift) or a compilation artifact (which typically checks lower-level guarantees).

We have used Lynx to validate that Erlang’s json implementation roundtrips, to guarantee functions in Elixir’s Task module do not leave trailing messages in your inbox, to uncover bugs and gaps in Elixir’s type system (more on this soon), and more.

At Dashbit, we help startups and enterprises adopt and grow their Elixir teams. We work with a limited number of clients and use our shared experiences to improve the Elixir ecosystem. Get in touch to learn how our team of experts can take your use of Elixir to the next level.

Why proof assistants?

Developers use different techniques daily to verify their software is correct: code review, automated tests, fuzzing, type systems, and more. Some of these techniques fall under formal verification: they provide mathematical guarantees about the behavior of a program. Arguably, the most widespread form of formal verification is the use of static type checking with sound type systems.

Type systems do encode some guarantees about our programs, but they are often not expressive enough to encode properties we care about. For example, let’s take a function that receives a list of integers and returns a sorted list of integers. Most type systems would allow us to type this function as List[Int] -> List[Int]. However, an implementation that simply returns the empty list would satisfy the type above.

In order to guarantee our sorting algorithm is actually behaving as expected, we may think of additional properties beyond its type signature, such as:

  • Ordering: Every element in the output list is less than or equal to the element that follows it (except for the last one)

  • Preservation: Every element in the input list appears in the output list the same number of times, and no new elements are introduced

  • Idempotence: Sorting a list twice gives the same result as sorting it once

Some techniques, such as property-based testing, allow us to test these properties by generating many input values, often at random, and executing our code looking for counterexamples. However, since they can only finitely check many inputs from infinitely many options, they cannot ensure the absence of errors. Also note the exact inputs generated are an important part of the specification: a property that only generates empty lists as inputs would most likely accept a sorting implementation that always returns an empty list.

On the other hand, formal verification can guarantee a property holds for all possible specified input values. Proof assistants, in particular, allow us to write those proofs in an expressive logic, with every step checked by a small trusted kernel. This is precisely what Lynx enables. In practice, Lynx doesn’t replace the techniques mentioned here, but rather augments them.

A quick example

You can install Lynx as a Hex package. The quickest way to get started is by using Lynx with ExUnit to run proofs using the built-in test runner.

Save this example as test/laws/sum_test.exs. It defines a recursive sum and proves that the empty list sums to zero and that, for integer lists, summing each list and adding the results equals summing their concatenation:

defmodule SumProofsTest do
  use ExUnit.Case, async: true
  use Lynx.Case

  def sum([]), do: 0
  def sum([x | xs]), do: x + sum(xs)

  laws "sum" do
    law sum_empty,
      expects: sum([]) == 0,
      proof: ~LEAN"""
      simp [«sum_empty:ensures/0», «sum/1», Erlang.erlang.«==/2»]
      """

    law sum_append(l, r),
      requires: is_integer_list(l) and is_integer_list(r),
      expects: sum(l) + sum(r) == sum(l ++ r),
      proof: ~LEAN"""
      have sums (input : Lynx.Term)
          (valid : «is_integer_list/1» input = .ok Lynx.Term.true) :
          ∃ value, «sum/1» input = .ok (.integer value) ∧
            ∀ right total, «sum/1» right = .ok (.integer total) →
              ∃ joined, Erlang.erlang.«++/2» input right = .ok joined ∧
                «sum/1» joined = .ok (.integer (value + total)) := by
        induction input using «sum/1».induct with
        | case1 => exact ⟨0, rfl, fun right total returned => ⟨right, rfl, by simpa using returned⟩⟩
        | case2 head tail ih =>
          cases head <;> simp [«is_integer_list/1», Erlang.erlang.«is_integer/1»] at valid
          rename_i value
          obtain ⟨subtotal, returned, append⟩ := ih valid
          refine ⟨value + subtotal, by simp [«sum/1», returned], ?_⟩
          intro right total rightReturned
          obtain ⟨joined, appended, combined⟩ := append right total rightReturned
          exact ⟨.cons (.integer value) joined, by simp [Erlang.erlang.«++/2», appended],
            by simp [«sum/1», combined, Int.add_assoc]⟩
        | case3 input notNil notCons => simp_all [«is_integer_list/1»]
      have validity : «is_integer_list/1» l = .ok Lynx.Term.true ∧
          «is_integer_list/1» r = .ok Lynx.Term.true := by
        simpa [«sum_append:requires/2»] using requires
      obtain ⟨leftSum, leftReturned, append⟩ := sums l validity.1
      obtain ⟨rightSum, rightReturned, _⟩ := sums r validity.2
      obtain ⟨joined, appended, combined⟩ := append r rightSum rightReturned
      simp [«sum_append:ensures/2», leftReturned, rightReturned, appended, combined,
        Erlang.erlang.«==/2»]
      """
  end

  defp is_integer_list([h | t]), do: is_integer(h) and is_integer_list(t)
  defp is_integer_list([]), do: true
  defp is_integer_list(_), do: false
end

requires: states the input assumptions and expects: must evaluate to true under those assumptions. Each laws block registers one ExUnit test and Lynx verifies all its laws together. The ~LEAN sigils contain the proofs checked by Lean. Laws also remain callable from ordinary tests, which can be used for fuzzing and validation.

Now run the example or all law groups with:

mix test test/laws/sum_test.exs
mix test --only laws

The translation process

Lynx implements a model of the Erlang runtime in Lean, including all of its data types (except ports and the newly added native records). Once you state a law, it automatically translates the Erlang/Elixir which is part of the law to Lynx’ runtime, which is then proof checked.

This technique is known as mixed embedding: your Erlang/Elixir functions become Lean functions (shallow embedding), which proofs reason about directly, while processes are modeled explicitly as a transition system over their states (deep embedding). If there are no bugs during translation, in the model of the Erlang runtime, or in Lean’s kernel, then the proofs are correct. Given the early nature of this project, you should expect bugs and limitations (for example, we do not yet implement all of Erlang’s built-in functions). Please file bug reports whenever you run into them!

Getting started with laws

A law states a property, expects:, that must hold for every input satisfying its assumptions, requires:. Several kinds of properties are straightforward to state and often catch real bugs. Here are some examples:

  • Totality: the function returns for every valid input, without raising or looping forever. Since a law can only prove its expectation when the computation returns, any expects: law doubles as a proof of totality for every input satisfying its requires:. The simplest one checks the result’s shape: expects: is_binary(encode(term)).

  • Roundtrip: one function undoes another, as with encoding and decoding, serializing and parsing, or compressing and decompressing: expects: decode(encode(term)) == {:ok, term}.

  • Equivalence: the function agrees with a simpler, obviously correct implementation, such as an optimized version against a naive one, or a rewrite against the code it replaces: expects: fast_sort(list) == naive_sort(list).

  • Idempotence: applying a function twice is the same as applying it once, as with normalization and formatting: expects: normalize(normalize(x)) == normalize(x).

  • Algebraic laws: the function interacts predictably with other operations, such as the sum(l) + sum(r) == sum(l ++ r) law in the example above.

Note that stating a law does not necessarily imply the absence of bugs. For example, proving that a JSON encoder roundtrips for some terms, such as JSON.decode(JSON.encode!(term)) == {:ok, term}, does not prove that it emits JSON according to its specification!

Similarly, the algebraic law written above for sum also holds for length, so a sum implementation that simply calls length would be accepted, even though it is incorrect!

It is important to state each law with care, as it states both the required inputs and expected outcomes. Assumptions that are too strong make a law hold vacuously, while missing assumptions make it false, and therefore unprovable, so review requires: as carefully as expects:.

Finally, because Lynx translates your Erlang/Elixir program to Lean, it relies on whole program analysis. It supports both sequential and concurrent features of the Erlang runtime, such as the process dictionary and spawning processes, but it cannot prove anything that involves external systems, running either over the network (sockets) or I/O (ports).

Using it with coding agents

The growing interest in formally verifying our programs is largely driven by AI and coding agents. Lynx embraces this trend, and we recommend the following approach:

  • Defining properties: you can use coding agents to help you explore and define properties, but we strongly recommend a human-in-the-loop approach, where you carefully review and validate each law. Luckily, laws are written in plain Erlang/Elixir, so you can leverage your existing knowledge to understand them.

  • Writing proofs: for the proofs themselves, you can delegate the work to coding agents. Lean’s kernel won’t let an agent write an invalid proof (except for soundness issues in the kernel). This makes proof writing particularly well suited for automation. Unless there is a bug in our translation process, the checked proofs state the laws about our Erlang/Elixir program.

More precisely, Lynx rejects every axiom other than Lean’s standard propext, Classical.choice, and Quot.sound, so proofs cannot be completed with sorry, native_decide, or new axioms. Lynx can also check your proofs against multiple kernels.

In other words, humans are responsible for specifying what correctness means, while coding agents can take care of proving it. Ask your coding agent to run mix help Lynx after installing Lynx, and you are ready to get started.

Additional features

Concurrency

Lynx can prove properties about sequential and concurrent programs. Because concurrent programs in Erlang/Elixir are built on top of well-defined primitives, such as spawning processes, sending and receiving messages, links, monitors, and so forth, Lynx models these operations and ensure concurrent laws hold for every interleaving of processes. Each proof has to state the upper bound of steps the concurrent system must take to guarantee all involved processes terminate.

Exploring all possible interleavings can become expensive quickly, so Lynx uses sleep sets to reduce the state space, exploring steps that commute only once. Alternatively, you may use reaches: instead of expects: to validate that a single outcome of a concurrent program is possible (instead of checking all of its executions).

One caveat to keep in mind is that timers and receive timeouts do not measure wall-clock time, so the model may fire them at any point, including orders elapsed time would rule out. This makes expects: laws cover more runs than Erlang/OTP can take, but it also means a run found by reaches: is possible in the model, and not necessarily in Erlang/OTP.

Debugging and Profiling

If you set LYNX_DEBUG=lean, Lynx will write all generated Lean files to disk and emit a report of how long each translated module and law takes to verify. Set LYNX_CACHE=0 to disable the verification cache and receive full verification reports.

You can also set LYNX_DEBUG=olean to additionally write the compiled .olean files, so you can use projects like leanprof to profile the laws directly.

Multi-kernel verification

Set the LYNX_EXPORT variable to export all elaborated proofs. The elaborated proofs can then be rechecked by Lean’s kernel and the independent checkers bundled with Lean. Lynx’s own runtime proofs are checked by all of them. Some checkers bound how much computation they perform, so proofs that rely on heavy evaluation may exhaust their fuel, which is reported separately from a rejection.

Alternative solutions and pitfalls

While designing Lynx, I considered different solutions and approaches for formally verifying Elixir programs. Initially, I explored SMT-based verifiers, such as Dafny or Why3, where you annotate programs with specifications and invariants, and proofs are discharged automatically, with little need to write them by hand.

My early experiments quickly showed this direction to be impractical: verification of simple programs often took too long, and small modifications to the implementation could lead to solver instability.

During this time, I read a post by Victor Taelin, author of the Bend programming language, saying he would rather optimize for explicit proofs and performance, given coding agents can take the brunt of the work of writing them. This made me change my priorities and focus on proof assistants.

I explored a few languages, modeling Erlang/Elixir data structures and runtimes in each of them. From this process, Lean and F* came out as the leading candidates. I chose Lean due to its current uptick in usage by coding agents, with companies like Mistral releasing its own fine-tuned models focused on Lean.

Unlike SMT-based verifiers, which rerun their automated proofs after each change, hand-written proofs must be updated whenever the code they reason about changes, and the shallow embedding ties them to the shape of the translated code. Therefore, updating Lean, Erlang, or Elixir versions may require your proofs to be updated to match the latest version of the code. Once again, coding agents can be responsible for this work, but it is a trade-off worth keeping in mind.

Acknowledgements: I’d like to thank Dániel Horpácsi, Péter Bereczky, and Benjamin Rosta for their extensive feedback and suggestions, both in Lynx and in this article. All opinions and mistakes are my own.