I checked Clojure's core with Lean and found 17 unreported bugs

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

I read Koukyosyumei’s article “著名なRust製OSSをLean 4で形式検証してみたら、めちゃめちゃバグが見つかった話” (in Japanese; the title means “I formally verified well-known Rust OSS with Lean 4 and found a lot of bugs”). The author ported well-known Rust projects into a form they could prove in Lean 4, and where a proof failed, they found a bug in the original code. Many people have used Clojure’s persistent data structures since around 1.0, so I expected no bugs to remain. Still, I wanted to see whether Lean would find something there too.

我阅读了 Koukyosyumei 的文章《著名なRust製OSSをLean 4で形式検証してみたら、めちゃめちゃバグが見つかった話》(日文标题意为“我用 Lean 4 对著名的 Rust 开源项目进行了形式化验证,结果发现了一堆 Bug”)。作者将著名的 Rust 项目移植到 Lean 4 中进行证明,凡是证明失败的地方,都发现了原始代码中的 Bug。由于许多人从 1.0 版本左右就开始使用 Clojure 的持久化数据结构,我本以为不会再有 Bug 了,但我还是想看看 Lean 是否也能在那里发现一些问题。

hirosassa/lean-verify describes a procedure for modeling a small function in Lean 4 and checking it for all inputs, so I applied it to the part of Clojure’s core written in Java. I modeled integer and bit arithmetic in Lean and searched for counterexamples. I checked the collections with differential testing against the java.util collections, and for Java interop I compared the same call with and without a type hint. I found 17 bugs that I could not find in Clojure’s JIRA or on ask.clojure.org.

hirosassa/lean-verify 描述了一种在 Lean 4 中对小型函数进行建模并检查所有输入的方法,因此我将其应用于 Clojure 用 Java 编写的核心部分。我在 Lean 中对整数和位运算进行了建模,并搜索了反例。我通过与 java.util 集合进行差异测试来检查集合,并针对 Java 互操作性比较了带有和不带有类型提示的相同调用。我发现了 17 个在 Clojure 的 JIRA 或 ask.clojure.org 上找不到的 Bug。

They include reduce on vector-of, the hash collision node of the HAMT, and calls to functional interfaces without a type hint. The HAMT itself showed no mismatch in 3 million operations of differential testing, and the vector tree showed none around its boundaries. The bugs sat in separate code outside the trees, and in places where two mechanisms meet, such as = and hashing. I used Clojure 1.12.7, released on 2026-11-18, and JDK 21. The links to the source point to the clojure-1.12.7 tag.

这些 Bug 包括 vector-of 上的 reduce 操作、HAMT 的哈希冲突节点,以及没有类型提示的函数式接口调用。在 300 万次差异测试中,HAMT 本身没有显示出不匹配,向量树在其边界处也没有发现问题。这些 Bug 存在于树结构之外的独立代码中,以及两种机制交汇的地方,例如 = 和哈希计算。我使用了 2026 年 11 月 18 日发布的 Clojure 1.12.7 和 JDK 21。源代码链接指向 clojure-1.12.7 标签。

How I checked The lean-verify procedure picks one function and models it as a Lean definition. You write a property that compares it with a naive specification computed at a wider width, and bv_decide searches for a counterexample. If you model Java’s long and int as BitVec 64 and BitVec 32, the wraparound of addition and multiplication maps onto BitVec operations. So do the rounding of / toward zero and the sign of %. When Lean found a counterexample, I turned the value into a Clojure input and reproduced it in the original code. I then modeled the fixed code in Lean and proved the same property.

我是如何检查的:lean-verify 流程会选取一个函数并将其建模为 Lean 定义。你编写一个属性,将其与在更宽位宽下计算的朴素规范进行比较,然后 bv_decide 会搜索反例。如果你将 Java 的 long 和 int 建模为 BitVec 64 和 BitVec 32,加法和乘法的溢出就会映射到 BitVec 操作上。除法 / 向零取整以及取模 % 的符号也是如此。当 Lean 找到反例时,我将其转换为 Clojure 输入并在原始代码中重现。然后,我在 Lean 中对修复后的代码进行建模,并证明了相同的属性。

