DEV Community

Cover image for Clojure's core has 17 unreported bugs — I reproduced 5
frank chu
frank chu

Posted on

Clojure's core has 17 unreported bugs — I reproduced 5

Clojure's core has 17 unreported bugs — I reproduced 5

Lean 4 found 17 unreported bugs in Clojure 1.12.7, a language whose core data structures have been in production since 2007. I reproduced five of them on stock 1.12.7 and JDK 21 in under an hour — including one that hangs forever on exactly 65,505 elements, and not one fewer.

Where the 17 came from

On November 24, conao3 published "I checked Clojure's core with Lean and differential testing and found unreported bugs in HAMT and vector-of." The method is the interesting part, and it's worth stealing: model one small function in Lean 4 as bit-vector arithmetic, state a property against a naive wide-width specification, and let bv_decide hunt for a counterexample. When Lean finds one, turn the value into a Clojure input and reproduce it against the real code. For the big persistent structures, which Lean can't model, he ran differential testing against java.util — 3 million operations on the HAMT, vectors checked around every tree boundary (32, 1,056, 32,800, 1,048,608).

He searched Clojure's JIRA and ask.clojure.org for each finding and reports no prior report for any of the 17. I did not re-run that search; what I did was take his five showpiece reproductions and run them myself, verbatim, on Clojure 1.12.7 (released November 18) under OpenJDK 21.0.13.1, jars pulled from Maven Central. All five reproduced exactly as written.

Bug 1: one element past 65,504 and reduce never comes back

vector-of stores values in primitive arrays, and its seq's reduce advances in 32-element chunks. Line 79 of gvec.clj computes the next chunk start:

(recur result (bit-and 0xffe0 (+ aidx 32)))
Enter fullscreen mode Exit fullscreen mode

0xffe0 clears the low 5 bits to round down to a multiple of 32. It also clears bit 16 and everything above it. I verified the mask is in the shipped jar, not just the GitHub view:

$ unzip -p clojure-1.12.7.jar clojure/gvec.clj | grep -n "0xffe0"
79:           (recur result (bit-and 0xffe0 (+ aidx 32)))))
Enter fullscreen mode Exit fullscreen mode

The arithmetic is the whole bug. With 65,504 elements the last chunk starts at index 65,504, which is 0xFFE0. Add 32 and you get 65,536, 0x10000 — and 0x10000 & 0xffe0 is 0. So reduce goes back to the start and reads the vector again, forever. I checked the mask math in Python first:

(65504 + 32) & 0xffe0 = 0x0        # next chunk should be 65536
(0x40000000 + 32) & 0xffe0 = 0x20  # Lean's counterexample: expected 0x40000020
Enter fullscreen mode Exit fullscreen mode

Then the real thing:

(reduce + (drop 1 (into (vector-of :long) (range 65504))))
;; => 2145354256

(reduce + (drop 1 (into (vector-of :long) (range 65505))))
;; => killed by timeout after 15 s, exit 124 — never returned
Enter fullscreen mode Exit fullscreen mode

The 65,504 result cross-checks independently: the sum of 1 through 65,503 is 65,503 × 65,504 / 2 = 2,145,354,256. One more element and the same expression hangs. The mask has been there since the 2010 commit that added internal-reduce, which means this particular infinite loop has been waiting sixteen years for a vector with more than 65,504 elements and a drop in front of it. The fix the author proved in Lean is (bit-not 0x1f) as the mask.

Bug 2: a key you can see but can't look up

Clojure's hash map is a HAMT. Keys with identical 32-bit hashes share a HashCollisionNode, and dissoc on that node builds the replacement with the wrong hash: it passes the parameter hash — the hash of the key you asked to remove — instead of the node's own this.hash.

The trap needs a key that is = to the stored key but hashes differently. A vector is = to a Java ArrayList with the same elements, but the two hash differently (tracked as CLJ-1372). My run:

(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]
Enter fullscreen mode Exit fullscreen mode

Read that last line twice. The map prints b's entry right there, counts 2 entries, and (get m3 b) returns nil. After the dissoc, the node recorded 1,867,155,179 — the hash of [0 42] — so the next assoc decided a (hash 1,003) didn't collide and split the keys into separate branches. Lookups for b follow the 1,003 branch, find only a, and give up. The author notes disj on a hash-set has the same bug, the transient dissoc! path does not, and patching the line to this.hash makes the same example return :B. A map that prints a key it cannot find is the kind of bug that makes you distrust your own REPL.

Bug 3: the same call, two answers, depending on a type hint

Since Clojure 1.12 you can pass a Clojure function where a Java method takes a functional interface. When the compiler knows the type, the adapter follows CLJ-2864 and does not coerce the return value as Clojure truthy. Without a type hint the call goes through reflection, and Reflector.coerceAdapterReturn still applies RT.booleanCast. Same call, same arguments:

