{"slug": "lynx-write-proofs-about-erlang-elixir-programs-using-lean", "title": "Lynx: Write proofs about Erlang/Elixir programs using Lean", "summary": "A project called Lynx lets developers write formal proofs about Erlang and Elixir programs in Lean by automatically translating their compiled code, including the Elixir and Erlang standard libraries, into Lean theorems checked by Lean's kernel. Lynx uses shallow embedding, turning each law written with Lynx.Case or Lynx.Laws into a Lean theorem with `requires:` as its hypothesis and `expects:` as its goal, and the project's documentation warns that proofs may not rely on `sorry` or untrusted axioms. The project's authors caution that Lynx is early-stage, that not all Erlang builtin functions are implemented, and that formal verification cannot prove software generally bug-free — only that specified properties hold for all specified inputs.", "body_md": "Write proofs about Erlang/Elixir programs using Lean.\n\nYou write laws in Erlang/Elixir, which are automatically translated to Lean alongside your Erlang/Elixir code, and you write proofs in Lean. The laws and proofs are assembled together and verified by Lean's kernel.\n\nThis technique is also known as *shallow embedding*, since it translates\nErlang/Elixir to Lean and then use the features and properties of Lean\nfor proofs. If there are no bugs during translation (or in Lean's kernel),\nthen the proofs are correct. However, given the early nature of this project,\nyou must expect bugs and find plenty of limitations (for example, we do not\nyet implement all of Erlang builtin functions). Please file bug reports\nwhenever you run into them!\n\nSee the documentation for [the Lynx module](https://lynx.hexdocs.pm) to get\nstarted or ask your coding agent to run `mix help Lynx`.\n\nImportant\n\n**A quick word on formal verification**\n\nFormal verification is not a silver bullet and it cannot prove your software is generally bug free! Instead, projects like Lynx allow you to prove that certain properties of a given program hold for all specified inputs. Proofs can be automated by coding agents, but defining the underlying properties and valid inputs is very likely to benefit from developer guidance.\n\nSee the [\"Getting started with proofs\"](#getting-started-with-proofs) section below.\n\n- \n**Laws written in Elixir or Erlang** - use`Lynx.Case` to verify laws\nalongside your ExUnit tests, or`Lynx.Laws` to control when they are verified\n- \n**Kernel-checked proofs** - each law becomes a Lean theorem, with`requires:` as its hypothesis and`expects:` as its goal, and proofs\nmay not rely on`sorry` or untrusted axioms\n- \n**Whole-program translation** - your compiled code is translated together\nwith all of its dependencies, including Elixir and Erlang's standard library\n- \n**Exceptions and termination** - exceptions are part of a function's\nresult, and proving a law also proves its computation returns. Recursive\nfunctions can declare their termination with`termination_by` or`partial_fixpoint` , and`cutoff` excludes dependencies your inputs are\nproven to never reach\n- \n**Purity tracking** - every function is classified as pure, higher-order,\nsequential, or concurrent, and each law is stated in the simplest form its\npurity allows\n- \n**Concurrency** - spawning, sending and receiving messages, links, monitors,\nexit signals, and timers are modeled after OTP. Concurrent laws hold for every\ninterleaving of processes and every point at which timers fire, and steps\nthat commute are explored only once.`lynx_counterexample` prints a failing\nrun of a concurrent program, one step per line. It is also possible to validate\na given outcome in a concurrent program is possible within one of its executions\n(instead of all of its executions) by using`reaches:` instead of`expects:`\n- \n**Profiling** -`LYNX_DEBUG=lean` reports the time each module and law takes\nto verify, and translated sources can be profiled with Lean's built-in profiler\nor[leanprof](https://github.com/unbalancedparentheses/leanprof)\n- \n**Independent checks** -`LYNX_EXPORT` exports the elaborated proofs, so\nthey can be checked again by the independent checkers bundled with Lean\n\nUse Lynx with ExUnit to run proofs alongside ordinary tests. Save this example\nas `test/laws/sum_test.exs`. It defines a recursive sum and proves that the empty\nlist sums to zero and that, for integer lists, summing each list and adding the\nresults equals summing their concatenation:\n\n```\ndefmodule SumProofsTest do\n  use ExUnit.Case, async: true\n  use Lynx.Case\n\n  def sum([]), do: 0\n  def sum([x | xs]), do: x + sum(xs)\n\n  laws \"sum\" do\n    law sum_empty,\n      expects: sum([]) == 0,\n      proof: ~LEAN\"\"\"\n      simp [«sum_empty:ensures/0», «sum/1», Erlang.erlang.«==/2»]\n      \"\"\"\n\n    law sum_append(l, r),\n      requires: is_integer_list(l) and is_integer_list(r),\n      expects: sum(l) + sum(r) == sum(l ++ r),\n      proof: ~LEAN\"\"\"\n      have sums (input : Lynx.Term)\n          (valid : «is_integer_list/1» input = .ok Lynx.Term.true) :\n          ∃ value, «sum/1» input = .ok (.integer value) ∧\n            ∀ right total, «sum/1» right = .ok (.integer total) →\n              ∃ joined, Erlang.erlang.«++/2» input right = .ok joined ∧\n                «sum/1» joined = .ok (.integer (value + total)) := by\n        induction input using «sum/1».induct with\n        | case1 => exact ⟨0, rfl, fun right total returned => ⟨right, rfl, by simpa using returned⟩⟩\n        | case2 head tail ih =>\n          cases head <;> simp [«is_integer_list/1», Erlang.erlang.«is_integer/1»] at valid\n          rename_i value\n          obtain ⟨subtotal, returned, append⟩ := ih valid\n          refine ⟨value + subtotal, by simp [«sum/1», returned], ?_⟩\n          intro right total rightReturned\n          obtain ⟨joined, appended, combined⟩ := append right total rightReturned\n          exact ⟨.cons (.integer value) joined, by simp [Erlang.erlang.«++/2», appended],\n            by simp [«sum/1», combined, Int.add_assoc]⟩\n        | case3 input notNil notCons => simp_all [«is_integer_list/1»]\n      have validity : «is_integer_list/1» l = .ok Lynx.Term.true ∧\n          «is_integer_list/1» r = .ok Lynx.Term.true := by\n        simpa [«sum_append:requires/2»] using requires\n      obtain ⟨leftSum, leftReturned, append⟩ := sums l validity.1\n      obtain ⟨rightSum, rightReturned, _⟩ := sums r validity.2\n      obtain ⟨joined, appended, combined⟩ := append r rightSum rightReturned\n      simp [«sum_append:ensures/2», leftReturned, rightReturned, appended, combined,\n        Erlang.erlang.«==/2»]\n      \"\"\"\n  end\n\n  defp is_integer_list([h | t]), do: is_integer(h) and is_integer_list(t)\n  defp is_integer_list([]), do: true\n  defp is_integer_list(_), do: false\nend\n```\n\n`requires:` states the input assumptions and `expects:` must evaluate to `true`\nunder those assumptions. Each `laws` block registers one ExUnit test and verifies\nall its laws together. The `~LEAN` sigils contain the proofs checked by Lean.\nLaws also remain callable from ordinary tests, which can be used for fuzzing and\nvalidation.\n\nRun the example or all law groups with:\n\n```\nmix test test/laws/sum_test.exs\nmix test --only laws\n```\n\nLynx can also verify laws written in Erlang.\n\nEach `-law` attribute names ordinary predicate functions. A separate\nbinary `-proof` attribute must immediately follow its law:\n\n```\n-module(sum_proofs).\n-export([sum/1, sum_empty_ensures/0,\n         sum_append_requires/2, sum_append_ensures/2]).\n\n-law #{name => {sum_empty, []}, ensures => sum_empty_ensures}.\n-proof ~\"\"\"\n(SAME PROOF AS ABOVE)\n\"\"\".\n\n-law #{name => {sum_append, [l, r]},\n       requires => sum_append_requires,\n       ensures => sum_append_ensures}.\n-proof ~\"\"\"\n(SAME PROOF AS ABOVE)\n\"\"\".\n\nsum([]) -> 0;\nsum([X | Xs]) -> X + sum(Xs).\n\nsum_empty_ensures() -> sum([]) == 0.\nsum_append_requires(L, R) -> is_integer_list(L) andalso is_integer_list(R).\nsum_append_ensures(L, R) -> sum(L) + sum(R) == sum(L ++ R).\n\nis_integer_list([H | T]) -> is_integer(H) andalso is_integer_list(T);\nis_integer_list([]) -> true;\nis_integer_list(_) -> false.\n```\n\nThe proof placeholders refer to the proofs above, with the generated Elixir predicate names replaced by their Erlang equivalents.\n\nThe argument names in `name` become Lean theorem parameters. The predicate\nhelpers receive those arguments in order and remain callable from Erlang.\n`ensures` is required, while `requires` may be omitted for an unconditional\nlaw. Then call `Lynx.Laws.verify([:sum_proofs])` to validate the proofs.\n\nInstall Elixir 1.18+ and Elan, Lean's toolchain manager, with `lake` available on\n`PATH`.\n\nNow add Lynx to your application's `mix.exs` dependencies:\n\n```\ndefp deps do\n  [\n    {:lynx, git: \"https://github.com/josevalim/lynx.git\", only: :test}\n  ]\nend\n```\n\nYou likely want to lock the Lean version Lynx uses. You can do so by adding a\n`lean-toolchain` file to your project's root with the same version as Lynx's:\n\n```\nleanprover/lean4:v4.36.0\n```\n\nFor agentic usage, you can ask your agent to run `mix help Lynx` and get all\ninstructions to get started.\n\nA law states a property, `expects:`, that must hold for every input satisfying\nits assumptions, `requires:`. Several kinds of properties are straightforward\nto state and often catch real bugs. Here are some examples:\n\n- \n**Totality** - the function returns for every valid input, without raising\nor looping forever. Since a law can only prove its expectation when the\ncomputation returns, any law doubles as a proof of totality. The simplest one\nchecks the result's shape:`expects: is_binary(encode(term))` .\n- \n**Roundtrip** - one function undoes another, as with encoding and decoding,\nserializing and parsing, or compressing and decompressing:`expects: decode(encode(term)) == {:ok, term}` .\n- \n**Oracle** - the function agrees with a simpler, obviously correct\nimplementation, such as an optimized version against a naive one, or a\nrewrite against the code it replaces:`expects: fast_sort(list) == naive_sort(list)` .\n- \n**Invariants** - some aspect of the input is preserved, or some structure\nof the output always holds, such as sorting preserving the length of a\nlist:`expects: length(sort(list)) == length(list)` .\n- \n**Idempotence** - applying a function twice is the same as applying it\nonce, as with normalization and formatting:`expects: normalize(normalize(x)) == normalize(x)` .\n- \n**Algebraic laws** - the function interacts predictably with other\noperations, such as the`sum(l) + sum(r) == sum(l ++ r)` law in the\nexamples below.\n\nNote that a property does not necessarily imply the absence of bugs.\nFor example, proving that a JSON encoder roundtrips for some terms,\nsuch as `JSON.decode(JSON.encode!(term)) == {:ok, term}`,\ndoes not prove that it emits JSON according to its specification.\nSimilarly, the algebraic law written above for `sum` also holds for `length`.\nTherefore, it is important to have additional properties and tests to ensure\nthe correctness of your programs.\n\nEach law also states which inputs it is about. Assumptions that are too strong\nmake a law hold vacuously, while missing assumptions make it unprovable, so\nreview `requires:` as carefully as `expects:`.\n\nFinally, 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).\n\nThe Elixir code, the translation layer, and the overall design of the Erlang runtime in Lean were done with full human design and review. Proofs, which are validated by Lean's kernel, and the deserialization layer in Lean were produced by coding agents with limited review.\n\nThe project requires Elixir 1.18+ and Lean 4.36.0+, which includes Lake. With those installed, fetch dependencies and compile the project with:\n\n```\nmix deps.get\nmix compile\n```\n\nRun tests with:\n\n```\nmix test          # Elixir tests\nmix test.lean     # Lean tests only\nmix test.all      # Elixir + Lean\n```\n\nBefore committing:\n\n```\nmix precommit\n```\n\nThe Lean source code can be found in the `Lean` directory.\nYou can run `lake` commands from that directory whenever working\nwith Lean directly.", "url": "https://wpnews.pro/news/lynx-write-proofs-about-erlang-elixir-programs-using-lean", "canonical_source": "https://github.com/josevalim/lynx", "published_at": "2026-11-23 22:20:21+00:00", "updated_at": "2026-11-23 22:42:18.110226+00:00", "lang": "en", "topics": ["developer-tools", "artificial-intelligence"], "entities": ["Lynx", "Lean", "Erlang", "Elixir", "ExUnit", "Lynx.Case", "Lynx.Laws", "OTP"], "also_reported_by": [], "takeaway": "Lynx translates compiled Erlang/Elixir code and its standard-library dependencies into Lean, turning each law's `requires:` into a theorem hypothesis and `expects:` into its goal, with `termination_by`/`partial_fixpoint` for recursive functions and `reaches:` to check that an outcome is possible in ", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/lynx-write-proofs-about-erlang-elixir-programs-using-lean", "markdown": "https://wpnews.pro/news/lynx-write-proofs-about-erlang-elixir-programs-using-lean.md", "text": "https://wpnews.pro/news/lynx-write-proofs-about-erlang-elixir-programs-using-lean.txt", "jsonld": "https://wpnews.pro/news/lynx-write-proofs-about-erlang-elixir-programs-using-lean.jsonld"}}