Lean can only take small functions that reduce to integer and bit arithmetic, so I checked the large persistent data structures with differential testing. Each test applies the same random sequence of operations to PersistentHashMap and to java.util.HashMap and compares the results. For the HAMT, the keys mix partial collisions at each 5-bit level with fully identical hashes, and I ran 1,500 operations for each of 2,000 seeds. For vectors, I compared against ArrayList around 32, 1056, 32800, and 1048608, where the tree gains a level. The operations were conj, pop, assoc, and their transient versions.

Lean 只能处理能简化为整数和位运算的小型函数,因此我通过差异测试检查了大型持久化数据结构。每个测试都对 PersistentHashMap 和 java.util.HashMap 应用相同的随机操作序列并比较结果。对于 HAMT,键在每个 5 位级别混合了部分冲突和完全相同的哈希值,我为 2,000 个种子中的每一个运行了 1,500 次操作。对于向量,我将其与 32、1056、32800 和 1048608 附近的 ArrayList 进行了比较,这些点是树增加层级的地方。操作包括 conj、pop、assoc 及其瞬态版本。

I checked whether anyone had reported each bug before. I searched Clojure’s JIRA through its REST API and ask.clojure.org through web search and the site’s own search, and found no matching report.

我检查了是否有人之前报告过每个 Bug。我通过 REST API 搜索了 Clojure 的 JIRA,并通过网络搜索和网站自带的搜索功能查询了 ask.clojure.org,没有发现匹配的报告。

reduce on vector-of never finishes vector-of is a vector that stores its values in primitive arrays. Clojure implements it in gvec.clj, written in Clojure and separate from PersistentVector. If you drop from one and then reduce it, the call never returns once the vector has 65505 or more elements. (reduce + (drop 1 (into (vector-of :long) (range 65504)))) ;; => 2145354256 (reduce + (drop 1 (into (vector-of :long) (range 65505)))) ;; => never returns (reduce + (drop 1 (vec (range 65505)))) ;; => 2145419760

vector-of 上的 reduce 永不结束:vector-of 是一种将值存储在原始数组中的向量。Clojure 在 gvec.clj 中实现了它,该文件是用 Clojure 编写的,与 PersistentVector 分开。如果你对它执行 drop 操作然后再进行 reduce,一旦向量拥有 65505 个或更多元素,该调用就永远不会返回。(reduce + (drop 1 (into (vector-of :long) (range 65504)))) ;; => 2145354256 (reduce + (drop 1 (into (vector-of :long) (range 65505)))) ;; => 永不返回 (reduce + (drop 1 (vec (range 65505)))) ;; => 2145419760

The cause is line 79 of gvec.clj, where the seq’s reduce computes the start of the next 32-element chunk. (recur result (bit-and 0xffe0 (+ aidx 32))) The code uses 0xffe0 to clear the low 5 bits and round down to a multiple of 32, but the mask also clears bit 16 and everything above it. With 65505 elements, the last chunk starts at index 65504. After that chunk, the start of the next one should be 65536, but the mask turns it into 0, so reduce goes back to the start and reads the vector again and again. The 0xffe0 mask has stayed in place since the 2010 commit that added internal-reduce.

原因是 gvec.clj 的第 79 行,seq 的 reduce 在此处计算下一个 32 元素块的起始位置。(recur result (bit-and 0xffe0 (+ aidx 32))) 代码使用 0xffe0 清除低 5 位并向下舍入到 32 的倍数,但该掩码同时也清除了第 16 位及其以上的所有位。对于 65505 个元素,最后一个块从索引 65504 开始。在该块之后,下一个块的起始位置应该是 65536,但掩码将其变成了 0,因此 reduce 回到开头并反复读取向量。自 2010 年添加 internal-reduce 的提交以来,0xffe0 掩码一直保持不变。

In Lean, I wrote the property that from a position a that is a multiple of 32, the next chunk starts at a + 32. import Std.Tactic.BVDecide def stepImpl (a : BitVec 64) : BitVec 64 := 0xffe0 &&& (a + 32) def stepFix (a : BitVec 64) : BitVec 64 := (~~~0x1f) &&& (a + 32) theorem impl_ok (a : BitVec 64) (h32 : a &&& 0x1f = 0) (hlt : a < 0x7fffffe0) : stepImpl a = a + 32 := by unfold stepImpl; bv_decide theorem fix_ok (a : BitVec 64) (h32 : a &&& 0x1f = 0) (hlt : a < 0x7fffffe0) : stepFix a = a + 32 := by unfold stepFix; bv_decide impl_ok fails with the counterexample a = 1073741792, and #eval stepImpl 65504 returns 0 as well. fix_ok uses (bit-not 0x1f) as the mask, and its proof goes through under the assumption that a is a multiple of 32 below 0x7fffffe0.

