alkahest

The reflective certificate kernel

Indefinite-integration certificates are, by default, checked by a small verified checker in the repository's Lean library Alkahest.Kernel instead of by a tree of Mathlib tactics. This is proof by reflection. The certificate is data: an expression AST for the claim plus a witness. A Boolean checker, written and proved correct in Lean, decides it, and one soundness theorem, proved once in the library, turns check data = true into the mathematical statement. The same kernel checks dsolve solutions (alkahest.experimental.dsolve_certificate, below) and the PDE residuals of alkahest.fex.finalize (PDE residuals).

The alkahest_check tactic puts the same checker behind a tactic for goals you write yourself in Lean, with Alkahest as an untrusted witness oracle.

Definite integrals take the same path through defint_sound (Definite integrals). Not every certificate does: answers the kernel does not encode fall back to the HasDerivAt tactic emitter (or, for a definite integral, the tactic interval-FTC proof), and the other certified operations (derivatives, limits, sums, resultants, rewrites) have tactic emitters only. certificate_status["path"] says which checker a result's certificate uses.

Lean
import Alkahest.Kernel

open Alkahest.Kernel in
theorem alkahest_integral (x : ℝ) (h1 : x ≠ 0) :
    HasDerivAt (fun (x : ℝ) => Real.log x) ((x)⁻¹) x :=
  integral_sound (H := [(.ne (.var 0))])
    (F := (.app .log (.var 0)))
    (f := (.inv (.var 0)))
    (w := ⟨[⟨(.var 0), .zero⟩, ⟨(.fn .log), (.var 0)⟩, ⟨.inv, (.var 0)⟩], [], []⟩)
    (by decide +kernel) [] x ⟨h1, trivial⟩

The statement is written in ordinary notation. AExpr.eval unfolds to exactly that term, so Lean matches it against the soundness theorem's conclusion by definitional unfolding. A reader checks the statement, not the data.

What the checker does

checkIntegral H F f w (in Alkahest/Kernel/Check.lean):

  1. computes the symbolic derivative D 0 F itself (Deriv.lean). The soundness theorem D_hasDerivAt says that on the domain dconds F (denominators, log arguments ≠ 0, sqrt radicands > 0, arcsin arguments in (-1, 1), cos ≠ 0 under tan), y ↦ F has derivative D 0 F;
  2. decides each of those side conditions from the hypotheses H with a structural sign checker (Sign.lean, the reflective analogue of positivity): exp, cosh, π, even powers, positive literals, sums and products of positive terms, b < a ⟹ a - b > 0;
  3. checks D 0 F - f = Σ cᵢ·(Lᵢ - Rᵢ) as an identity of polynomials over ℚ in atoms (Norm.lean, Poly.lean). Each Lᵢ = Rᵢ is a relation proved in Rel.lean: u·u⁻¹ = 1 (needs u ≠ 0), √u² = u (needs 0 ≤ u), (u^(1/q))^q = u (needs 0 ≤ u), erfc u = 1 - erf u, sin² + cos² = 1, cosh² - sinh² = 1, the addition formulas for sin, cos, sinh, cosh and exp, tan = sin/cos, tanh = sinh/cosh, log (exp a) = a, and a few more. Their side conditions are also decided from H.

Atoms are given by a table in the witness, but the kernel normalises each atom's argument against the earlier entries. So sin (x + 1) and sin (1 + x), or (1 + x²)⁻¹ from D (atan x) and (x² + 1)⁻¹ in the integrand, are the same atom without any trusted matching. Inverses distribute over monomials unconditionally ((c·a²)⁻¹ = c⁻¹·(a⁻¹)² holds in Lean's ℝ, where 0⁻¹ = 0). Facts that need a nonzero denominator enter only through the relation u·u⁻¹ = 1, whose condition the checker decides.

Special functions and roots

The normal form treats g(u) as an opaque atom, so the checker only needs a function's derivative. Any function defined as the integral of an elementary one therefore costs one constructor, one rule in D and one HasDerivAt lemma. Mathlib v4.36 defines none of the functions marked "Alkahest-defined" below, so Alkahest/Kernel/Special.lean defines each by its textbook integral and proves its derivative from Mathlib's fundamental theorem of calculus. Certificates that mention them state their theorems about exactly these definitions:

