Skip to content

Latest commit

 

History

History
583 lines (458 loc) · 31.6 KB

python-guide.md

File metadata and controls

583 lines (458 loc) · 31.6 KB

Python guide

leanfran | Python quick start

Source paths below are relative to langs/Python/.

Install

uv add leanfran
nix profile install 'github:conao3/lean-leanfran/v<version>#leanfran'

<version> is the release of the Python package; the package and the compiler come from the same release. Put lean and lake of Lean 4.35.0 on PATH. Generated modules run with the Python package and pydantic alone.

Quick start

Write a Lean block in a module of your package:

# src/myapp/arith.py
from leanfran import lean

arith = lean("arith", r"""
def double (n : Nat) : Nat := n + n

theorem double_eq (n : Nat) : double n = 2 * n := by
  unfold double; omega
""")

Generate the code and call it:

$ uv run leanfran --lang python sync
leanfran: 1 blocks checked and generated
$ uv run python -c 'from myapp.arith import arith; print(arith.double(21))'
42

sync also prints the progress of Lake. A changed block is stale until the next sync:

$ uv run leanfran --lang python status
myapp.arith:arith: stale

Samples

samples/ holds Python packages with Lean blocks. make check-samples syncs each one, runs it, and compares the output with its expected.txt.

sample shows
word-count strings and lists, a proof by induction
roman-numerals a round-trip theorem checked for every number below 1000 (decide +kernel)
todo-cli an invariant over a list kept by every operation, JSON storage, tampered JSON rejected
verified-python a proved refines and a property test of the original Lean specification
pricing-api FastAPI with a pydantic model and a Lean inductive type as request body, 422 for invalid input

samples/steps/ introduces one feature at a time, from functions on Nat (01) to types shared between blocks with uses= (09).

Lean blocks

lean(name, source, *, imports=(), uses=(), models=()) defines a Lean block of the calling module, which must belong to a package. The block's definitions live in the namespace LeanPythonEmbed.<module>.<name>. The returned module exposes them under their names relative to it (Discount.percent, total).

  • imports=["Std.Data.HashMap"]: Lean modules to import.
  • uses=["geometry"]: other blocks of the module (or "pkg.mod:name") to import and open. The block shares their types and does not generate them again.
  • models=[LineItem]: pydantic models available as Lean structures (below).

A Lean error points at the Python file:

src/myapp/m.py:6:54: error: (lean block myapp.m:m, Lean 4:53) Tactic `rfl` failed: The left-hand side ...

At run time lean(...) compares a hash of the block (its source, imports, uses and the Lean structures of its models) with blocks.json. If the block changed since the last sync or its generated module is missing, it raises LeanBlockStale:

leanfran: the Lean block myapp.arith:arith is out of date; run 'leanfran --lang python sync'

With LEANFRAN_AUTO_SYNC=1 it runs leanfran --lang python sync instead.

Your pydantic models in Lean

models=[LineItem] writes a Lean structure for each model (and the models its fields use) to the namespace LeanPythonModels.<python module>, and the block opens that namespace:

structure LineItem where
  sku : String
  qty : Nat
  qty_ge : 1 ≤ qty
  unitPrice : Nat

int with a lower bound of at least 0 becomes Nat; the other bounds and min_length/max_length become proof fields. Field types:

  • int, bool, str, float, list[T], tuple[...], T | None, other models
  • enums: an inductive type LeanPythonModels.<module>.<Enum> with a constructor per member
  • Literal["a", "b"]: LeanPythonLiterals.<module>.<Model>_<field>
  • unions of models: LeanPythonUnions.<module>.<Model>_<field>, a constructor per model holding it as val

Lean proofs cannot assume multiple_of, pattern or validators; the structure's docstring lists them. A length is the number of code points in pydantic and in Lean. A value that a validator or str_to_lower changes after pydantic has checked its length or bounds is rejected on the way to Lean when the new value breaks the constraint. Generated functions take and return your classes. Values that skipped validation (model_construct) go through validation again on the way to Lean.

Types