在 Lean 中,我编写了一个属性:从 32 的倍数位置 a 开始,下一个块从 a + 32 开始。import Std.Tactic.BVDecide def stepImpl (a : BitVec 64) : BitVec 64 := 0xffe0 &&& (a + 32) def stepFix (a : BitVec 64) : BitVec 64 := (~~~0x1f) &&& (a + 32) theorem impl_ok (a : BitVec 64) (h32 : a &&& 0x1f = 0) (hlt : a < 0x7fffffe0) : stepImpl a = a + 32 := by unfold stepImpl; bv_decide theorem fix_ok (a : BitVec 64) (h32 : a &&& 0x1f = 0) (hlt : a < 0x7fffffe0) : stepFix a = a + 32 := by unfold stepFix; bv_decide impl_ok 在反例 a = 1073741792 时失败,并且 #eval stepImpl 65504 也返回 0。fix_ok 使用 (bit-not 0x1f) 作为掩码,在假设 a 是小于 0x7fffffe0 的 32 的倍数的情况下,其证明是成立的。

dissoc on a HAMT collision node hides another key Clojure’s hash-map is a HAMT: it splits the key’s hash into 5-bit pieces and uses them to walk down the tree. Keys whose 32-bit hashes are identical share a HashCollisionNode at the bottom of the tree, and the node finds a key among them with =. HashCollisionNode.without builds the new node with one key removed. It should give the new node its own hash, this.hash, but it passes the parameter hash instead. return new HashCollisionNode(null, hash, count - 1, removePair(array, idx/2)); The parameter hash is the hash of the key you pass to dissoc. If you dissoc with a key that is = to the stored key but has a different hash, the node records the wrong hash.

HAMT 冲突节点上的 dissoc 会隐藏另一个键:Clojure 的 hash-map 是一个 HAMT:它将键的哈希值拆分为 5 位片段,并使用它们向下遍历树。32 位哈希值相同的键在树的底部共享一个 HashCollisionNode,该节点通过 = 在它们之间查找键。HashCollisionNode.without 在移除一个键后构建新节点。它应该给新节点赋予它自己的哈希值 this.hash,但它却传递了参数 hash。return new HashCollisionNode(null, hash, count - 1, removePair(array, idx/2)); 参数 hash 是你传递给 dissoc 的键的哈希值。如果你使用一个与存储的键相等但哈希值不同的键进行 dissoc,该节点就会记录错误的哈希值。

In Clojure, a vector is = to a Java ArrayList with the same elements, but the two hash differently. CLJ-1372 tracks this mismatch. In the example below, I chose a and b so that both ArrayList keys hash to 1003. (def a (java.util.ArrayList. [0 42])) (def b (java.util.ArrayList. [1 11])) [(hash a) (hash b) (hash [0 42]) (= a [0 42])] ;; => [1003 1003 1867155179 true] (def m3 (-> (hash-map a :A b :B) (dissoc [0 42]) (assoc a :A2))) [m3 (count m3) (get m3 b)] ;; => [{[1 11] :B, [0 42] :A2} 2 nil]

在 Clojure 中,向量与具有相同元素的 Java ArrayList 相等,但两者的哈希方式不同。CLJ-1372 跟踪了这种不匹配。在下面的示例中,我选择了 a 和 b,使得两个 ArrayList 键的哈希值都为 1003。(def a (java.util.ArrayList. [0 42])) (def b (java.util.ArrayList. [1 11])) [(hash a) (hash b) (hash [0 42]) (= a [0 42])] ;; => [1003 1003 1867155179 true] (def m3 (-> (hash-map a :A b :B) (dissoc [0 42]) (assoc a :A2))) [m3 (count m3) (get m3 b)] ;; => [{[1 11] :B, [0 42] :A2} 2 nil]