Verus 与 Lean 中面向证明的编程对比
Proof-oriented programming in Verus vs. Lean

原始链接: https://willcrichton.net/notes/verus-lean-bitset/

该文认为,验证的未来在于面向证明的编程:规范直接针对实现进行证明。它通过一个案例研究比较 Verus 和 Lean:实现一个行为类似抽象集合的已验证位集。在 Verus 中,Rust 风格的实现把定义域保留为一个字段,使用外在不变式(`wf`、requires/ensures、触发器、ghost 变量、广播引理),并依赖 SMT 自动化。Lean 则把定义域编码进类型,将良构性证明作为字段携带,并使用 `Fin` 和 `Finset` 等丰富抽象,使规范更内在、通常也更简洁。`empty` 和 `insert` 这类简单操作在两者中都很直接;子集和并集则暴露出差异。Verus 在规范语言与实现语言分离、迭代器抽象、循环不变式以及不透明的求解器错误方面存在困难,不过它支持地道的 Rust,并且近期即可采用。Lean 提供更富表达力、统一的语言以及更简单的规范,但命令式证明可能很复杂,其实现生态也较不成熟。AI 极大加速了证明生成,但人的判断力在规范与代码质量上仍然重要。作者最后认为,Verus 像是实用面向证明编程的近期未来,而 Lean 像是更远的未来。

围绕 Verus 与 Lean 的讨论,核心是由 SMT 支撑的自动验证与交互式/依赖类型证明工程之间的取舍。一位评论者将 SMT 视为应对证明人力稀缺的变通办法,认为交互式定理证明更“完备”;另一些人则反驳说,SMT 求解器是强大的工程工具,支撑着许多验证系统,尤其适用于算术不变量,而在这些场景中依赖类型可能更慢或更笨重。尽管 Lean 和 Verus 都与 Z3 的创建者有关联,但应澄清它们是不同的方法;Lean 并不是简单地构建在 Z3 之上。 还讨论了 LLM 辅助验证:模型往往过度依赖 SMT 或高成本的证明策略,但明确的约束——例如严格的类型检查时间限制——以及在小规模、可由人类审查的接口与更大规模、由机器维护的证明之间做出清晰划分,可以取得良好效果。有人建议程序员先学习基于求解器的验证,使用前置/后置条件、不变量和断言,并引用 Bradley 与 Manna 的《计算演算》。
相关文章

原文
Proof-Oriented Programming in Verus vs. Lean

A lot of people are now interested in software verification, both because AI is finding many bugs, and because AI is lowering the barrier to entry to formal methods. I believe the future of verification is proof-oriented programming, a term I take from F*. A core element of proof-oriented programming is that a system’s specification can be proven directly about its implementation. As of November 2026, there are two proof-oriented programming languages that seem poised to catch on: Verus and Lean. This post describes a small case study which illustrates the contrasts between the two approaches.

What kinds of software verification are not proof-oriented programming?

A common issue with verification tools is that they can verify a model of your system, but not the system itself. For example, one can model the correctness of a consensus protocol like Raft in TLA+, but TLA+ cannot check that a Rust implementation of Raft is written correctly. There are plenty of workarounds like differential testing, but hopefully the future does not consist solely of workarounds.

Specifically, we’re going to implement a verified bitset. A bitset is an efficient data structure for sets of numbers over a small fixed domain. For example, say we want a set which can contain the numbers 0 to 127. We can represent that set as two 64-bit integers. To insert the number 5, we set the 5th bit on the first integer to a 1. Operations like set union reduce to bit operations like bitwise-OR.

Bitsets are a nice case study because their implementation is small and self-contained, and their specification is straightforward: a bitset should behave like a “normal” or “abstract” set. Moreover, neither Verus nor Lean appears to have a bitset implementation, so it was a fun exercise for me! For context, I know a lot about Rust, a moderate amount about Lean, and very little about Verus. I apologize in advance for errors or unnecessarily complex proofs. All code in this post is publicly available at willcrichton/verified-bitset.

AI disclosure: The text of this post was written entirely by hand. I largely wrote the specifications by hand with light AI assistance. I used AI heavily to generate the proof terms.

A bitset is defined by a domain, or the maximum number of elements in the set. The bitset contains an array of fixed-size integers, for simplicity always 64-bit. This array needs ⌈domain / 64⌉ words. We’ll look at the Verus definition on the left, and the Lean definition on the right (or top / bottom on mobile).

div_ceil is exactly the function we want. The problem is that as of the time of writing, the Verus standard library does not provide a formal semantics for div_ceil. We could in theory provide one ourselves, but I don’t want to make this post more complicated than it already is!