(let [l (java.util.ArrayList. [1 2 3])]
  (.removeIf l #{1 2}) (vec l))
;; => ClassCastException

(let [l (identity (java.util.ArrayList. [1 2 3]))]
  (.removeIf l #{1 2}) (vec l))
;; => [3]
Enter fullscreen mode Exit fullscreen mode

identity hides the type, so the second call reflects. A set used as a function returns the element itself; the typed adapter can't turn the Long into a Boolean and throws, while the reflective path reads it as truthy and removes the elements. Whether your code works depends on whether the compiler happened to know what your variable was. That is not a semantics, it's a mood.

Bug 4: drop a big number and the index goes negative

Clojure 1.12 added IDrop implementations that make drop faster. The ones for string seqs and vector seqs add the current position and n as ints and compare the sum with the length. Integer/MAX_VALUE + 1 wraps to -2,147,483,648:

(drop Integer/MAX_VALUE (seq "abc"))
;; => ()

(drop Integer/MAX_VALUE (next (seq "abc")))
;; => StringIndexOutOfBoundsException Index -2147483648 out of bounds for length 3
Enter fullscreen mode Exit fullscreen mode

The only difference is next: position 1 instead of 0 is enough to overflow the addition. Lean's counterexample was i = 2,147,483,646, n = 2,147,483,647; the fix compares n against the remaining length instead of adding first.

Bug 5: assoc at -1 rewrites the vector your subvec came from

assoc on a plain vector rejects a negative index. assoc on a subvec does not — it writes through to the underlying vector, outside the window:

(assoc [2 3] -1 :x)
;; => IndexOutOfBoundsException

(let [s (assoc (subvec [0 1 2 3 4] 2 4) -1 :x)]
  [s (.-v s)])
;; => [[2 3] [0 :x 2 3 4]]
Enter fullscreen mode Exit fullscreen mode

The subvec still prints [2 3], looking unchanged, while the vector it was cut from now reads [0 :x 2 3 4]. The same bug in nth was fixed years ago as CLJ-962; assoc still has it. Silent mutation of a supposedly persistent structure, through an index that should have thrown, is the worst of the five — the other four at least fail loudly or hang visibly.

The other 12, as reported (not reproduced by me)

The author reproduced all of these on 1.12.7; I list them as his findings, not mine:

Behavior Example
reduce-kv throws on vector-of (reduce-kv f [] (vector-of :long 5 6))
FI with 3+ args truncates an int return, silently (fn [a b c] 4294967297) returns 1; 2-arg version throws
next on a string/array/repeat seq keeps metadata (meta (rest (with-meta (seq "abc") {:m 1}))) is {:m 1}
(long ##NaN) and (int ##NaN) return 0 (byte ##NaN) throws instead
long clamps 2^63, int clamps 2^31, to max value (long (Math/pow 2 63)) is Long/MAX_VALUE
char wraps a BigInt at 2^64 (char 18446744073709551681N) is \A
float rejects ##Inf but lets ##NaN through (float ##Inf) throws; (float ##NaN) is ##NaN
Boxed vs primitive doubles differ on byte conversion (byte (identity 127.9)) is 127; (byte 127.9) throws
get truncates a fractional index (get "abc" 1.9) is \b
byte-array/short-array reject an initial value (byte-array 2 7) throws
.indexOf and .contains disagree on primitive-array seqs (.indexOf (seq (byte-array [1 2 3])) 2) is -1
.lastIndexOf on a list uses equals, not = (.lastIndexOf (list 1 2) (int 2)) is -1

What held up — and why that matters

The differential testing is the part I respect most, because it's where the author could have found something and didn't. PersistentHashMap and PersistentHashSet matched java.util.HashMap over 3 million operations mixing persistent and transient updates, including collision nodes down to depth 7. PersistentTreeMap matched TreeMap and kept its red-black invariants. Vectors matched ArrayList around every tree boundary. The HAMT itself showed no mismatch in 3 million operations; the bugs sat in the code around the trees, and in the seams where two mechanisms meet — = versus hashing, typed versus reflective calls, int versus long arithmetic.

That is the real lesson. Nobody needed Lean to tell them the HAMT works; sixteen years of production already did. What formal verification bought here is the seams: a bitmask that clears one bit too many, a this that became a parameter, a coercion that survived a cleanup in only one of two call paths. Each bug is one character or one word away from correct, each sat in released code for years, and each was found by stating the property the code was supposed to have and letting a machine check it for all inputs instead of the ones a test author thought of.

Caveats, stated plainly

I reproduced 5 of the 17 bugs, on stock Clojure 1.12.7 + JDK 21, with the author's exact inputs. The other 12 are listed above as the author's findings; I did not run them. My hang test proves the 65,505-element reduce doesn't return within 15 seconds, not that it never returns — the mask arithmetic is what makes "never" credible, and I showed that arithmetic. The Lean proofs are the author's; I verified the bit-vector claims they rest on (the 0xffe0 mask, the counterexamples) with my own runs, not by running Lean. And "unreported" is the author's search result (JIRA REST API + ask.clojure.org), not mine.

Sources

Top comments (0)