Leanpub Header

Skip to main content

Lean 4, Rust and Agents

The Spec Layer: Lean 4 for Rust Developers

Lean 4, Rust and Agents

It is Tuesday, 9:40. An agent has opened a pull request against your storage engine: forty files, four thousand lines of Rust. CI is green. Clippy is quiet. The borrow checker is satisfied. You have standup at 10:00.

You can read it all, skim it, or approve it. Most teams skim and call it review.

The Spec Layer teaches a fourth option: write a small spec in Lean 4, let the agent write the big untrusted Rust, and let checkers decide what to believe.

100-word teaser

Agents moved the bottleneck from writing code to deciding whether to trust it. Reading is linear in code size, and code size is now cheap, so review cannot keep up.

The Spec Layer: Lean 4 for Rust Developers splits the work. Humans own a small, machine-checkable spec in Lean. Agents write the large, untrusted Rust. Differential tests, certificates and proofs check one against the other.

You learn Lean through a running graph store, next to the Rust you already know. Every chapter ends with a trust ledger: what is checked, what is trusted, what is only hope. Lean itself is on the list.

Minimum price

$40.00

$60.00

You pay

Author earns

$

Also available for 2 book credits with a Reader Membership

PDF
EPUB
About

About

About the Book

Don't read the diff. Check it.

An agent opens a pull request against your storage engine: forty files, four thousand lines of Rust. CI is green, Clippy is quiet, the borrow checker is satisfied, and you have standup in twenty minutes. You can read it all, skim it, or approve it. Most teams skim and call it review.

Agents moved the bottleneck from writing code to deciding whether to trust it. Reading is linear in code size, and code size is now nearly free. "The tests pass" was always a weak claim. It is weaker when the same agent wrote the code and the tests, from the same misunderstanding.

The Spec Layer gives Rust developers a fourth option. Split the work three ways:

  • Spec. A small Lean 4 model of what the code must do. Humans own it; agents can read it, not edit it.
  • Implementation. Rust. Large, agent-written, untrusted.
  • Checkers. Differential tests, certificates and proofs that decide whether to believe the implementation.

Then review the one thing a machine can't: whether the spec says what you meant.

Two jobs in every chapter

  1. You learn Lean 4, just in time, next to the Rust you already know: structs and enums, traits as type classes, ? as do, Prop versus Bool, tactics, induction.
  2. You gain one way to check code you did not write. Each chapter opens with a box naming both.

Everything happens on one running project, a small graph store. A human writes its spec in Lean. An agent writes its fast engine in Rust and makes realistic mistakes. You watch the same planted bugs meet unit tests, differential testing, certificates and proofs, and learn which technique catches which.

The whole loop, before chapter 2

A ten-minute interlude runs the loop once, end to end, on the book's headline bug: an agent's "tidy" sort that passes every one of its own tests and silently drops duplicates. A gate that compares it with a Lean model fails and shrinks the bug to [4, 4], and a one-line fix turns the PR into one that carries evidence instead of asking for faith. Every command and output in it is real.

What you will be able to do

  • Read Lean specs fluently and write small ones a reviewer can read in one sitting.
  • Run an agent loop gated by checkers, where the agent cannot edit the yardstick.
  • Connect Rust and Lean through a process boundary, FFI, certificates and differential tests.
  • Prove properties of real Rust through an Aeneas-style translation, and keep the proof tied to the Rust you actually ship.
  • Accept proofs from agents as untrusted provers, safely.
  • Open pull requests that carry evidence, and spend review time only where the evidence stops.
  • Say exactly what each guarantee covers and what it assumes.

Honest accounting, including Lean

Every chapter ends with a trust ledger: what is checked, what is trusted, and what is only hope. Lean is on the list. Its kernel has had soundness bugs, checkers can verify the wrong statement, and one line of Lean can redefine what + means.

So the book attacks its own pipeline. Chapter 14's threat model is a test suite: weakened theorems, edited specs, hostile instances, hidden axioms, tampered gate scripts, a substituted checker binary. Each attack is run against the gates. Two defences exist only because the tests failed the first time.

Appendix L measures what verification cost. Six planted defects, three workflows on the same code: conventional tests caught 1, executable specs caught 5, the proof-carrying gates caught 6. It also gives the price, from 68 lines of test code for the first workflow to 894 for the last, and says plainly what one run on one machine cannot show.

What is inside

Prologue. The Review Wall

Part I. Thinking in Lean, through the spec (Ch 1–4, plus the Interlude) Why Lean, for Rust people. The whole loop in ten minutes. Data, behaviour and errors. Effects, mutation and the executable model. Facts, then proofs.

Part II. Lean as the spec layer (Ch 5–8) Specs are the new source code. Writing specs in Lean. The spec-driven agent loop. Proof-carrying pull requests.

Part III. Wiring Rust to the spec (Ch 9–11) Rust and Lean together. Untrusted oracle, trusted checker. Reference models and differential testing.

Part IV. Lean over Rust (Ch 12–13) Proving Rust: one Aeneas-style proof, and the alternatives (Kani, Verus). Agents as provers.