function Lean name in certificates source definition DLMF derivative D domain the kernel uses (stated as hypotheses)
exp, log, sin, cos, tan, √, atan, asin, acos, sinh, cosh, tanh, asinh Real.exp, Real.log, … Mathlib Mathlib's §4 Mathlib's lemmas log: x ≠ 0; √: x > 0; tan: cos x ≠ 0; asin/acos: -1 < x < 1
x^(1/q), q ≥ 3 x ^ ((1 : ℝ) / ((q : ℕ) : ℝ)) Mathlib (Real.rpow) Mathlib's §4.2(iv) (q · (x^(1/q))^(q-1))⁻¹ x > 0
erf Alkahest.Kernel.erf Alkahest-defined 2/√π · ∫₀ˣ exp(-t²) dt 7.2.1 2/√π · exp(-x²) all x
erfc Alkahest.Kernel.erfc Alkahest-defined 1 - erf x 7.2.2 -2/√π · exp(-x²) all x
erfi Alkahest.Kernel.erfi Alkahest-defined 2/√π · ∫₀ˣ exp(t²) dt 7.2.1 (erfi x = -i·erf(ix)) 2/√π · exp(x²) all x
Si Alkahest.Kernel.Si Alkahest-defined ∫₀ˣ sin t / t dt (Real.sinc) 6.2.9 sin x / x x ≠ 0
Shi Alkahest.Kernel.Shi Alkahest-defined ∫₀ˣ sinh t / t dt 6.2.15 sinh x / x x ≠ 0
Ci Alkahest.Kernel.Ci Alkahest-defined γ + log x + ∫₀ˣ (cos t - 1)/t dt 6.2.11 cos x / x x > 0
Chi Alkahest.Kernel.Chi Alkahest-defined γ + log x + ∫₀ˣ (cosh t - 1)/t dt 6.2.16 cosh x / x x > 0
Ei Alkahest.Kernel.Ei Alkahest-defined γ + log x + ∫₀ˣ (exp t - 1)/t dt 6.2.5, 6.6.2 exp x / x x > 0
li Alkahest.Kernel.li Alkahest-defined Ei (log x) 6.2.8 1 / log x x > 0, x - 1 ≠ 0
dilog (Li₂) Alkahest.Kernel.dilog Alkahest-defined -∫₀ˣ log(1 - t)/t dt 25.12.2 -log(1 - x) / x x < 1, x ≠ 0
fresnels Alkahest.Kernel.fresnelS Alkahest-defined ∫₀ˣ sin(π t²/2) dt 7.2.8 sin(π x²/2) all x
fresnelc Alkahest.Kernel.fresnelC Alkahest-defined ∫₀ˣ cos(π t²/2) dt 7.2.7 cos(π x²/2) all x

Each Alkahest-defined function is checked numerically in CI (tests/test_lean_kernel_special_defs.py). The test evaluates the Lean definition literally, with its integrand, limits and constants, by quadrature. It compares the result with mpmath reference values and with alkahest's own evaluator of the function of the same name. A wrong normalisation, such as a Fresnel integral without π/2 or Ci without γ, fails it.

  • γ is Mathlib's Real.eulerMascheroniConstant and log is Real.log (which is log |x| for x < 0).
  • Each integrand (g t - g 0)/t is Mathlib's dslope g 0 t. It fills the removable singularity at t = 0 with g'(0), the same construction as Mathlib's Real.sinc = dslope sin 0, so every integrand is continuous.
  • The Fresnel integrals use the normalised convention (π/2 inside), which is alkahest's fresnels/fresnelc, DLMF 7.2.7–8, SymPy, SciPy and Mathematica. A certificate whose integrand is sin(x²) does not check against fresnelS.
  • The domains are where these formulas are the real functions alkahest means, and a certificate states each one as hypotheses (or derives it, as for Ei(eˣ)). Ci and Chi are complex for x < 0, and Li₂ is complex for x > 1, so the kernel only uses them on x > 0 and x < 1. Ei is real for x < 0 as well, but the kernel uses it only on x > 0. li x = Ei (log x) holds for every x > 0, x ≠ 1. An answer on any other branch gets no kernel certificate; the side condition cannot be derived or assumed there.
  • The derivative rules sin x / x, exp x / x, … are written with Lean's division, where t / 0 = 0. They are only true for x ≠ 0, so that condition is part of the rule's domain and becomes a hypothesis when the certificate cannot derive it.