Lean Python
Nat int (leanfran.types.Nat = Annotated[int, Ge(0)])
Int int
UInt8 … UInt64, USize, Int8 … Int64 int with the range as Ge/Le
Fin n Annotated[int, Ge(0), Lt(n)]
Bool bool
Char str of one character
String str
Float, Float32 float
Unit None
Option α α | None
List α, Array α list[α]
α × β tuple[α, β]
Except ε α leanfran.Ok[α] | leanfran.Err[ε]
{x : α // p x} Annotated[α, AfterValidator(p)]
structure a frozen, strict pydantic model
inductive type, constructors without arguments enum.StrEnum
other inductive type a model per constructor, subclasses of the type's class
IO α α; an IO.Error is raised as LeanIOError (an OSError)

The generated functions check arguments while they convert them: pub.double(-1) raises ValidationError with the location of the bad value. Constants are functions without arguments (answer()).

Constructors and structures take keyword arguments (Shape.rect(width=1, height=2)); unnamed constructor arguments are a0, a1, …. Inductive values work with match:

match shape:
    case geometry.Shape.rect(width=w, height=h):
        ...

A function returning Except ε α returns Ok(value=…) or Err(error=…), and an Except argument or field takes either:

from leanfran import Err, Ok

match kernel.transition(actor, snapshot, command):
    case Ok(value=(write, reply)):
        ...
    case Err(error=e):
        ...

Handles

A generated function converts its arguments to Lean values and its result back on every call, which costs time in proportion to their size. fn.lean is the same function on handles (leanfran.Lean): it takes Python values or handles and returns a handle, which keeps the Lean value without converting it.

snapshot = kernel.init.lean()
result = kernel.transition.lean(actor, snapshot, command).get()
snapshot = kernel.apply.lean(snapshot, write)
rows = snapshot.get()
snapshot = kernel.apply.lean.params["snap"].new(rows)
  • handle.get() converts a handle to the Python value.
  • fn.lean.params[name] and fn.lean.result are the Lean types of the function (leanfran.LeanType), and handle.type is the type of a handle. type.new(value) checks a Python value like an argument and makes a handle. A handle of another Lean type is rejected with ValidationError.
  • A handle is immutable: Lean functions that receive it build new values instead of updating in place.

fn.local is the function on local handles (leanfran.Local). A local handle keeps the reference counts of its objects, so a Lean function can update the value in place when it gets the only reference. Passing a local handle keeps it valid; handle.take() gives its reference to the function and leaves the handle empty:

snapshot = kernel.init.local()
result = kernel.transition.local(actor, snapshot, command).get()
snapshot = kernel.apply.local(snapshot.take(), write)  # the list is updated in place
  • type.new_local(value) makes a local handle of a Python value and local.share() the Lean handle of a local one. fn.local and fn.lean take both kinds.
  • Use a local handle, and the local handles made from it, from one thread at a time: the reference counts are plain Python integers, also on free-threaded builds. A Lean handle can be read from several threads, since its objects are never updated.

IO actions have no lean and no local. One transition and apply on a snapshot of 100 two-number structures in a List takes 0.84 ms with Python values, 0.09 ms with Lean handles and 0.06 ms with a local handle.

JSON

The JSON of a generated model is the JSON of Lean's derived ToJson: a structure is an object, a constructor without arguments is its name ("dot"), a constructor with named arguments is {"rect": {"width": 1, "height": 2}}, with unnamed arguments {"num": 7} or {"pair": [1, "x"]}. Ok is {"ok": value} and Err is {"error": error}, the JSON of deriving instance ToJson for Except. tests/test_json.py compares the generated models with a native Lean program that prints toJson.

Generated code

leanfran --lang python sync imports every module of the packages of the project, writes each block to a Lake workspace in .leanfran/python/workspace/ at the project root, builds it, and generates src/myapp/_lean/<module>__<name>.py and src/myapp/_lean/blocks.json. It records the blocks and the generated files in leanfran.manifest.json at the project root and prints leanfran: <N> blocks checked and generated.

_lean/__init__.py and the generated modules start with

# Code generated by leanfran --lang python (generator 7) from LeanPythonEmbed.myapp.arith.arith. DO NOT EDIT.

where from <Lean module> is absent in _lean/__init__.py. sync replaces and deletes only the files of the manifest and those whose first line names a Lean module of leanfran (LeanPythonEmbed and the others of the workspace); it stops with 254 before it overwrites another file.

Commit <package>/_lean/ and leanfran.manifest.json. sync writes .leanfran/.gitignore, which keeps the workspace and the lock file .leanfran/lock out of git.

Performance

make bench (CPython 3.14, x86_64; the native column is the C backend):

workload n Python (s) native C (s)
Array.push, set!, sum 10⁴ 0.017 0.005
Array.push, set!, sum 10⁵ 0.179 0.006
Array.push, set!, sum 10⁶ 1.796 0.017
fib (loop) 10⁵ 0.176 0.074
naiveFib 25 0.149 0.005
String.push 10⁴ 0.012 0.005
String.push 10⁵ 0.227 0.006
Array.qsort 10⁵ 1.929 0.020

Passing 10⁴ models to a Lean function takes 0.036 s (pydantic's TypeAdapter(list[Model]) validates 10⁴ dicts in 0.009 s).

Commands

Set LEANFRAN_CLI to select the compiler executable used by host tools (default: leanfran on PATH). Set LAKE to select the Lake executable used by the compiler (default: lake on PATH).

Every command is a command of the executable leanfran:

leanfran --lang python sync [--dir <dir>] [--verbose]
leanfran --lang python check [--dir <dir>] [--verbose] [--require proved]
leanfran --lang python status [--dir <dir>] [--require proved]

--dir is the project directory (default: the working directory). The project root is the nearest directory at or above it with a leanfran.toml, or else with a pyproject.toml. The executable reads the packages with python3 -m leanfran.cli scan and, during check, translate, run in the root. These two commands print JSON and write no file; the executable builds the Lake workspace in .leanfran/python/workspace, generates the Python, installs it, and writes leanfran.manifest.json and leanfran.lock. A failed install restores the previous files. sync and check take .leanfran/lock for the whole run and status shares it.

leanfran --lang python status runs without Lean and Lake. It compares the blocks with the manifest and checks that the generated files exist, then compares the functions with the lock. It prints <block>: stale, <block>: missing <path> and <block>: removed for blocks (calc.spec:spec: stale), python: missing <path> for a missing _lean/__init__.py or _lean/blocks.json, and the function rows of check, with stale for a function when its source, the pydantic models of its types, the blocks of its specifications (with the blocks they use), a @model function that it calls or a proof changed, and <id>: removed for a locked function that the project no longer has. It prints no row for a fresh block. status exits 1 when it prints a block row, a stale or removed function, or an unextracted or failed obligation, and with --require proved when an obligation is not proved. It hashes with sha256sum (shasum on macOS), so that command must be on PATH; without it sync, check and status exit 255.

Run leanfran where python3 imports the project's leanfran, for example uv run leanfran --lang python sync; otherwise it prints that example and exits 255. The Python package installs no command. The release version, generator version and Lean version of the executable must match the installed Python package, so install both from the same release. The executable reads the version of the installed leanfran distribution before it runs the package and, for another release, exits 255 with the command that installs the package of its release (uv add leanfran==<version>). The package exits 255 when an older executable passes it sync, check or status, and names the compiler release to install. lean and lake on PATH must have the executable's Lean version, Lean 4.35.0, and a lean-toolchain at the project root must name the same version for sync and check. A mismatch exits 255.

module generate

The same executable compiles a built Lean module:

leanfran --lang python module generate --module-name <Name> [--roots <Name> ...] [--namespace <Name>]
  [--output-file <path>] [--type-module <Name>=<module> ...] [--model-module <Name>=<module> ...]
  [--import <Name> ...] [--search-path <dir> ...] [--internal-only] [--output json|text]
leanfran --lang python module generate --batch <file> [--import <Name> ...] [--search-path <dir> ...]
  [--internal-only] [--output json|text]
leanfran --lang python obligations check --modules <Name> ... --obligations <file> [--search-path <dir> ...]
leanfran --lang python --version | --generator-version | --help

leanfran --lang python <command> --help prints the options of a command.

A job of a --batch file has the keys module, output_file, roots, namespace, type_modules and model_modules (arrays of {"namespace", "target"}), path (the Python name of the generated module) and type_group (jobs that share types). An unknown key or a value of another type exits 252. The exit code of a batch is the highest one of its jobs.

module generate writes one Python module with the IR of the roots and of everything they call (Init and Std included), and public functions and types for the roots. It reports the definitions it cannot expose (polymorphic functions, functions over functions) as skipped. The @[csimp] lemmas of the modules, and of those that --import adds, apply to the roots; a lemma whose other side is an @[extern "py:<module>#<qualname>"] definition applies to every call. These commands use the exit codes 0 success, 252 invalid parameters, 254 input that cannot be converted, 255 other errors.

Exit codes

sync, check and status exit 0 on success, 1 for the rows and states described in Verifying Python functions, 252 for an argument they cannot read, 254 for an error in the package (a Lean diagnostic, a module that fails to import such as src/myapp/broken.py:1:1: error: RuntimeError: boom, a file leanfran did not generate at a path that sync writes) and 255 for an error in the environment (a missing tool, a version mismatch).

Configuration

The project file leanfran.toml is optional. The settings of sync, check and status describe the project root, [check], [[require]] and projects with several languages.

The packages are the directories of paths in [embed.python] of leanfran.toml, relative to the project root:

[embed.python]
paths = ["src/myapp", "src/mylib"]

Without paths, the package is src/<name>, or else <name>, where <name> is the project name of pyproject.toml at the project root in lower case with _ for - and .. A package has an __init__.py. Packages of one project have different names, do not contain each other, and can use each other's blocks (uses=["pkg.mod:name"]). [[require]] tables of leanfran.toml add Lake packages to the workspace.

With paths = ["."] the project root is the package. The package then has the name of that directory, so Python imports it from the directory above: in flat/, sync generates the block of flat/arith.py as flat.arith:arith, and from flat.arith import arith works with the parent of flat/ on sys.path.

Variable Effect
LEANFRAN_AUTO_SYNC=1 A stale lean(...) runs leanfran --lang python sync instead of raising LeanBlockStale.
LEANFRAN_RUNS, LEANFRAN_SEED The number of inputs and the seed of the random tests.

Verifying functions

@model binds a typed, pure Python function to specifications written in a Lean block. The function stays ordinary Python. leanfran --lang python check translates it to Lean and checks your proofs, and check_model runs the same specifications as a Hypothesis random test.

Marking a function

from leanfran import lean
from leanfran.verify import model

spec = lean("spec", r"""
def clampSpec (x lo hi : Int) : Int := max lo (min hi x)
def ordered (_x lo hi : Int) : Bool := lo ≤ hi
def inRange (_x lo hi : Int) (r : Int) : Bool := lo ≤ r && r ≤ hi
""")

@model(refines=spec.clampSpec, requires=spec.ordered, ensures={"in_range": spec.inRange})
def clamp(x: int, lo: int, hi: int) -> int:
    if x < lo:
        return lo
    if x > hi:
        return hi
    return x
  • refines=s: f x = s x (Except.ok (s x) for a function that may fail); requires=p: p x = true → before each obligation; ensures={"label": q}: q x (f x) = true. A function annotated -> Nat also gets returns_nat (0 ≤ f x).

  • The labels of ensures match [a-z][a-z0-9_]*; refines and returns_nat are reserved.

  • The translation: int is Int (a Nat parameter is a Nat converted to Int on entry); statements become Lean do notation (let mut, for, while, break, continue, early return); indexing, //, %, raise and while make the function return Py.M α = Except Py.Exc α, with Python's negative indices and floor division (LeanPythonLib.Py). A while loop that does not end is the error nonTermination, so a refines of it includes that it ends; Py.Loop.forIn_eq unfolds one round (tests/ops/lean/Proofs/Ops.lean).

  • Supported types: int, bool, str, float, list, tuple, T | None, and pydantic models (as the Lean structures of models=). An operation is translated for the types for which Python returns the value of the Lean operation, and a value of another type is not converted (bool to int, int to float):

    operation types
    +, -, *, unary - int, float; + also str, list
    //, % int
    ==, != int, bool, str, float and their T | None; lists and tuples of int, bool, str
    <, <=, >, >= int, bool, str, float; lists of int, bool, str
    in, not in str in str; a list of a type that has == in a list
    and, or, not, conditions bool
    x[i] lists; tuples with a literal index
    len / sum / abs / min, max of two str, list / list[int] / int / int, bool, float
    fields, list comprehensions, calls of other @model functions of the module
  • Not translated: == and in on lists and tuples with a float (Python compares the elements by identity first, so a NaN is equal to itself) and on models (__eq__ of the class); assert (python -O removes it); recursive calls; the else of a loop; a variable that is read in another block than the block of its first assignment; raise of a value that is not an exception class or its call; a negative number for a Nat parameter; *args, default values and keyword arguments in calls; a name that the module, an outer function or a local variable defines in place of a builtin function; a function below a decorator other than @model.

  • append and += update a list that the function created (a literal, a comprehension, xs + ys). They are not translated while another name or value may refer to the list, and in a loop over it.

  • On str: literals without a surrogate, +, len, the comparisons and in, which are about code points as in Lean.

Obligations and proof status

leanfran --lang python check runs sync, then writes the translation and one obligation per specification to .leanfran/python/workspace/LeanPythonModel/calc/calc.lean. In tests/verify, where the block is in calc/spec.py, the file starts:

import LeanPythonEmbed.calc.spec.spec
import LeanPythonLib.Py

/-- `calc.calc.clamp`, translated from Python. -/
def LeanPythonModel.«calc».«calc».clamp (x : Int) (lo : Int) (hi : Int) : Int := Id.run do
  if (decide (x < lo)) then
    return lo
  if (decide (x > hi)) then
    return hi
  return x

abbrev LeanPythonModel.«calc».«calc».clamp.obligation.refines : Prop :=
  ∀ (x : Int) (lo : Int) (hi : Int), LeanPythonEmbed.calc.spec.spec.ordered x lo hi = true → (LeanPythonModel.«calc».«calc».clamp x lo hi) = (LeanPythonEmbed.calc.spec.spec.clampSpec x lo hi)

Then it judges the theorems <function>.proof.<label> of lean/Proofs/*.lean at the project root:

import LeanPythonModel.calc.calc
open LeanPythonEmbed.calc.spec.spec
namespace LeanPythonModel.«calc».«calc»

theorem clamp.proof.refines : clamp.obligation.refines := by
  intro x lo hi h
  simp only [ordered, decide_eq_true_eq] at h
  simp only [clamp, clampSpec]
  split <;> (try split) <;> simp_all <;> omega

It prints a row <id> [<label>]: <state> per obligation (tests/verify):

calc.calc:clamp [in_range]: proved
calc.calc:clamp [refines]: proved
calc.calc:first_or [refines]: proved
calc.calc:half [refines]: sorry
calc.calc:half [returns_nat]: missing
calc.calc:sum_abs [nonneg]: proved
calc.calc:sum_to [refines]: proved
calc.calc:sum_to [returns_nat]: proved

Under simp, a for loop over a list becomes List.foldl (forIn_pure_yield_eq_foldl), so you prove a loop by induction on the list (tests/verify/lean/Proofs/Calc.lean proves sum_abs).

The states:

state meaning
proved the theorem holds
sorry the proof uses sorry
axioms the proof uses non-standard axioms
failed the proof has an error, or the kernel rejects it
missing no theorem for the obligation
mismatch the theorem states something else
unextracted the function has no obligation to prove (reasons)

A function that cannot be translated also prints <file>:<line>:<column>: error: unextracted <id>: <message> on stderr, for example calc/calc.py:40:16: error: unextracted calc.calc:distinct: unsupported expression SetComp. check exits 1 when an obligation is unextracted or failed, and with --require proved when an obligation is not proved. It writes the results to leanfran.lock at the project root; commit the lock with the manifest.

The hash of a function covers its source and the blocks of the project. Import the model module of the function in its proof file (import LeanPythonModel.<module>).

Replacing a proved specification

Leanfran replaces a specification only when status reports a proved refines without requires, the generated code can call the implementation, and its values can round-trip. The model must not use a specification that is a candidate for replacement. If several functions qualify for one specification, the first by function id wins.

The obligation must cover all of the specification's arguments in the same order, and the model and specification types must match after unfolding reducible definitions such as abbrev. The sole result exception is an Int model result for a Nat specification; that proof guarantees a nonnegative result. Arguments coerced or supplied by elaboration do not qualify.

check writes the lock and applies the replacement. The next sync drops it if the function, its dependencies, the proofs, or other inputs changed so that status no longer reports it as proved. Until that sync, generated calls may still reach the changed implementation. Random tests always compare the host function against the Lean body with no replacements.

The bridge looks up the function on each call and imports its module if needed. If the module is unavailable or has not defined the function yet, it runs the Lean body. The original is available as spec.sumTo.spec for a function named sumTo and is what check_model compares against. Exceptions from the host function reach the caller.

Values that do not round-trip, such as triples, unions with a subclass of another arm, and model fields of those types, make a function ineligible. Keyword-only parameters, nested functions, and decorators that prevent resolving the original modeled function also prevent replacement.

Random tests

Each accepted input calls the implementation once. The test checks refines first, then ensures in the written order, and reports the first failure for that function. run is the zero-based index of the original failure among accepted inputs; input shows the counterexample after shrinking. If the host call fails, the value is failed: <reason>. If a specification fails, the report says the spec failed and shows error: <reason>.

  • check_model(f) / check_module(m) generate arguments from the annotations (pydantic constraints included), skip those failing requires, and compare with refines and ensures. check_module(m) reports failures from all modeled functions together. A float can be a NaN, an infinity or -0.0, and a list can have an element twice. An int with a lower and an upper bound (Int64) takes the bounds and the numbers around powers of two such as 2⁵³; without both bounds it is between -1000 and 1000, and about one of three is around ±2³¹, ±2⁵³, ±2⁶³ or ±2⁶⁴ when the function is fast for them: it has no loop, comprehension or recursion, calls only such @model functions, abs, min, max, len, int, float, round and functions of math, and repeats no list or str. Such an argument is left out when the specification takes more than 100,000 steps. Give the parameter bounds (Int64) to test a function with a loop on large numbers. A result is the value of refines when its type is the same too: True is not 1, 0.0 is not -0.0, and a NaN is a NaN. LEANFRAN_RUNS (1 to 2147483647) sets the number of arguments that satisfy requires (200 by default) and LEANFRAN_SEED (0 to 9223372036854775807) the seed (1 by default); check_model(f, max_examples=, seed=) overrides them. A failure raises PropertyFailure with the input that Hypothesis shrank, the seed, and the number (from 0, of the arguments that satisfy requires) of the run that failed first:

    calc.calc:clamp [refines]: mismatch (seed 1, run 3)
      input: x=1, lo=0, hi=0
      expected: 0, got: 1
    

    An ensures specification shows <name in the block> does not hold in place of mismatch and result: <value> in place of the last line. A function that raises shows failed: <exception> as its value, and a specification that raises shows the spec failed and error: <exception>. Arguments can repeat, so a function of one bool also runs 200 times. check_model fails when it discards more than 100 arguments per run because they do not satisfy requires.

Limits

  • leanfran does not expose polymorphic functions, functions taking or returning functions, or Thunk/Task/IO.Ref/ByteArray in public signatures. They still run inside Lean code.
  • Tasks run synchronously.
  • Building a String with String.push copies the string each time (Python bytes), so it grows quadratically.
  • The translation of Python functions covers the subset above. A proof is about arguments of the annotated types, with the names that the module has when check imports it: an int for a float parameter, a bool for an int parameter, and a global name that another module replaces while the program runs are outside of it. ensures says nothing about a call that fails or does not end.