The last difference is how we encode data structure invariants. Bitsets have two key invariants:

  1. The array should have enough words to hold the entire domain.
  2. The unused “padding” bits at the end of the last word should be zero. (This will be needed to prove our is_subset method correct.)
  1. the Verus guide).

In Verus, we can attach wf to Bitset in one of two ways. One option is to add requires self.wf() and ensures self.wf() on every method. The other option is to use a specific mechanism called #[type_invariant]. I tried this, but it seems to interact poorly with methods requiring longer-lived mutable borrows (such as union, which uses iter_mut over words), so I abandoned it in favor of the first approach.

The foundation of the bitset is checking whether it contains an element. Given a number n, we look it up by first getting its coordinates, or which word and which bit to check. Then we test whether that word contains that bit.

grind tactic can easily dispatch this proof. Note that the @[grind] annotation on coords makes the definition of coords transparent to the grind tactic, similar to the concept of an broadcast proof in Verus.

The two preconditions are already captured by the wf field on Bitset and the type of n as Fin d. Another notable detail is that in Lean, because s.words is indexed by a Fin (i.e., a proof that the index is in-bounds), indexing does not incur a bounds-check. In Rust, while Verus does ensure that the bounds-check never panics, Verus does not change the underlying Rust semantics. To actually eliminate the runtime bounds-check, you have to write (provably safe) unsafe code like this:

Finset, so we model the bitset as a Finset (Fin d), or a finite set of the numbers up to d. We construct this with Finset.univ (the set of all values in the type Fin d), and filter it to those numbers contained in s. Additionally, we provide a theorem which relates Bitset.contains to the membership operator on Finset and add it to the simp tactic (comparable to grind, but with different search strategies). This theorem is necessary to make the proofs of the remaining theorems which connect Bitset to Finset relatively compact.

Why do we need to write (s.contains ·) instead of just s.contains?

The eagle-eyed functional programmer may notice an unnecessary eta-expansion where (s.contains ·) is shorthand for fun x => s.contains x. We have to do this because Finset.filter expects a function which returns a Prop (a proposition, True or False, potentially undecidable), but contains returns a Bool (a boolean, true or false, decidable). The eta-expansion allows Lean to automatically convert from Bool to Prop on our behalf. It’s useful to observe this distinction because it doesn’t exist in Verus!

Verus provides a standard library of abstract collection types for which the SMT solver provides a theory. Thankfully this includes a set, so we model our bitset as a Set<nat>. Verus provides first-class support for the idea of “the abstract view on this concrete Rust object”, represented by the View trait. Hence, we implement View for Bitset with the view type being Set<nat>.

In Verus, we define the set as a filtered range. The range goes from 0 to domain, and then we filter for containment. Note that @ is a Verus shorthand for .view(). So self.words@ converts the Rust type Vec<u64> into the SMT/Verus type Seq<u64>.

One small but annoying thing here is the difference in integer types. Rust vectors are indexed by usize, while Verus sequences are indexed by the abstract SMT int type, hence we have to cast idx as int. A consequence of this annoyance is that the implementation of contains is largely duplicated here. Whereas in Lean we could directly use contains at the specification and implementation levels, we can’t do that in Verus. auto_spec does not work for contains due to the index type mismatch.

Our bitset theorems will need to reason about a bunch of bit operations. These lower-level lemmas are more general than the bitset library, so we can extract them as standalone statements which might exist in a separate module. Here’s one example:

bv_decide. Annoyingly in Verus, you have to fully restate the theorem when stuffing it into the solver. Both theorems are registered with solvers — Lean using simp, grind like before, and Verus using broadcast. The broadcast use declaration allows the bitset to explicitly import these proofs into the solver’s scope.

Now we can put all the pieces together to define a verified method which constructs an empty bitset.

Vector.modify documentation says that the underlying storage is modified in-place. The theorem that insert is correct is still short and sweet: the insert on a Bitset behaves like insert on a Finset.

One bizarre piece of Lean syntax is the (eq := _) annotation on the first let-binding. This annotation is needed because the wf proof is produced inside the definition of insert rather than outside. Specifically, let-bindings with pattern matching by default “forget” their provenance, so the grind tactic does not know that idx = (coords n).1. The (eq := _) annotation puts that fact into the function’s type context, enabling grind to succeed in proving well-formedness.

In Verus, we use an idiomatic &mut self reference. This requires us to show that the data structure is still valid after being changed, specifically we ensure final(self).wf() and also ensure that domain has not changed. This uses the old(..) and final(..) syntaxes to refer to a variable’s value at the beginning and end of the function. The theorem that insert is correct again looks like the one in Lean, but using @ instead of toFinset.

Thus far the proofs have been relatively trivial — one or two tactics in Lean, and fully automated in Verus. A more interesting example is computing whether one bitset is the subset of another, relying on the helper function word_subset(a, b) = a & !b == 0.