The tactic emitter's in-file preamble keeps its own alkahestErf, alkahestErfi and alkahestSi, defined by the same integrals, so tactic certificates still need only Mathlib.

Rational powers. x ^ (1/q) for q ≥ 3 is the constructor .root q, which evaluates to Mathlib's Real.rpow: (x : ℝ) ^ ((1 : ℝ) / ((q : ℕ) : ℝ)). Alkahest writes every rational power x^(p/q) as (x^(1/q))^p, and square roots as Real.sqrt. For x < 0, Real.rpow is not the real root, and alkahest's x^(1/3) is the principal (complex) power, so neither means the real cube root there. A certificate therefore mentions x ^ (1/q) only under the hypothesis 0 < x, or when the sign checker derives it. The emitter adds 0 < base for every root in the statement, the integrand included, not only for the roots it differentiates. The derivative is D (x^(1/q)) = (q · (x^(1/q))^(q-1))⁻¹. The relation (x^(1/q))^q = x (for 0 ≤ x) lets the checker reduce powers of the root atom. Roots of one base with different indices are related through the root of the least common index: x^(1/q) = (x^(1/(qk)))^k and √x = (x^(1/(2k)))^k. That is how ∫ 1/(x^(1/3) + √x), whose answer is written in x^(1/6), is checked.

The trusted base

To accept a kernel certificate you trust:

  • Lean's kernel, which type-checks the proof term and evaluates the checker when it reduces decide +kernel;
  • the Mathlib definitions the statement mentions (HasDerivAt, Real.exp, Real.log, …);
  • the statement itself, which you read: the theorem says what it proves in ordinary notation.

You do not trust Alkahest, the Rust emitter, the atom table or the cofactors in the witness: if any of them is wrong, the checker returns false and the certificate does not compile. The checker and its soundness theorems (D_hasDerivAt, integral_sound, ode_sound, pde_sound) are themselves proved in Lean, and CI rejects any sorry, admit or axiom in Alkahest.Kernel.

A definite-integral certificate adds the subdivision pts to that list of untrusted data, and the trusted Mathlib definitions grow by intervalIntegral (the ∫ x in a..b of the statement). defint_sound itself is proved from Mathlib's intervalIntegral.integral_eq_sub_of_hasDerivAt, and the interval decider's enclosures from Mathlib's bounds on exp, log, √, sin, cos, rpow and π (Real.add_one_le_exp, Real.mul_le_sin, Real.pi_gt_d6, …) and from the defining integrals of erf and erfi in Alkahest.Kernel.Special.

The opt-in kernel_native mode (below) closes the same certificate with native_decide, which adds Lean's compiler and Lean.ofReduceBool to that list. The default never uses it.

Kernel reducibility

Every checker is structural recursion over lists and the AST, using Nat, Int and ℚ arithmetic, which the Lean kernel evaluates with GMP-backed literals. Merges such as polynomial addition use an inner/outer recursion instead of well-founded recursion, which the kernel cannot unfold efficiently. Certificates are closed by decide +kernel, which sends the Boolean straight to the kernel without elaborator-level reduction.

native_decide is opt-in: alkahest.set_lean_certificate_mode("kernel_native"). It compiles the checker and adds Lean's compiler and Lean.ofReduceBool to the trusted base. The certificate says so in its header, and certificate_status["path"] reports "kernel_native". CI rejects any default certificate that uses it.

Measured cost

Per-certificate check time, from Lean's profiler: every category except import, so loading Mathlib is excluded. Shared corpus: the calculus suites' 163 integrals that both paths certify.

kernel tactic
median 0.32 s 0.58 s
90th percentile 3.3 s 29.5 s
max 13.1 s 107.9 s
import (median) 5.5 s 7.2 s

The kernel is faster on every certificate, with a worst-case ratio of 0.82. What made the difference:

  • Witness numbers are raw literals (nat_lit, Int.ofNat, Int.negSucc), so the elaborator runs no OfNat instance search per number.
  • Comparisons are Nat.blt matched as Bool, not Decidable instances.
  • The atom lookup uses a structural Boolean equality: the derived DecidableEq on lists of ℚ was the slowest step.
  • Products put the shorter operand outermost, and cofactor terms arrive in the kernel's own order.