Part V. Honest accounting and the road ahead (Ch 14–16) Who checks the checker. Closing the loop. The future of agentic coding is verifiable.

Appendices. Rosetta reference, error decoder, trust ledger template, nineteen worked samples, a reading guide to Cedar and SymCrypt, checklists, tooling, further reading, answers to every exercise, and the cost experiment.

Two ways through

  • The Lean path, if you mainly want to learn Lean through Rust: Chapters 1–4, then 6, then 9–12.
  • The agent path, if your review queue is on fire: the Prologue, then Chapters 1, 5, 7, 8, 10, 13 and 14.

Both paths meet at Chapter 1, where you prove your first property, and Chapter 10, where Rust does the work and Lean checks the answer.

Companion code

All code is public under the MIT licence, so you can check it before you buy:

What has been checked

The book prints a status for every listing and gate, generated from one file, so the claims cannot drift from the code.

  • The Lean listings for Chapters 1–6, 9, 10 and 12 and the exercise answers compile in CI, with no sorry and only Lean's standard axioms.
  • The Rust and the gates were run, and every gate was also fed a deliberately broken variant to show it rejects it.
  • The ring-buffer and midpoint proofs are checked against real Charon/Aeneas output and replayed in a fresh process.
  • Marked where they appear: Chapter 11's Plausible listings were run by the author and are not in a repository yet, Chapter 13's agent-prover session is a scenario, and the newest CI jobs are configured but have not yet run on GitHub.

You need working Rust. You do not need any Lean or proof background.

About the author

Volodymyr Pavlyshyn has spent more than twenty years building software, from COBOL to self-sovereign identity, and now works on AI agents, knowledge graphs and agent memory. He is the author of Metagraph for AI Agents.

Author

About the Author

Volodymyr Pavlyshyn

Hey I am Volodymyr 

Seasoned Developer's Journey from COBOL to Web 3.0, SSI, Privacy First Edge AI, and Beyond

 As a seasoned developer with over 20 years of experience, I have worked with various programming languages, including some that are considered "dead," such as COBOL and Smalltalk. However, my passion for innovation and embracing cutting-edge technology has led me to focus on the emerging fields of Web 5.0, Self-Sovereign Identity (SSI),AI Agents, Knowledge Graphs, Agentiic memory systems, and the architecture of a decentralized world that empowers data democratization.

A firm believer in the potential of agent systems and the concept of a "soft" internet, I am dedicated to exploring and promoting these transformative ideas. In addition to writing, I also enjoy sharing my knowledge and insights through videoblogging. Most of my Medium posts serve as supplementary content to the videos on my YouTube channel, which you can explore here: https://www.youtube.com/c/VolodymyrPavlyshyn. 

Join me on this exciting journey as we delve into the future of technology and the possibilities it holds.

Contents