Vector.isEqv function which works similarly to .zip(..).all(..): it returns true iff the two inputs are equivalent under the given function, wordSubset. The correctness of isSubset is similarly defined as iff A is a bit-subset of B, then Finset of A is a subset of the Finset of B. The proof involves several tactics, including helper theorems from the Vector, Finset, and UInt64 modules.

Why these proofs? How did I know to define lemma_is_subset exactly as it is, or to use simp with its particular inputs? I did not know. I largely relied on AI assistance (specifically Claude Fable 5.2) to generate the proof terms and supporting lemmas. I’ll speak more to this in the reflection at the end.

Finally, we conclude with the most ambitious method: unioning one bitset into another. Specifically, union s t will add all the elements from t to s, and it will return true if s changed in the process. We will now consider each language in turn.

Union in Verus

In the Rust implementation, I picked a style I felt most idiomatic for non-Verus Rust: using iter_mut().zip to get mutable references to pairs of words, and then bitwise-OR-ing them in a for-loop. In both the Rust and Lean versions, it would likely simplify the proof to iterate over just an integer range, and then index in the loop body. But my goal is to write implementations that look beautiful, and then find the proofs that match.

Vector.mapFinIdx to map over each word along with its index, bitwise-ORing with t. The proof of well-formedness is straightforward. However, the Δ implementation is less efficient than in Rust, because (a) isSubset requires three bit operations per word rather than one, and (b) isSubset requires a second pass over the data with all its attendant cache issues.

This simple implementation has a correspondingly simple proof of correctness:

Std.DHashMap.Raw), and then an outer “nice” data structure which bundles the raw data with an invariant (e.g., Std.DHashMap).

I originally implemented unionImpWords with a subtle performance issue. If the for-loop iterates over both vectors like sw in s, tw in t, then both s' and the for-loop’s iterator hold a reference to the same input data, which causes a copy rather than in-place update when s'.set is called.

The proof of correctness for unionImpWords involves using Lean’s vcgen tactic for verifying imperative code:

guide to vcgen. Focus on the theorem statement which describes the high-level behavior of unionImpWords. First, the resulting words contain the bitwise-OR of the input words. Second, the Δ boolean reflects whether the second set of words is not a subset of the first set (duplicating the implementation of isSubset, which could be factored into a helper).

The unionImpWords_spec theorem is used in the unionImp well-formedness proof, and it also supports the corresponding toFinset_unionImp_words and toFinset_unionImp_Δ theorems which are very similar to those for unionFunc, so I do not reproduce them here.

Functional union, inductive

An intermediate approach is to write in a functional-inductive style. This loses some of the conciseness of the functional-library style, but it has equivalent efficiency to the imperative style while requiring a much smaller proof:

the result in both languages. I felt that I did not have to seriously sacrifice code style or performance to achieve correctness.

I did experience several “abstraction taxes” where trying to write a clean implementation led to an ugly or impossible proof.

  • Lean: I disliked how I have to sprinkle various let (eq := _) and if _ : ... annotations around to bring a proof term into the function body scope. In the union example, I had to forgo abstraction to achieve optimal performance.

  • Verus: The spec language being different from the implementation language introduces a lot of papercuts, like the limitations of #[auto_spec]. I also had to fight a bit to use the abstractions I wanted like .iter().zip(..).all(..), which required an additional lemma specifically to model the interaction of zip, all, and the postcondition. It wasn’t impossible, but the solver would have been happier if I wrote C-like Rust.

I found that my AI assistant would continually make lots of small choices that passed the verifier but reduced the code quality (often related to the abstraction tax). For example in Verus, the AI will happily inline definitions into lemmas (causing repeated code), and it will stuff a function full of proofs even when some of those facts ought to live as standalone statements. Taste still matters!

I came into this experience with a lot of skepticism about primarily SMT-based approaches to verification. I still have no idea how people are supposed to debug the spartan “postcondition not satisfied” errors that get emitted from Verus, versus interactively proving theorems in Lean and always having a clear statement of the current goal and its environment. But perhaps proof is a non-issue now due to AI. I certainly would have taken 10x longer to write both the Verus and Lean proofs if purely by hand.

At least, specifications will always matter because they need to be either written or reviewed by humans. Lean has an unambiguously better spec language than Verus, both for its consistency (same as implementation language) and for its breadth (full of rich primitives like Fin and Finset). Lean offers the ability to express both extrinsic and intrinsic forms of verification, while Verus seems largely targeted at extrinsic verification. Yet, Lean as an implementation language is still much more experimental compared to the battle-tested Rust language and compiler. My intuition is that Verus feels like the near future of proof-oriented programming, and Lean feels like the far future.

联系我们 contact @ memedata.com