Fallback and reporting

The Rust emitter (alkahest-core/src/lean/kernel.rs) mirrors the Lean checker exactly: the same D, the same normal form and the same sign rules. It computes the atom table, relations and cofactors the checker will accept, and re-verifies the identity before emitting. When it cannot encode an answer (RootSum, special functions outside the table above such as EllipticF, constants of unproved sign, atoms whose arguments differ only through an irrational scaling such as fresnels(x·√(2/π))), integrate's certificate falls back to the HasDerivAt tactic emitter, and certificate_status["kernel_detail"] gives the reason (withheld_special_function, withheld_unsupported_node, …). A definite integral the kernel withholds falls back to the tactic interval-FTC emitter in the same way.

How often each path is taken

Measured in the default "auto" mode, indefinite integrals only, with wheels built from main before and after the special functions and roots were added to the kernel (the "before" numbers equal the published 3.15.0 wheel's). "Certified" counts the answers that came with a certificate; the Lean CI job compiles the integration corpus in both modes.

corpus integrands certified (before → after) kernel tactic
tests/lean_integrate_corpus.py 50 50 → 50 45 → 50 5 → 0
calculus suite, standard tier 51 44 → 47 41 → 47 3 → 0
calculus suite, Rubi hard tier 171 136 → 143 132 → 143 4 → 0
total 272 230 → 240 218 (95%) → 240 (100%) 12 → 0

Before, every tactic fallback was an erf/erfi/Si answer or a cube root. Those twelve now take the kernel path, and ten answers no checker certified before (Ei, li and a mixed x^(1/3)/√x answer, among them ∫ exp(eˣ) = Ei(eˣ)) are certified by the kernel. Every certificate in these corpora is now a kernel certificate. The calculus suites are the integral tiers of the CAS comparison benchmark (the standard tier, and the hard tier drawn from the Rubi test suite).

Python
import alkahest

x = alkahest.symbol("x")
r = alkahest.integrate(alkahest.parse("x*exp(x)"), x)
src = r.certificate                       # kernel certificate, else tactic, else None
assert r.certificate_status["path"] == "kernel"   # "kernel" | "kernel_native" | "tactic" | None
r.certificate_status["kernel_detail"]     # why the kernel path withheld, if it did

alkahest.set_lean_certificate_mode("tactic")      # tactic emitter only
assert r.certificate_status["path"] == "tactic"
alkahest.set_lean_certificate_mode("auto")        # back to the default

Certificates are built lazily, only when .certificate or .certificate_status is read. integrate itself does no extra work.

Checking a kernel certificate yourself

Kernel certificates import Alkahest.Kernel, so build the library once from a checkout of the repository:

Shell
cd lean
lake exe cache get        # Mathlib's prebuilt oleans
lake build Alkahest       # the kernel (about a minute)
lake env lean -DwarningAsError=true -DautoImplicit=false my_certificate.lean

A certificate that compiles with no errors is checked. Before trusting it, read its theorem statement, and check that the file contains no sorry, admit, axiom or native_decide (the last appears only in kernel_native mode).

Definite integrals

Alkahest.Kernel.DefInt adds checkDefInt P X F f A B w pts. Its soundness theorem is

Lean
theorem defint_sound (h : checkDefInt P X F f A B w pts = true) (ps : List ℝ)
    (hP : HoldsAll (0 :: ps) P) :
    ∫ x in A.eval (0 :: ps)..B.eval (0 :: ps), f.eval (x :: ps) =
      F.eval (B.eval (0 :: ps) :: ps) - F.eval (A.eval (0 :: ps) :: ps)

The checker accepts when

  1. checkIntegral (P ++ X) F f w accepts, so F' = f wherever the conditions P ++ X hold;
  2. the differentiability conditions of f itself follow from P ++ X, so f is continuous there and hence interval-integrable;
  3. the endpoints A, B and the conditions P do not mention x. P are hypotheses on the parameters and become binders of the theorem;
  4. every condition in X holds at every point between A and B. This is the interval decider. It computes rational enclosures of both endpoints, so π-multiples, √2 and the like work as well as rationals. The witness subdivision pts = [p₀, …, pₙ] must cover an interval containing both enclosures, and on each piece [pᵢ, pᵢ₊₁] every condition is decided by a rational interval enclosure of its expression (encl).

The enclosures use interval arithmetic for + − · /, exact even powers, and proved bounds for the elementary functions. exp uses (1 + t/n)ⁿ ≤ eᵗ ≤ (1 − t/n)⁻ⁿ and log uses 1 − 1/t ≤ log t ≤ t − 1, both with monotonicity; √ uses Newton steps (AM–GM) and π ∈ [3.141592, 3.141593]. sin and cos use Jordan's inequality on [0, π/2], the reflections sin (π − t) and cos (π − t), and 1 − t²/2 ≤ cos t around 0, π/2 and π; atan, asin, acos and tanh get their ranges. On intervals in [0, ∞), erf, erfc and erfi are bounded through their defining integrals and monotonicity (2l·e^{-l²}/√π ≤ erf t ≤ 2u/√π, with √π ∈ [1.7724, 1.7725]), and the rational-power atom t^(1/q) lies between min t 1 and max t 1. The other special functions (Si, Ci, Ei, li, Li₂, Fresnel, …) have no enclosure, so a condition that contains one is refused. All of it is ℚ arithmetic, which decide +kernel evaluates. When X is empty (no condition depends on x), nothing about the interval is needed, so symbolic endpoints work too: ∫₀ʸ cos x dx = sin y − sin 0.

Lean
theorem alkahest_definite_integral :
    ∫ x in ((1 : ℝ))..((2 : ℝ)), ((x : ℝ))⁻¹ = Real.log |(2 : ℝ)| - Real.log |(1 : ℝ)| :=
  defint_sound (P := [])
    (X := [(.ne (.var (nat_lit 0)))])
    …
    (pts := [(Int.ofNat (nat_lit 1), nat_lit 1), (Int.ofNat (nat_lit 2), nat_lit 1)])
    (by decide +kernel) [] trivial

The Rust side (alkahest-core/src/lean/kernel/defint.rs) mirrors encl exactly. It bisects the interval at short dyadic points until every condition is decided (up to 256 pieces), and it takes the antiderivative from integrate, but only when the certificate is requested. The statement is ∫ x in a..b, f = F b − F a with F written at the endpoints, the same form the tactic emitter proves.

What the kernel refuses, with the reason in certificate_status["kernel_detail"]:

  • an infinite endpoint: withheld_improper_integral;
  • a side condition that fails at a point of [a, b], such as a pole or a log or √ argument that reaches 0: withheld_interval_singularity. That includes integrable endpoint singularities such as ∫₀¹ √x, because F must be differentiable on the closed interval;
  • a condition that holds but that the enclosures cannot prove within the budget (sinh/cosh/arsinh or a special function other than erf/erfc/erfi inside a condition, erf of an argument that can be negative, cos x ≠ 0 outside [-π, π]): withheld_interval_undecided;
  • a condition that mixes x with a parameter, or a symbolic endpoint while some condition depends on x: withheld_interval_parametric.

The tactic emitter is tried next in each case. Improper integrals and integrands with interior singularities are not certified at all.

Coverage and cost

Each corpus was run in the default "auto" mode and in "tactic" mode, which is what every release before this one did for definite integrals. "Test suites" means every distinct definite integrate(f, x, a, b) call that returns a result in the 19 test files that exercise definite integrals, 240 integrals in all. Many of them have no possible certificate: improper integrals, special-function values, floating-point bounds and piecewise integrands.

corpus integrals tactic only auto: kernel auto: tactic
tests/lean_definite_corpus.py 51 12 49 0
definite integrals in the test suites 240 11 70 0
tests/lean_corpus.py (definite entries) 12 12 12 0

Every integral the tactic emitter certifies is now certified by the kernel. All kernel certificates compile, and #print axioms on samples lists only propext, Classical.choice and Quot.sound.

Check time, measured as with the indefinite certificates above (Lean's profiler, every category except import), on the integrals both paths certify:

kernel tactic
lean_definite_corpus.py, 12 shared: median 0.28 s 0.67 s
lean_definite_corpus.py, 12 shared: max 0.49 s 1.12 s
test suites, 11 shared: median 0.26 s 0.38 s

The kernel certificate is faster on every shared integral: worst-case ratio 0.84 on the corpus. On the test-suite set, two of the first files timed under machine load came out marginally slower, and three re-runs of each measured 0.26 s against 0.32–0.35 s for the tactic proof. Over the kernel certificates the median is 0.3 s. Subdivisions of up to 39 pieces cost a few seconds (∫ √(cot x) on [1/5, 3/2]: 6.3 s). The slowest certificate, 47 s, is spent in the antiderivative identity, not in the interval decider.

ODE solutions

alkahest.experimental.dsolve_certificate(equation, x, y, derivs, y_of_x) certifies that a solution returned by dsolve satisfies its equation. The certificate states the derivative chain S, S', … of the solution (each link a HasDerivAt, computed by the kernel's D) and that the equation with them substituted is identically zero, through ode_sound. Free constants C1, C2, … are universally quantified.

Python
import alkahest as ak
from alkahest import experimental as ex

x, y, yp, ypp = (ak.symbol(n) for n in ("x", "y", "yp", "ypp"))
eq = ak.parse("ypp + y")
sol = ex.dsolve(eq, x, y, [yp, ypp])[0]["y_of_x"]
out = ex.dsolve_certificate(eq, x, y, [yp, ypp], sol)
out["path"]                                 # "kernel"
"ode_sound" in out["certificate"]           # True

native=True closes it with native_decide instead. The Lean CI job compiles the ODE corpus tests/lean_ode_corpus.py.

PDE residuals (FEX solutions)

Alkahest.Kernel.Pde adds one more checker. checkPde u op n w takes an explicit function u of n coordinates and an operator op written over the variables 0 … n-1 (the coordinates), n (u), n+1 (Δu) and n+2+i (∂u/∂xᵢ). It builds the jet itself with the kernel's derivative D (Σᵢ D i (D i u) and D i u), substitutes it into op (AExpr.bind), and decides that the result is zero with checkEq. The differentiability conditions of u and of every first partial must follow from no hypotheses at all, so they hold on the whole of ℝⁿ and in particular along every coordinate line. pde_sound turns acceptance into a statement about Mathlib's deriv:

Lean
theorem pde_sound {u op : AExpr} {n : Nat} {w : Witness} (h : checkPde u op n w = true)
    (ρ : List ℝ) (hn : ρ.length = n) : op.eval (jetR u ρ n) = 0

where jetR u ρ n is ρ ++ u(ρ) :: Σᵢ deriv (deriv (y ↦ u(ρ[i ↦ y]))) ρᵢ :: [deriv (y ↦ u(ρ[i ↦ y])) ρᵢ, …]. A certificate states the theorem in ordinary notation about a definition fexU of the solution, for example (cubic Schrödinger, d = 2)

theorem fex_pde (x0 x1 : ℝ) :
    ((-((0 : ℝ) + deriv (deriv (fun (y : ℝ) => fexU y x1)) x0
         + deriv (deriv (fun (y : ℝ) => fexU x0 y)) x1)) + (fexU x0 x1) ^ 3 + V * fexU x0 x1) = 0

and proves it with pde_sound _ (by decide +kernel) [x0, x1] rfl. The statement matches the kernel's conclusion by definitional unfolding, so the reader never has to trust Alkahest's derivatives.

alkahest.fex.finalize emits these certificates for Poisson, the cubic Schrödinger equation, the eigenproblem and linear transport whenever the fitted closed form is exact and its interior PDE is proved, falling back to the HasDerivAt tactic proof for Poisson and transport. The exponential relations the NLS solutions need (exp(2a) = exp(a)²) are the kernel's expAdd family; a constant exp(−log 3 + a) is first written ⅓·exp(a) (the certificate's solution_form). The theorem covers the PDE residual at every point of ℝ^d; boundary conditions are not part of it.

Next steps

  • Derivatives and sums through the kernel; today they use the tactic emitters. Improper definite integrals (a limit at the endpoint) and integrable endpoint singularities for the definite-integral checker.
  • PDE certificates for verify_pde_solution through checkPde, and for symbolic d (FEX's Sum forms), which needs a kernel notion of an n-fold sum.
  • Polynomial-algebra witnesses (factorisation, Bézout cofactors, Gröbner membership) through checkEq, and SOS witnesses for domain conditions the structural sign checker cannot decide.
alkahest 3.15.1