Table of Contents

  • About this edition
  • Prologue: The Review Wall
    • The inversion
    • Two tempting answers
    • A third answer
    • But who checks the checker?
    • How to read this book
    • Companion code
  • Part I — Thinking in Lean, through the spec
    • 1. Why Lean, for Rust People
      • Two tools in one
      • Install Lean in two commands
      • The five-minute payoff
      • What Lean did not check
      • A preview: proving the Rust itself
    • Interlude: The Whole Loop in Ten Minutes
      • 1. The spec a human approved
      • 2. The agent's implementation
      • 3. The tests pass
      • 4. The gate fails
      • 5. The minimal counterexample
      • 6. The corrected implementation
      • 7. The new evidence
      • 8. What is still trusted
    • 2. Rosetta I — Data, Behaviour and Errors
      • Structs are structures
      • Methods live in namespaces
      • Enums are inductive types
      • Traits are type classes
      • Errors: Except, do and the ? operator
      • List and Array
      • Modules, namespaces and visibility
    • 3. Rosetta II — Effects, Mutation and the Executable Model
      • Purity, and where effects go
      • Mutation without mutation
      • In-place updates: Lean's answer to &mut
      • The model
      • partial: allowed in the shell, never in the spec
      • StateM in one paragraph
    • 4. Facts, Then Proofs
      • Bool is a value; Prop is a claim
      • Reading logic like a Rust signature
      • Types that carry facts
      • Read the statement before the proof
      • Goals and tactics
      • First induction: a filter never grows (Lean path)
      • Worked proof: the reference model is correct (Lean path)
      • Fake proofs, and how to see them
      • Termination in one paragraph
      • A proof is a durable record
  • Part II — Lean as the spec layer
    • 5. Specs Are the New Source Code
      • Spec-driven development, and its missing verdict
      • The spec rigor ladder
      • Ten kinds of evidence, not one
      • What a reviewable spec looks like
      • How specs fail quietly
      • The redefined-operator trap
      • Mutation-testing the spec
      • What specs cannot say
      • Spec smells
      • When a Lean spec pays for itself
    • 6. Writing Specs in Lean, for Rust People
      • Pattern 1: invariants that travel with the data
      • Pattern 2: laws as classes with proofs
      • Pattern 3: refinement
      • Pattern 4: the range scan, completely
      • Slicing a real component
      • Laying out the repository
      • Agents as spec drafters
    • 7. The Spec-Driven Agent Loop
      • From request to contract
      • The architecture
      • The gate ladder
      • G1 in practice
      • Demo: G2 catches the tidy sort
      • The generator is part of the spec
      • Designing the feedback
      • Telling the agent the rules
      • How agents cheat, and which gate notices
      • When the spec is wrong
      • Budgets and stopping
      • What this loop does not give you
    • 8. Proof-Carrying Pull Requests
      • What a pull request carries
      • Classify every change
      • Golden statements
      • The spec's surface is larger than its definitions
      • The ten-minute review
      • Roles
      • Spec versions and spec debt
  • Part III — Wiring Rust to the spec
    • 9. Rust and Lean Together
      • Option 1: the process boundary
      • Option 2: the foreign function interface
      • The purity contract
      • Panics must not cross
      • Every @[extern] is a hole in the proof story
      • Which one to use
    • 10. Untrusted Oracle, Trusted Checker
      • Checking is cheaper than computing
      • The weak checker
      • The checker is the spec, made decidable
      • Making the checker fast without trusting it
      • Wiring the checker into the gate
      • A real certificate: the range scan
      • Exact for the index is not exact for the store
      • Certificates and the generator blind spot
      • Where checkers go wrong
    • 11. Reference Models and Differential Testing
      • Why a second implementation works
      • The harness
      • What it found
      • Generators are spec
      • Property testing inside Lean
      • native_decide and what it costs
      • Precedent: Cedar
      • The old code as an oracle
      • When to stop testing and start proving
      • The project at the end of Part III
  • Part IV — Lean over Rust
    • 12. Proving Rust — One Aeneas-Style Proof, and the Alternatives
      • Two ways to prove Rust
      • The pipeline
      • A warm-up: Chapter 1's midpoint, on real usize
      • The Rust
      • What the translation looks like
      • The spec
      • The assumption the tests never saw
      • The proof
      • The same property in Kani
      • Keeping the proof about the Rust you ship
      • Limits and cost
    • 13. Agents as Provers
      • Why this works at all
      • The division of labor
      • Metaprograms run code at build time
      • Replay: check the result, not the build
      • The hygiene checklist
      • Where agents help, and where they do not
      • Telling the prover the rules
  • Part V — Honest accounting and the road ahead
    • 14. Who Checks the Checker?
      • What a Lean proof actually trusts
      • The kernel had bugs
      • The statement trap, again
      • Independent checkers
      • Trusting Rust
      • Trusting the rest of the pipeline
      • The threat model, tested
      • Trusting trust, again
      • The layered answer
      • The trust ledger template
    • 15. Closing the Loop
      • The running project, end to end
      • Which gate caught which bug
      • What it cost
      • Adoption path for Monday
      • Recap: the Lean you learned
      • Your turn: the loop on your own code
    • 16. The Future of Agentic Coding Is Verifiable
      • The argument so far
      • The bottleneck moves again
      • Three scenarios
      • What changes for people
      • What does not change
      • Back to Tuesday
  • Appendices
    • A. Rosetta Reference
    • B. Error Decoder
    • C. Trust Ledger Template and Matrix
      • Template
      • Matrix: what each pattern in this book proves, trusts and leaves open
    • D. Worked Samples
      • D.1 The agent's "tidy" sort (Rust)
      • D.2 Reference model, spec, golden statements and model entry point (Lean)
      • D.3 G2 differential gate (Python)
      • D.4 G1 spec-integrity gate (shell)
      • D.5 AGENTS.md
      • D.6 Range-scan certificate (Rust)
      • D.7 Differential harness (Rust, proptest)
      • D.8 Stand-in model (Python)
      • D.9 FFI: Rust side and C caller
      • D.10 Ring buffer (Rust)
      • D.11 PR summary template
      • D.12 Axiom allowlist (Python)
      • D.13 make gates
      • D.14 Language lint for agent-owned Lean (Python)
      • D.15 G5 replay gate (shell)
      • D.16 G3 sort-certificate gate (Lean and shell)
      • D.17 Lean calling Rust in one binary (Lean, C, Lake)
      • D.18 The environment audit (Lean)
      • D.19 G4: is the proof about the Rust we ship? (shell)
    • G. Reading Guide — Cedar and SymCrypt
      • AWS Cedar
      • Microsoft SymCrypt
      • What to look for in both
    • H. Checklists
      • Spec review (Chapter 6)
      • Agent-proof acceptance (Chapter 13)
      • Pull-request review (Chapter 8)
    • I. Tooling and Setup
      • The repositories
      • Versions to pin
      • Editor
      • Sandbox for untrusted Lean
      • CI outline
      • Building this book
    • J. Further Reading
      • Lean
      • Rust verification
      • Rust safety
      • Specs, agents and trust
    • K. Answers to the Exercises
    • L. What Verification Cost on the Running Project
      • The setup
      • What each workflow caught
      • What it cost to run
      • What it cost to write
      • What it cost to keep up
      • What this experiment does not show
      • Where it pays, and where it does not
  • Lean Coverage Map

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub