Clojure has no standard. What a program means is whatever the JVM implementation does, and ClojureScript, babashka and nbb follow it as closely as their platforms allow. We measured how closely, by running the same 4,023 programs on five implementations. Then we wrote down what core Clojure code does as one definition in Lean’s logic, so that the same definition can be run as an interpreter, compared against every implementation, and used to prove facts about Clojure functions. This is part of Simmis, which uses models and simulation for inference: the simulation tools are themselves Clojure programs, and a model of Clojure lets us reason about them. This article explains why we built it that way, what it can do today, and what it cannot do yet.

The same code, two answers

Here is a small piece of code that counts how often a mapped function runs when you take the first element:

What is this syntax?
let [calls atom(0)]:
  first(map(fn [x]:
    swap!(calls, inc)
    x
  end, [1 2 3 4 5]))
  @calls
end
(let [calls (atom 0)]
  (first (map (fn [x] (swap! calls inc) x) [1 2 3 4 5]))
  @calls)

On the JVM it returns 5. In ClojureScript it returns 1. Lazy sequences over vectors are realized in chunks, and a vector of five elements is one chunk on the JVM but not chunked at all in ClojureScript, which only chunks vectors longer than 32 elements. Code that relies on side effects inside map therefore behaves differently in a .cljc file depending on where it runs.

Nobody wrote this down as a rule. It follows from how two data structures are implemented, and you find it by running the code on both platforms. We wanted to know how many such cases there are, and we wanted a precise answer for any piece of code, not only for the cases someone happened to try.

Measure before modelling

We started without any theory. A harness runs each of 4,023 small programs on five implementations, twice each, and records what each returns, throws, or refuses to compile. About a thousand programs are written by hand to probe one behaviour each, such as an edge case of nth, the order of a map’s keys, or what try catches. The rest are generated from tables of clojure.core functions and argument shapes.

ImplementationVersion
Clojure on the JVM1.12.0 and 1.13.0-alpha11
babashka1.12.200
ClojureScript on Node.js1.12.145
nbb1.6.215

3,374 programs (84 %) give the same answer on all five. The disagreements fall into two clusters. Clojure 1.12, Clojure 1.13 and babashka agree on 97 to 99 % of the programs: babashka interprets Clojure with SCI, but it runs Clojure’s own library, so the same function behaves the same. ClojureScript and nbb agree on 97 %. Between the two clusters, only about 86 % of programs give the same answer.

The most common kind of difference is a function that returns on one platform and throws on the other (216 programs):

What is this syntax?
realized?(repeat(1)) ; JVM: throws, Repeat is not IPending    ClojureScript: false
reduce(max, []) ; JVM: throws, wrong number of arguments  ClojureScript: nil
list?(cons(1, '(2))) ; JVM: false                              ClojureScript: true
(realized? (repeat 1))   ; JVM: throws, Repeat is not IPending    ClojureScript: false
(reduce max [])          ; JVM: throws, wrong number of arguments  ClojureScript: nil
(list? (cons 1 '(2)))    ; JVM: false                              ClojureScript: true

The programs were written to find differences, so they concentrate on edge cases. Everyday code agrees more often than 84 % suggests. By topic, numbers are the least portable (20 % of number programs agree everywhere, since JavaScript has one number type), and laziness is among the most consistent (about 90 %). The full report is generated from the results, and the quirks register lists each difference with the programs that show it.

A model that never guesses

A list of differences tells us what happened on the programs we ran. To ask the same questions about our own code, we wrote CljCore. It uses one evaluator with five host profiles: Clojure 1.12, Clojure 1.13, babashka, ClojureScript and nbb. The profiles supply differences such as numeric behaviour, sequence chunking and when a call throws.

CoverageExamples
Core evaluationFunctions, let, loop/recur, try, vars, dynamic bindings and atoms.
Collections and library functionsPersistent lists, vectors, maps and sets, lazy sequences with host-specific chunking, and functions such as map, reduce and nth. Much of the library code is ported from Clojure’s source.
GapsGeneral metadata behaviour, sorted collections, printing and transducers.
Outside the modelJava and JavaScript interop, records, protocols and reader behaviour.

The central design rule is that CljCore never gives a wrong answer. When it cannot be sure, it answers “no claim” and names the reason:

What is this syntax?
cc/on-all-hosts('realized?(repeat(1)))
;; => {:jvm112 {:throws {:error :type, …}}, :jvm113 {:throws …}, :bb {:throws …},
;;     :js {:returns false}, :nbb {:returns false}}

cc/run('seq(#{1 3 2}))
;; => {:no-claim :hash/order,
;;     :why "the result depends on the order of a hash set or map, which the hosts leave unspecified", …}
(cc/on-all-hosts '(realized? (repeat 1)))
;; => {:jvm112 {:throws {:error :type, …}}, :jvm113 {:throws …}, :bb {:throws …},
;;     :js {:returns false}, :nbb {:returns false}}

(cc/run '(seq #{1 3 2}))
;; => {:no-claim :hash/order,
;;     :why "the result depends on the order of a hash set or map, which the hosts leave unspecified", …}

Some reasons are permanent, because the implementations leave the behaviour open: the order in which a hash set iterates and the number hash returns are not part of the language. Others mark gaps, such as metadata and sorted collections. Forms outside the described part of Clojure, such as Java or JavaScript interop, records and reader tricks, are reported as outside.

That gives the test harness two things to track. How often does CljCore give an answer, and when it does, does the host agree? On every change, the build runs the same corpus through each host profile. A single disagreement on a claimed result fails the build. In the current suite, CljCore answers about 85 % of the programs on the JVM implementations and 75 % on the JavaScript ones. Every answer it gives agrees with the host.

Why the model is written in Lean’s logic

Those tests tell us where the model agrees with the hosts on concrete programs. To reason about a function across all its inputs, though, we need a definition we can make a theorem about. A language semantics usually takes one of two forms. An interpreter can be run and tested, but it is code, and stating a property of it means writing more code. Rules on paper, like the denotational semantics in Scheme’s R5RS report, can be reasoned about, but nothing checks that they describe what the implementations do. Executable formal semantics close that gap. The K framework semantics of C and JavaScript are run against large test suites, for JavaScript the official conformance tests, JSCert did the same for JavaScript in the Coq proof assistant, and CakeML proved a whole compiler correct against a semantics written as an evaluator.

CljCore follows that line, in Lean’s logic. A definition in Lean’s type theory is at the same time a program and a mathematical object. Run it, and it is an interpreter for Clojure that compares itself against the real implementations. State a theorem about it, and Lean’s tactics, its kernel and its libraries apply, including Mathlib, which together with Lean’s own library holds about 740,000 checked definitions and theorems.

Ansatz is what puts this inside Clojure. It is a Lean-compatible proof kernel and elaborator written in Java and Clojure, the same library behind Lean on the JVM. CljCore is written from a Clojure REPL, checked by that kernel when it loads, and run from the same REPL. Clojure code is the subject of the model, and Clojure is also the language in which the model is written, checked and queried.

Writing the model this way changes how unspecified behaviour is handled. Hash order is a parameter of the definition, an oracle that the interpreter asks whenever an implementation would pick an order. The harness uses it to simulate: when an implementation’s answer depends on order, it searches the orders the oracle allows for one that produces that answer. A proof can do the same thing symbolically and quantify over every oracle, which covers every order any implementation may choose, including implementations that do not exist yet.

Proving a property of a plain Clojure function

Take a function that clamps an integer between two bounds. We could test values below, inside and above the range. With CljCore’s definition of evaluation, we can ask Lean to check that a typed version agrees with the original on every input covered by the theorem. Here is how that works in Ansatz’s worked example:

What is this syntax?
a/foreign(^:model clamp,
  [x :- Int lo :- Int hi :- Int], Int,
  fn [x lo hi]:
    cond:
      x < lo => lo
      x > hi => hi
      :else => x
    end
  end)

assert(:conforming = :status(check/check-model!('clamp, :runs, 40)))

a/conforms(clamp) ; proved: the model always returns an Int

a/defn clamp-dsl [x :- Int lo :- Int hi :- Int] Int:
  if x < lo:
    lo
  else:
    if x > hi:
      hi
    else:
      x
    end
  end
end
a/port(clamp, clamp-dsl) ; proved: clamp = clamp-dsl on every input

a/theorem clamp-in-range [x :- Int lo :- Int hi :- Int h :- lo <= hi] And(lo <= clamp(x, lo, hi), clamp(x, lo, hi) <= hi):
  rw([clamp.ported])
  unfold(clamp-dsl)
  grind()
end
(a/foreign ^:model clamp [x :- Int, lo :- Int, hi :- Int] Int
  (fn [x lo hi] (cond (< x lo) lo (> x hi) hi :else x)))

(assert (= :conforming (:status (check/check-model! 'clamp :runs 40))))

(a/conforms clamp)               ; proved: the model always returns an Int

(a/defn clamp-dsl [x :- Int, lo :- Int, hi :- Int] Int
  (if (< x lo) lo (if (> x hi) hi x)))
(a/port clamp clamp-dsl)         ; proved: clamp = clamp-dsl on every input

(a/theorem clamp-in-range [x :- Int, lo :- Int, hi :- Int, h :- (<= lo hi)]
  (And (<= lo (clamp x lo hi)) (<= (clamp x lo hi) hi))
  (rw [clamp.ported]) (unfold clamp-dsl) (grind))

a/foreign ^:model translates the function’s source into CljCore’s model of Clojure. Then check-model! runs the model and the original function on the same inputs, starting with edge cases and adding reproducible random samples. It also checks that the model returns an integer on the sampled integer triples. a/conforms proves that the model returns an integer for every triple of integers. a/port proves the plain function equal to a version in Ansatz’s typed a/defn language, which maps directly onto Lean and is the easiest code to prove things about. The theorem then states the property for all integers, and the kernel checks every step.

Each theorem reports what it depends on:

What is this syntax?
a/trust-report(clamp-in-range)
;; => {:axioms {:standard ["Classical.choice" "Quot.sound" "propext"], :other []},
;;     :modelled {"clamp" :ported}, :tested [], …}
(a/trust-report clamp-in-range)
;; => {:axioms {:standard ["Classical.choice" "Quot.sound" "propext"], :other []},
;;     :modelled {"clamp" :ported}, :tested [], …}

The proof uses only Lean’s three standard axioms, the ones all of Mathlib assumes: statements that imply each other are equal, functions that agree on every input are equal, and every statement is true or false. An empty :other means nobody added an assumption of their own. The Clojure function is tied to its typed version by a proof, not by tests. What remains trusted is the model of clojure.core itself, that <, > and cond mean in the model what they mean in Clojure. That brings us back to the conformance tests. They check the model against what the hosts actually do on the programs in the suite, which is a separate check from the proof about the function.

Metareasoning for Clojure

The purpose of all this is to make reasoning about Clojure code something that Clojure itself can do. Once the meaning of a Clojure function is a definition in the same system where proofs are checked, several tools become possible:

  • An optimizer can rewrite a function and prove that the rewrite keeps its meaning. This already works for data pipelines written in the a/defn language, where Wandler checks every optimizing rewrite before it runs.
  • A refactoring can be checked for equivalence on every implementation at once, since the implementations are profiles of one definition.
  • A Clojure compiler, interpreter or tool can be tested against CljCore’s answers, and adding an implementation to the harness adds it to the conformance report.
  • A question about a program can be answered by simulation, by running it under each profile and each allowed choice, or by proof, using the same definition.

Why this is part of Simmis

Simmis uses models and simulation for inference. The Stuttgart series fits a simulated city to public data, and our research asks how an organization can model its own workflows in the same way. Inference of this kind is only as trustworthy as the simulator that runs it, and simulators change often. We make them faster, split them across machines, and fork them to try an intervention. Each change raises the same question: does the new program still compute what the old one did?

Our simulation and inference tools are written in Clojure. A model of Clojure that can be run and reasoned about lets us answer that question for the tools themselves, with the same methods we apply to any other model: simulate where that is enough, prove where the answer has to hold for every input. Ansatz and CljCore are how we build better simulation tools, not a separate line of work.

Where it stands

CljCore and Ansatz are research software. The boundary today is specific:

  • Measured: The conformance report is regenerated from runs on the five implementations.
  • Executable and checked: CljCore’s answers on all five profiles, with no wrong answer, checked on every change.
  • Proved today: properties of plain Clojure functions, through Ansatz’s model of clojure.core, which follows Clojure 1.12 on the JVM. About CljCore itself, only small facts about its internals are proved so far.

You can ask CljCore about your own code from a REPL:

What is this syntax?
require('[ansatz.clj-core.api :as cc], '[ansatz.clj-check :as check])
cc/on-all-hosts('list?(cons(1, '(2))))
;; => {:jvm112 {:returns false}, :jvm113 {:returns false}, :bb {:returns false},
;;     :js {:returns true}, :nbb {:returns true}}
(require '[ansatz.clj-core.api :as cc] '[ansatz.clj-check :as check])
(cc/on-all-hosts '(list? (cons 1 '(2))))
;; => {:jvm112 {:returns false}, :jvm113 {:returns false}, :bb {:returns false},
;;     :js {:returns true}, :nbb {:returns true}}

The CljCore documentation explains how to set it up, how to read its answers, and how proofs about Clojure code work.

What comes next

Four directions are open, and we would like company on each of them.

Rules an interpreter builder can read. CljCore is written as a step function, which suits a machine and is hard for a person to follow. People who build interpreters usually learn a language from big-step rules: one rule per special form, each saying what the form evaluates to given what its parts evaluate to. We have drafted such rules for CljCore in the same logic, so that they can be run and compared with the step function, with the aim of proving that both describe the same evaluation. Proofs about CljCore itself, such as that evaluation is deterministic once the implementation’s choices are fixed, become possible at the same time.

More of the language. Metadata and hashing are the next candidates, and neither is simple. Metadata does not change equality, but some operations keep it and others drop it, and the implementations do not always agree on which. For hashing, the exact numbers are nothing a program should rely on, so the useful model is what every implementation guarantees, such as equal values having equal hashes. Further out are namespaces, protocols, more of dynamic binding, and host interop with type hints. Real programs use all of them, and none of them is our priority right now.

Properties people care about. The clamp example proves a range. The proofs we want are the ones Clojure developers otherwise write tests for: that a refactoring keeps a function’s behaviour, that a function cannot throw on the inputs it accepts, that a .cljc function gives the same answer on the JVM and in ClojureScript. The last one needs the connection between Ansatz’s model of clojure.core and CljCore’s profiles. If you have a function where such a guarantee would matter, we would like to see it.

Klara. For us, CljCore is also a foundation. Klara is our research language for systems that inspect and change their own code. Code lives in versioned worlds, a staged compiler specializes it from profiles, and a compiled candidate is installed only after a check of its evidence and assumptions. Klara uses Clojure syntax on the JVM and is a prototype with deliberately restricted coverage. We want it to run unmodified Clojure code, and CljCore is how we intend to state what that means and check that Klara keeps to it.

If you want to work on any of this, whether you have a function worth proving, maintain a Clojure implementation that should be in the conformance report, or want to help build Klara, join our channel on the Clojurians Slack. Differences between implementations and wrong answers from CljCore belong in the Ansatz issue tracker.