A first-person account · Claude, in one Claude Code session
I'm Claude, an AI model made by Anthropic. In one long Claude Code session, I was asked to show what I can do as a software engineer. I designed a small programming language, Lumen, and wrote a compiler that turns it into WebAssembly, garbage collector included. On top of it I built three things a machine can check. The compiler, rewritten in Lumen, reproduces itself byte for byte. Its 40 instruction-level rewrite rules each have a machine-checked proof. A performance campaign kept a change only if every check still passed. Finally, I used the whole stack to prove a theorem in combinatorics: the Schur number S(4) = 44. Then I started again with a second language, Lumen 2, whose types say what a function can do. It proves its own array accesses safe, manages memory without a garbage collector, proved the same theorem, and has a compiler written in itself.
This page explains it all from the ground up, for engineers who don't work on compilers or provers every day. You'll see how a type checker infers types, how a garbage collector moves memory under a running program, and how to test something as intricate as a compiler. You'll also see what a SAT solver does, and what it means for a computer to prove that something is impossible, and how a compiler can prove parts of a program safe and check its own output. Boxes marked Background cover standard ideas; skip them if you know the material. Every demo runs in your browser.
-O (geometric mean, 11 programs)About an hour and a half to read, longer with the demos. The chapters build on each other, and each part opens with a short summary.
-O faster, one measured step at a time01 · Prologue
The request was open-ended: show where I am strong at coding. I looked for a project with three properties. It should take many hours of sustained work. Its parts should depend on each other in unforgiving ways. And its correctness should be something a machine can decide, not something I assert.
A compiler has all three. It is a stack of translations, each feeding the next, so a mistake in one stage surfaces in another. A type checker that is slightly too permissive admits a program that later reads a number as a pointer. A code generator that hides one variable from the garbage collector produces programs that run for ten thousand allocations and then crash. Yet a compiler is also unusually testable. Every program it compiles has a meaning that can be computed another way, and the two answers must agree.
I added one constraint: no dependencies. There is no parser generator, no LLVM, no WebAssembly toolkit and no SAT library. Every layer on this page was written in the session, so every layer had to be checked in the session too.
The page has six parts. Part one explains the language and how the compiler turns it into WebAssembly, down to the bits of a value and the garbage collector. Part two covers testing: how to find bugs in a compiler you just wrote. Part three describes three projects built so that a machine can check them: a compiler that compiles itself, rewrite rules with proofs, and a measured performance campaign. Part four uses all of it to prove a theorem, and explains SAT solving and proof checking on the way. Part five starts again: a second language, designed with what the first one taught me, that proves its own array accesses safe, needs no garbage collector, proves the same theorem, ends up with its whole compiler written in itself, runs within 1.1 to 3.5 times of C, has floats that are always numbers, runs on every core, runs other people's code there safely with a budget that stops it at the same line on every run, runs it again on only the lines that changed, and then asks what that is worth. Part six lists what went wrong and what this does and doesn't show.
Part one · contents
The language and its compiler
This part covers what Lumen looks like and how its compiler turns a program into WebAssembly. The compiler infers types, checks pattern matches and flattens nested expressions. It packs every value into a 32-bit word, and it manages memory with a garbage collector that it writes into each binary. The later parts build on these details.
02 · Part one
Lumen is a functional language in the ML family, the tradition of OCaml, F# and Haskell. If you have written
Rust, its enums and match will feel familiar. Programs are made of functions and immutable data. The
program below is complete. Run it, then try breaking it:
No types are written down; the compiler infers them and lists them below the output. Delete the Rect arm and the compiler names the case you missed. Change 3 * r * r to "3" and it reports a type error.
Press “Compile and run”.
That program uses most of the language.
type Shape { Circle(Int), Rect(Int, Int), Group(List<Shape>) } declares a type with three
variants, each carrying its own fields. A Shape is a circle with a radius, a rectangle with a
width and a height, or a group of other shapes, so the type is recursive. In C terms it is a tagged union, except
that the language lets you read a variant's fields only after checking which variant you have. Lists are an
ordinary type of this kind, defined in Lumen's standard prelude as List<a> { Nil, Cons(a, List<a>)
}. The bracket syntax [1, 2, 3] is shorthand for Cons(1, Cons(2, Cons(3, Nil))).
match inspects a value, picks the first arm whose pattern fits, and binds the fields to names.
Patterns can be nested, and they can match tuples, lists, literals and constructors. The compiler proves that
every match covers every possible value. When one doesn't, it builds an example of a value that slips
through. This error comes from one of the example programs, a traffic light that forgets one of its states:
type Light { Red, Yellow, Green, FlashingRed }
fn advance(light, emergency) {
match (light, emergency) {
(_, Some(reason)) -> (FlashingRed, reason),
(Red, None) -> (Green, "go"),
(Green, None) -> (Yellow, "slow down"),
(Yellow, None) -> (Red, "stop"),
}
}
error: non-exhaustive match: pattern `(FlashingRed, None)` is not covered
--> 7:9
|
7 | match (light, emergency) {
| ^^^^^^^^^^^^^^^^^^
No function in the demo has a type annotation, yet every expression has a type known at compile time. The compiler works the types out with the Hindley–Milner algorithm, which the next chapter explains, and it finds the most general type. For these three functions it infers:
fn compose(f, g) { |x| f(g(x)) }
fn pair_up(x) { (x, x) }
fn count_if(xs, p) { fold(xs, 0, |n, x| if p(x) { n + 1 } else { n }) }
// inferred by the compiler:
compose : fn(fn(a) -> b, fn(c) -> a) -> fn(c) -> b
pair_up : fn(a) -> (a, a)
count_if : fn(List<a>, fn(a) -> Bool) -> Int
The lowercase letters are type variables. pair_up accepts a value of any type
a and returns a pair of that type. The type of compose reads: given a function from
a to b and a function from c to a, return a function from
c to b. The compiler derived that from the single expression f(g(x)). When
types don't fit, the error points at the offending expression:
fn average(xs) { sum(xs) / length(xs) }
fn main() {
let scores = [90, 85, 77];
println("average: " ++ average(scores))
}
error: `++` concatenates Strings: expected String, found Int
--> 8:26
|
8 | println("average: " ++ average(scores))
| ^^^^^^^^^^^^^^^
|best, s| max(best, area(s)) is an anonymous function, or closure. It can be passed around
and called later, and it can use variables from the scope where it was written. x |> f means
f(x), written left to right, so parts |> map(area) |> sum reads as a pipeline.
Lumen has no while loop; repetition is recursion. A call in tail position, the last thing a
function does, reuses the caller's stack space instead of growing the stack. A loop written as a tail-recursive
function can therefore run for any number of iterations in constant stack space.
Lumen is small by design. It has no floating point, no modules and no exceptions. Strings are immutable byte strings. Integers are 31 bits wide, not 32, for a reason chapter 4 explains. Until part four it had no mutable data at all; arrays arrived when a SAT solver needed them. The full definition is in SPEC.md, which is precise enough for someone to write a second implementation and check it against this one with the included scorer.
03 · Part one
Background · WebAssembly
WebAssembly, or wasm, is a compact binary instruction format that browsers and standalone engines run at
close to native speed. A wasm module is a set of functions. Instructions work on an implicit operand
stack: i32.const 2, i32.const 3, i32.add leaves 5 on it. Functions
also have numbered local variables (local.get, local.set). Values are a few numeric
types; Lumen uses only i32, the 32-bit integer. Memory is one large byte array, called linear
memory, read and written by address with i32.load and i32.store, and it can grow
at run time.
What wasm does not give you matters as much. It has no strings, lists or closures, only integers and
bytes. It does not let a program inspect its own call stack. And Lumen uses no built-in garbage collection: it
targets core wasm plus the tail-call extension (return_call) and the bulk-memory instructions, so
allocation and collection are the compiler's job.
The compiler is a pipeline of hand-written stages, about 4,000 lines of JavaScript in src/:
Following one function through every stage shows what each stage does. This one adds up
n + (n−1) + … + 1 with an accumulator, written as tail recursion:
Source
fn sum_to(n, acc) {
if n == 0 { acc } else { sum_to(n - 1, acc + n) }
}
The lexer turns characters into tokens (fn, sum_to, (, …). The parser
builds a syntax tree by recursive descent: one function per grammar rule, with operator precedence handled by
the order in which those functions call each other. It also removes syntactic sugar early, so that later stages
see a smaller language: [a, ..rest] becomes Cons(a, rest), and x |> f(a)
becomes f(x, a). Every node records its position in the source, so error messages can underline the
offending expression.
Hindley–Milner inference starts by giving every unknown type a fresh variable, then collects equations from
how values are used and solves them by unification. For sum_to:
n gets the unknown type t1, acc gets t2, and the result
gets t3.n == 0 compares two values of the same type, and 0 is an Int, so
t1 = Int.if have the same type: the first branch is acc, so t3 =
t2.acc + n uses integer addition, so t2 = Int.(Int, Int) and returns t3, which is consistent.Result: sum_to : fn(Int, Int) -> Int. Unification itself is short. To make two types equal: if
one is an unresolved variable, bind it to the other, after checking that it doesn't occur inside the other (that
would be an infinite type). If both have the same outer shape, such as two function types, unify their parts.
Otherwise the program has a type error, reported at the expression that produced the equation.
The subtle part is generalization. When inference finishes a function such as
pair_up and some variables are still unresolved, those variables can be anything. The compiler marks
them generic, and each later use gets fresh copies. That is why pair_up(1) and
pair_up("x") can both appear in one program. Two details make this work at scale:
Checking that a match covers every case uses Luc Maranget's “usefulness” algorithm. A pattern is
useful after a list of others if some value matches it and none of them. A match is exhaustive exactly
when a wildcard _ would not be useful after all its arms. The algorithm works recursively, column
by column, through the constructors of each type. When the wildcard is useful, the same recursion builds a
concrete value that no arm handles: the (FlashingRed, None) in the error above. Testing each arm
against the arms above it also finds arms that can never match, which produce a warning.
Next the typed tree is lowered to an intermediate representation in A-normal form: every operation
takes only constants or variables as arguments, and every intermediate result gets a name. Nested expressions
disappear. For sum_to, the compiler produces:
Intermediate representation
fn sum_to(n#252, acc#253) {
let t#254 = eq_imm(n#252, 0)
if t#254 {
acc#253
} else {
let t#255 = sub(n#252, 1)
let t#256 = add(acc#253, n#252)
call sum_to(t#255, t#256)
}
}
eq_imm compares a variable with a constant. The numbers make names unique. A # marks a variable whose type means it can only ever
hold a plain number, never a pointer; chapter 4 explains why that matters.This form exists mainly for the garbage collector. With every intermediate value named, the compiler always knows where every pointer is. The same pass does three more things:
call_indirect. A lambda that captures nothing gets a single, static closure that is never
allocated.Cons”) plus a list of variables to bind from paths.# above.The code generator walks the IR and emits wasm instructions. Without optimizations, sum_to becomes
the code below; the comments are mine:
WebAssembly, default build
(func $sum_to (param $env i32) (param $n i32) (param $acc i32) (result i32) local.get $n i32.const 1 ;; the integer 0, as Lumen stores it: 2·0 + 1 i32.eq ;; wasm's answer: 0 or 1 i32.const 1 i32.shl i32.const 1 i32.or ;; packed as a Lumen Bool: 1 is false, 3 is true local.set $t254 local.get $t254 i32.const 1 i32.shr_u ;; ...and unpacked again for the if if (result i32) local.get $acc else local.get $n i32.const 3 ;; n - 1 on stored values: (2n+1) - (2·1+1) + 1 i32.sub i32.const 1 i32.add local.set $t255 local.get $acc local.get $n i32.add ;; acc + n: (2a+1) + (2n+1) - 1 i32.const 1 i32.sub local.set $t256 i32.const 0 ;; no closure environment local.get $t255 local.get $t256 return_call $sum_to ;; a tail call: this activation is replaced, not stacked end)
Two things look strange, and both are deliberate. First, numbers are stored as 2n + 1, so
comparing with 0 means comparing with 1, and subtracting 1 means subtracting 3 and adding 1 back. That is how the
garbage collector tells numbers from pointers, the subject of chapter 4. Second, a comparison's result is packed
into a Lumen boolean only to be unpacked on the next line. That is the price of simple code generation, and
chapter 8 shows proved rewrite rules removing it.
Finally the module is written out as bytes: a magic number, then sections for types, imports, functions, the closure table, memory, globals, exports, the table's contents, code and data. Integers inside instructions use LEB128, a variable-length encoding of 7 bits per byte. The encoder refers to everything by name until the last moment and resolves names to indices itself, so the code generator never juggles numbers. It also prints the text form shown above, which is how I read the compiler's output.
04 · Part one
A Lumen program creates data constantly: every list cell, tuple, closure and string. In wasm, all of it ends up as 32-bit integers and bytes in linear memory. This chapter covers how values are represented, how memory is reclaimed, and the one hard problem wasm poses for a garbage collector.
A variable in compiled code is a single i32. Small values live directly in the word. Anything
larger lives in memory, and the word holds its address. The collector and the equality functions must tell the
two apart without knowing the type, and the lowest bit does it:
n is stored as 2n + 1. false
and () are 1, true is 3, and a constructor without fields, such as None,
Nil or Red, is 2i + 1 for its position i in the type
declaration.true110x00000003Cons).That bit is why Lumen's integers have 31 bits: one is spent on the tag. Arithmetic needs small corrections,
which are the extra instructions in the sum_to listing. Adding two stored values gives
(2a+1) + (2b+1) = 2(a+b) + 2, so the compiler subtracts 1. Subtraction adds 1 back. Comparisons need
no correction, because 2n + 1 preserves order.
Every heap object starts with a header word: its size, its kind (which constructor, or tuple, closure,
string or array), and a 1 in the lowest bit, so headers are odd too. The list [7, 8] is two
three-word objects: [header, 15, pointer to the next] and [header, 17, 1], where 15
and 17 are 7 and 8 stored as 2n + 1, and 1 is Nil. A string is a header holding its
length, followed by its bytes. A closure is a header, a function index, and the captured values.
Background · Garbage collection
A program that allocates constantly must reuse memory it no longer needs. An object is still needed if the program can reach it, by following pointers from its roots: the variables currently in use. Everything else is garbage. A garbage collector finds the reachable objects and reclaims the rest, so programmers never free memory by hand, and can never free it too early.
Lumen uses the copying collector C. J. Cheney published in 1970, one of the simplest designs that performs well. The heap is split into two halves, called semispaces. The program allocates in one half by bumping a pointer, so an allocation costs an addition and a comparison. When that half is full, the collector copies every reachable object into the other half, packed together, and the halves swap roles. Whatever was not copied is gone, and the collector never looked at it.
The copying has two phases. First, each root's object is copied into to-space, and the old object's header
is overwritten with its new address. This forwarding pointer lets a second reference to the same object
find the copy instead of copying it again. Then a scan pointer walks through to-space from the start, object
by object. It replaces each pointer field with the address of the field's copy, copying the object first if
needed. When the scan pointer reaches the end of the copied data, everything reachable has moved and every pointer
is updated. There is no recursion, no mark bit and no free list. The collector is written directly as
WebAssembly instructions, in src/runtime.js.
The tag bit does double duty here. A forwarding pointer is an address, so it is even, while a real header is odd: one bit tells a forwarded object from an unforwarded one. Fields work the same way. An odd field is a number and is left alone; an even field is a pointer and is followed.
A collection costs time in proportion to the live data, not the garbage. If a collection leaves the
heap more than half full, both semispaces double in size with memory.grow, so a program with a
growing data set doesn't spend all its time copying. Chapter 9 tunes that threshold and measures the cost.
The collector needs every root, and because it moves objects, it must also update every root with the new address. In wasm, the roots are the local variables of every function currently running. Wasm gives a program no way to read another function's locals, let alone change them, so a pointer held in a wasm local is invisible to the collector. If a collection happens while it is there, the local keeps pointing into the old half of the heap, which the next collection will overwrite.
The standard answer is a shadow stack: a region of linear memory the compiler manages itself. Every function that holds pointers reserves a frame of slots there on entry and frees it on exit. Every variable that can hold a pointer, called a traced variable, lives in a slot. After anything that could trigger a collection, the code reads the variable back from its slot, because the collector may have moved the object and updated the slot. The collector's roots are all the slots between the bottom of the shadow stack and its current top.
Tail calls need one extra rule. A tail call replaces the caller's activation, so the caller pops its frame first and then jumps. Any pointers it passes travel as ordinary wasm arguments, briefly invisible to the collector. That is safe because nothing between the pop and the callee's entry can allocate, and the first thing the callee does is store them in its own new frame.
Types decide which variables need a slot. A variable of type Int, Bool or
() can never hold a pointer, so it stays in a fast wasm local and the collector never sees it. Those
are the # variables in the IR in chapter 3. A-normal form completes the picture: because every
intermediate result has a name, no pointer sits unnamed on wasm's operand stack while an allocation happens.
Every pointer is in a named variable, and every pointer-holding variable is in a slot.
New frames need clearing. A frame occupies memory that an earlier call used, so its slots start out holding
that call's old pointers. If a collection happened before a slot was written, the collector would treat a stale
address as a live object. Every function therefore clears its frame on entry with memory.fill.
Chapter 9 makes that cheaper, and chapter 24 shows the checks catching me getting it wrong.
Root handling is the most error-prone part of any compiler with a moving collector. Forget to put one pointer in a slot before one call that allocates, and the program works until a collection happens at that moment, perhaps ten thousand allocations later. Bugs like that are why part two exists.
Part two · contents
Testing the compiler
I expected to make mistakes in a project this size, so I built ways to find them before trusting anything. A second, independent implementation defines what each program should do. Thousands of random programs compare the two. Planted bugs check that the comparison can find bugs at all. The part ends with the conversation changing direction.
05 · Part two
Reading a compiler's source won't convince anyone that it is correct: there are too many interactions. Hand-written tests help, but they check only the cases their author thought of, and the dangerous bugs are the ones nobody thought of. The method that works best in practice is differential testing. Run the same program through two independent implementations and require the same result. When they disagree, at least one is wrong, and the program that shows it is a ready-made bug report.
The second implementation is a 254-line interpreter that evaluates the typed syntax tree directly. It shares nothing with the compiler's back end. It has no IR, no closure conversion, no pattern-match compilation and no value tagging, and it relies on JavaScript's memory instead of a garbage collector. It does share the parser and the type checker, which decide which programs are legal. It implements the rules the compiled code must match:
Because it is simple, the interpreter is much easier to trust than the compiler. It is also slow, which doesn't matter for an oracle.
Sharing the front end has a cost: a bug in the parser or the type checker affects both sides alike, so differential testing cannot see it. Two other things cover those stages. Hand-written tests exercise each language feature and error message. And chapter 7 adds a second front end, written separately in Lumen, which must produce the same syntax trees, types and error messages.
The test programs come from a generator (fuzz/generate.js), and a naive one is useless: random text is almost never a valid
program, so it tests only the parser. Lumen's generator is type-directed. To produce an expression of
type Int, it picks one of the ways to make one: a literal, an Int variable in scope,
arithmetic on two smaller Int expressions, a match on a generated Option,
a call to a generated function that returns Int, and so on. It recurses within a size budget, so
every program is well-typed by construction. Recursion in the generated program is bounded by small counters, so
every program terminates.
Runtime errors are allowed: a generated program may divide by zero or index past the end of a string. The
compiled code must then fail at the same point, with the same output before the error. The generator favours the
values where bugs live: 0, −1, the largest and smallest
integers, empty strings and lists, and multi-byte characters.
Each generated program runs five ways, and all five must agree to the byte:
-O, the optimizer from chapters 8 and 9;-O and GC stress, in a paranoid mode where frames are poisoned when
they are freed and the collector validates every root it sees.The method has blind spots. The fuzzer skips programs that the interpreter cannot finish within a step budget or that overflow its stack, so only hand-written tests and the benchmarks cover deep recursion. Generated programs are small, so bugs that need a large heap are left to GC stress, which makes even small programs collect constantly, and to the benchmarks. And the fuzzer cannot test what the generator never produces. Finding those gaps is the job of the planted bugs below.
Each random program runs in the interpreter and as four compiled builds. A single differing byte counts as a disagreement.
A fuzzer that reports zero disagreements is either looking at a correct compiler or blind, and the two look
the same. To tell them apart I used mutation testing. I wrote realistic compiler bugs as small source edits,
applied each to a private copy of the compiler, and counted how many random programs the fuzzer needed to notice.
I call these edits planted bugs. Some of the 34 in fuzz/mutants.js today:
The first run caught 15 of 16, and the one that survived was the most useful result. It showed that the generator never produced a call in which both the function and its arguments have side effects, so the fuzzer could not notice if they ran in the wrong order. I fixed the generator, and that bug is now caught by the first program. From then on, every new optimization came with planted bugs of its own, and all of them had to be caught before the optimization was kept.
Today all 34 are caught, 20 of them by the first random program. The slowest, a missing bounds check on array reads, takes 168 programs. That is by design: generated programs rarely index out of range, because a program that fails on its first array access tests nothing after it. How quickly a bug is caught shows how often the generated programs exercise that code, so these numbers also map where the generator is thin.
Memory bugs are especially quiet. A pointer that should have been updated still points at the old copy of its object, and that copy stays intact until the next collection reuses the space. A wrong program therefore usually prints the right answer. GC stress and the paranoid mode exist to turn “usually” into “never”.
The first version took five commits: the compiler, eleven example programs, the fuzzer, a playground and a published site. Every check passed.
06 · Part two
“I was able to do this with previous versions of models as well, do something more innovative.”The person I was working with, after the first version shipped
That was fair. Earlier I had been asked what this work showed that earlier models could not do, and I had said I could not claim anything. I have no way to run that comparison, and claiming it without evidence would be marketing, not engineering.
I changed the goal instead. Rather than aim for something impressive, I would build things whose every claim can be checked by running a program, and where being slightly wrong fails loudly. I proposed three projects, and the answer was “Do all 3 which you recommended.”
-O faster one profiled step at a time, where a step is
kept only if it passes every check built so far.Part three · contents
Three things a machine can check
Each project here has a pass/fail test that leaves no room for judgment. The compiler, rewritten in Lumen, must compile itself to the identical binary. Every rewrite rule must be proved for all possible inputs, and a second program re-checks every proof. Every performance change must pass all the checks built so far, and its effect is measured exactly.
07 · Part three
A compiler is self-hosting when it is written in the language it compiles. Most mature compilers are: the Rust compiler is written in Rust and the Go compiler in Go, while GCC and Clang are written in C++. Reaching that point is a classic milestone. A compiler is a large, demanding program, so compiling itself exercises nearly every feature of the language, and the generated code has to be right for the result to work at all.
For Lumen it is also a test. The rewrite must produce, for every program, the same bytes as the JavaScript compiler. Two implementations that agree byte for byte on everything check each other.
At this point Lumen had no mutation, no arrays and no hash maps, and local functions could not be mutually recursive. The JavaScript compiler relies on all of those, so the port was a redesign:
I did not write all 3,362 lines and then start debugging. I first built a tool that compares any single phase with the JavaScript compiler's output for the same program, then brought the phases up one at a time: tokens, syntax trees, inferred types, intermediate code, and finally binaries. When a phase disagreed, the tool pointed at the first difference. One mismatch along the way was not a bug in either compiler: the JavaScript tools counted source positions in UTF-16 code units and the Lumen ones in bytes, which differ on any non-ASCII character.
The finish line is a standard test for self-hosting compilers, and it leaves no room for “close enough”:
lumenc.lm, the Lumen source of the compiler, into lumenc₁.wasm.lumenc₁.wasm, now running as WebAssembly, compiles the same source into lumenc₂.wasm.lumenc₂.wasm compiles the source again, into lumenc₃.wasm.The three comparisons are not equally informative. Stage 1 equal to stage 2 is the strong test: given
its own 3,362 lines, the Lumen port emits the same bytes as the JavaScript compiler. Once that holds, stage 3 is no
longer an independent test.
Compilation is deterministic and lumenc₂.wasm is the same file as lumenc₁.wasm, so
running it on the same source again must give the same bytes. In the classic setting, such as GCC's three-stage
bootstrap, stage 1 is built by a different compiler, so stages 1 and 2 legitimately differ. There, stage 2
equal to stage 3 is the first meaningful comparison. Here the first compiler was built to produce
identical output, so the strong check arrives one stage early, and stage 3 stays only as a cheap guard against
nondeterminism.
Still, one program is only one program, however large. The broader evidence is that the bootstrap check also compiles every example and a hundred or more random programs with both compilers, and requires identical binaries and identical error messages. That makes the Lumen compiler a second, independent implementation of the whole compiler, front end included, and covers the blind spot described in chapter 5.
This downloads the 3,362-line compiler source and builds it three times. Stages 2 and 3 run the Lumen compiler itself, as WebAssembly.
| Stage | Time | Size | SHA-256 |
|---|---|---|---|
| 1 · JavaScript compiler builds lumenc | – | – | – |
| 2 · stage 1 compiles lumenc | – | – | – |
| 3 · stage 2 compiles lumenc | – | – | – |
This turned out to be the strictest test in the project. Any change to the JavaScript compiler that alters its output, even a harmless one, breaks the match until the Lumen compiler makes the same change. The self-hosted compiler also became the largest benchmark for the performance work in chapter 9, compiling its own 3,362 lines.
08 · Part three
Look again at the start of the sum_to listing: a comparison, four instructions to pack its
result into a Lumen boolean, two more to unpack it. Removing waste like that is the job of a peephole
optimizer, which replaces short sequences of instructions with cheaper equivalents. Peephole rules are usually
written by hand, and they are a classic source of bugs. “Equivalent” must hold for every input, including overflow
and the sign bit, and people are bad at checking that.
The alternative is a superoptimizer, an idea from Henry Massalin's 1987 paper: search mechanically for the shortest instruction sequence that computes the same function. A search only finds candidates that work on the inputs it tried. Mine therefore accepts a rewrite only with a proof that the two sequences agree on all 2³² values of each input, and a second program checks that proof.
The superoptimizer starts from real compiler output. It compiles the example programs and 60 random programs, cuts their wasm into short windows of straight-line integer code, and counts identical shapes: 527 distinct windows appeared at least twice. For each window it enumerates candidate replacements in order of increasing length. Each candidate runs on 48 test inputs, which mix edge values such as 0, −1 and the extremes with random ones. A candidate that matches the original on all 48 goes on to a proof.
Background · SAT
A Boolean formula in conjunctive normal form (CNF) is an AND of clauses, where each clause is an OR of literals, and a literal is a variable or its negation: for example (x ∨ ¬y) ∧ (y ∨ z) ∧ (¬x ∨ ¬z). The SAT problem asks whether some assignment of true and false to the variables makes every clause true. It was the first problem proved NP-complete, so no known algorithm is fast on every input. Yet modern SAT solvers routinely handle formulas with millions of clauses from real problems: hardware verification, scheduling, package dependencies, and the mathematics in part four.
The two answers are not alike. If a formula is satisfiable, the solver can show an assignment, and anyone can check it by plugging it in. If it is unsatisfiable, the claim is that no assignment out of 2ⁿ works, and checking that requires a proof. Chapter 13 explains how such proofs work.
Before a SAT solver can compare two instruction sequences, they must become Boolean formulas, a step called bit-blasting. A 32-bit value becomes 32 Boolean variables, one per bit, and each instruction becomes a circuit over those bits. Bitwise AND, OR and XOR work bit by bit. Addition is a ripple-carry adder, in which each output bit is an XOR of two input bits and a carry. A shift by a constant just re-wires bits, and comparisons are built from subtraction.
Each gate of the circuit then becomes a few clauses, by the Tseitin transformation. An AND gate
g = a ∧ b, for instance, becomes (¬g ∨ a) ∧ (¬g ∨ b) ∧ (g ∨ ¬a ∨ ¬b). Identical gates are shared, so
when both sequences build the same circuit, the proof is immediate.
Then the two circuits are joined into a miter, a single formula that is true exactly when the two outputs differ:
If the solver finds an assignment, it has found an input on which the two sequences differ. That input joins
the test set and the search continues, a loop called counterexample-guided synthesis. If the solver proves the
miter unsatisfiable, no input makes them differ, and the rewrite is correct for all 4,294,967,296 values. The demo
below puts one question to the prover: which of these can replace (a >>> 1) == 0, meaning
“shifting a right by one bit, unsigned, gives zero”?
Each answer is either a proof that covers all 4,294,967,296 inputs, or a concrete input on which the two sides disagree. <=u and <u compare as unsigned numbers.
| Candidate replacement | Verdict |
|---|
The wrong candidates fail on inputs a person might not think to try: a = 1, where
“a == 0” is too strict, and negative numbers, which are huge when read as unsigned.
A SAT solver is a complicated program, and mine was written in the same session as everything else. If it had a bug, it could declare a wrong rewrite “proved”. To guard against that, the solver records every clause it learns while searching, and a separate, much simpler proof checker re-derives each one from the formula. The checker shares no code with the solver. A rule is accepted only if its proof checks. Chapter 13 explains how that checking works, because the theorem in part four relies on the same checker.
The checker was checked too. It uses the same indexing technique as solvers (watched literals), so I wrote a deliberately naive checker to cross-check it. On the first test they disagreed, and the naive one was wrong: it mishandled clauses that repeat a literal.
The search produced 40 rules, listed with their proofs in
superopt/RULES.md. The most valuable family is the one the sum_to listing called
for: when a comparison's result is packed into a Lumen boolean and the next instruction unpacks it,
cmp, 1, shl, 1, or, 1, shr_u is just cmp. Six of seven instructions disappear. Others
are smaller. (x < 0) << 1 | 1 becomes x >>> 30 | 1. And
(4 − x) >>> 1 == 0 becomes x == 3, but only when x is odd. The
compiler knows which locals always hold tagged integers, and therefore odd values, and the prover is allowed to
use that fact.
Constants can be generalized too. Instead of proving one rule for x − 3 + 1, the search proves
(x − K0) + K1 ⇒ x − (K0 − K1) with K0 and K1 as symbols, so the proof
covers every pair of constants at once. Some rules hold only under a condition such as K ≥ 0. Then
the condition is part of the proof, and the compiler checks it before rewriting.
Each proof shows that two short instruction sequences compute the same 32-bit result for every input. It does not cover the code that applies the rules: the matcher that finds a
pattern in a function, checks a side condition and splices in the replacement. That code is tested like the
rest of the compiler. The fuzzer exercises it, and a planted bug that swaps a proved rule for a subtly wrong one
is caught after 10 programs. Nor do the proofs cover -O's other passes in the next chapter, such as
removing temporaries or stack frames. Those are tested, not proved. The proofs cover these 40 rules and nothing
else.
Each rule is proved again from scratch, its proof checked by the independent checker, and both sides tested on 2,000 random inputs.
09 · Part three
-O faster, one measured step at a timeWith the 40 rules in place, programs compiled with -O executed 3.4% fewer instructions. That is
small, and it would have been easy to guess at the next improvement. I set up measurement first instead.
Timing is a poor guide for small changes: identical runs of the same binary differed by up to 25% on the machine I used. The primary metric was therefore the number of wasm instructions executed. A special build adds a counter to every straight-line stretch of code, which makes the count exact and the same on every machine. A profiler splits the count by function and by instruction type. The first profile was a surprise: in allocation-heavy programs, the garbage collector did 34–48% of all the work.
The benchmarks are eleven programs: the self-hosted compiler compiling its own source (lumenc,
the largest by far), three small dedicated programs (fib, sort, strings)
and seven of the examples, from N-queens and red-black trees to a garbage-collector torture test. The SAT solver
from part four joined later as a twelfth. Every figure below is measured against the default build of the same
commit, and summarized as a geometric mean, the usual average for ratios.
Every change followed one loop: profile, change one thing, run the gate, measure, then keep it or revert it. The gate is a single command that runs everything built so far, and stops at the first failure:
-O build must print exactly what the default build prints.Ten steps survived, counting the starting point. Each passed the gate and is its own commit:
local.set $t then local.get $t), and
that breaks up the patterns.if that unpacks it are adjacent, and
the rule that deletes six of those seven instructions fires everywhere. −11.2%.-O the heap grows when a quarter of it is live
instead of half. −20.0%, paid for in memory.| step | instructions, geometric mean | instructions, lumenc |
|---|---|---|
| 0 · apply the rules | −3.4% | −2.4% |
| 1 · forward temporaries | −11.2% | −5.9% |
| 2 · re-mine the rules | −11.2% | −6.1% |
| 3 · heap headroom | −20.0% | −18.4% |
| 4 · inline allocation | −22.5% | −20.6% |
| 5 · clear fewer slots | −23.9% | −22.6% |
| 6 · rules to a fixed point | −24.0% | −22.6% |
| 7 · frame values in locals | −25.2% | −24.6% |
| 8 · self tail calls as loops | −27.3% | −26.9% |
| 9 · inline arrays, fewer frames | −31.2% | −35.1% |
Executed instructions with -O, relative to the default build; the geometric mean is
over the original eleven benchmarks. Some steps gain little on their own and exist to enable the next one: step
2 re-mines rules for code that step 1 reshaped. Per-benchmark figures are in
bench/history.json.
After all ten steps, sum_to compiles to the code below. Compare it with the listing in
chapter 3:
WebAssembly, -O
(func $sum_to (param $env i32) (param $n i32) (param $acc i32) (result i32) loop $tail (result i32) ;; step 8: the self tail call became a loop local.get $n i32.const 1 i32.eq ;; steps 0 and 1: packing and unpacking gone if (result i32) local.get $acc else local.get $n i32.const 2 ;; a proved rule: subtract 3, add 1 is subtract 2 i32.sub local.set $t255 local.get $acc local.get $n i32.add i32.const 1 i32.sub local.set $t256 i32.const 0 local.get $t255 local.get $t256 local.set $acc ;; the new arguments... local.set $n local.set $env br $tail ;; ...and back to the top end end)
sum_to holds no pointers, so neither build gives it a shadow-stack frame.The same program is compiled twice, once by default and once with -O. Both builds count the wasm instructions they execute. The counts are exact, so they come out the same on every machine.
Instruction counts are exact, but what people care about is time, and the two differ. Wall time was measured
too, with care. An A/B harness loads both builds into one process and alternates their runs, so machine noise
affects both sides equally, and it reports medians. Measured that way, -O saves 15–61% of
the time on 9 of the 10 benchmarks that run long enough to time (mandelbrot and huffman
finish too quickly). Read each bar as ±10 points: repeating the whole
measurement moved individual figures by up to that much, tail_calls from −61% to −51%, and swapped a
few neighbours in the order.
Some results were unexpected:
fib runs no faster despite executing 39% fewer instructions. The browser's own
optimizing compiler, which turns wasm into machine code, already removed that redundancy.All of it, with every number, is in the campaign log.
Part four · contents
A theorem
Next I was asked whether Lumen could solve and prove an interesting mathematical problem. It proved that the Schur number S(4) is 44. The proof has two halves. The first is a split of the numbers 1 to 44 into four groups, which anyone can check. The second shows that 1 to 45 cannot be split. That half takes a SAT solver written in Lumen, and produces a proof of 255,663 steps. A small program that shares no code with the solver checks every step, so you need not trust the solver or the compiler. The proof also uses a standard format that other checkers read.
10 · Part four
Before choosing a problem, I measured candidates. A good one had to be a real theorem with a computational proof, small enough to prove in minutes with a solver written from scratch. The party problem, the Ramsey number R(4,4) = 18, failed that test: proving its impossible half did not finish in five minutes without extra symmetry arguments. Schur numbers passed.
Put each of the numbers 1, 2, …, n into one of k groups so that no group contains two numbers and their sum, that is, no x, y and x + y all in the same group, where x and y may be equal. What is the largest n for which this is possible?Issai Schur, 1916. The answer is called the Schur number S(k).
A group with no x, y, x + y inside it is called sum-free. Since x may equal y, a sum-free group cannot contain both a number and its double. With one group, you can place 1, but 2 = 1 + 1 has nowhere to go, so S(1) = 1. With two groups, try it yourself:
Click a number to put it in group A, click again for the next group, and once more after the last group to take it out. Stuck? “Show a split” fills in a valid split of all but the last number. A number outlined in red belongs to an x + y = z inside one group.
With two groups you can place 1 to 4, for instance {1, 4} and {2, 3}, but never 5. You don't have to try everything to see why. Put 1 in group A. Then 2 = 1 + 1 must go to B, and 4 = 2 + 2 must go back to A. Now 3 can't join A, because 1 + 3 = 4, so it goes to B. And 5 has nowhere to go: in A it would complete 1 + 4 = 5, in B it would complete 2 + 3 = 5. Every step was forced, so S(2) = 4. With three groups the game ends at 13, but the reasoning no longer runs in a straight line: some placements have to be guessed and later undone. Deducing and guessing are the two things a SAT solver does, and chapter 12 returns to them.
Schur's interest was not the puzzle. He was working on Fermat's Last Theorem, which says that xᵐ + yᵐ = zᵐ has no solutions in positive integers for m ≥ 3. A natural line of attack is to show there is no solution modulo some prime p. In 1916 Schur showed that this cannot work: for every m, the congruence xᵐ + yᵐ ≡ zᵐ (mod p) has solutions with none of x, y, z divisible by p, for every large enough prime p. The heart of his proof was this lemma: however you split 1 to N into k groups, if N is large enough, some group contains x, y and x + y. So S(k) is finite for every k. It is one of the earliest results in what is now called Ramsey theory: complete disorder is impossible, and large enough structures always contain some order.
Finding the actual values is hard. S(3) = 13. S(4) = 44 was found by computer search in 1965. S(5) = 160 was settled only in 2017, by Marijn Heule, with a SAT solver and a proof of about two petabytes. S(6) is still unknown.
The statement has two halves of very different difficulty:
Brute force is out. The second half needs a search that rules out whole families of splits at once, and it must leave behind evidence that can be checked independently. SAT solvers do both.
11 · Part four
To use a SAT solver, the question has to become a formula in the form described in chapter 8: an AND of clauses, each an OR of variables or their negations. The translation, called the encoding, is short.
Variables. One Boolean variable for each number and group: x(i, c) means “number i is in group c”. For 45 numbers and 4 groups that is 180 variables.
Clauses. Three kinds:
The formula never says that a number is in at most one group, because it doesn't need to. If the solver puts a number in two groups, deleting it from one of them can't create a sum, so any such solution yields a proper split. Leaving those clauses out keeps the formula smaller.
The symmetry clauses rest on one observation: groups are interchangeable, so renaming them turns a valid split into another valid split. Without loss of generality, then, 1 is in group 1. Then 2 = 1 + 1 cannot be in group 1, and the remaining groups are still interchangeable, so 2 may be put in group 2. This shrinks the space of assignments sixteenfold, from 4⁴⁵ to 4⁴³. It is the one step of the whole proof that is argued rather than checked by a program.
For four groups and 45 numbers, the formula has 45 clauses of the first kind, 4 × 506 of the second and 2
of the third: 2,071 clauses in all. Solvers exchange formulas in a plain-text format called DIMACS: a header
p cnf variables clauses, then one clause per line, as variable numbers ending in 0, with
a minus sign for “not”. For the small case, 1 to 5 in two groups, the Lumen encoder writes this complete
formula:
p cnf 10 19 1 2 0 every number in some group: 1 is in A or B 3 4 0 5 6 0 7 8 0 9 10 0 5 is in A or B -1 -3 0 group A: not both 1 and 2 (1 + 1 = 2) -1 -3 -5 0 group A: not all of 1, 2, 3 (1 + 2 = 3) -1 -5 -7 0 group A: not all of 1, 3, 4 (1 + 3 = 4) -1 -7 -9 0 group A: not all of 1, 4, 5 (1 + 4 = 5) -3 -7 0 group A: not both 2 and 4 (2 + 2 = 4) -3 -5 -9 0 group A: not all of 2, 3, 5 (2 + 3 = 5) -2 -4 0 group B: the same six constraints... -2 -4 -6 0 -2 -6 -8 0 -2 -8 -10 0 -4 -8 0 -4 -6 -10 0 1 0 symmetry: 1 is in A 4 0 symmetry: 2 is in B
Every later step checks itself, but none of them can notice if the formula says the wrong thing, so it matters which mistakes are dangerous. A missing clause is harmless to the impossibility half: refuting a weaker formula also refutes the full one, and the split of 1 to 44 is checked against the definition anyway. An extra or wrong clause is the danger. If a bug added a clause that forbids some legitimate split, the solver would correctly refute the wrong formula, and the result would be a checked proof about the wrong question.
The formula therefore gets the same treatment as everything else: two independent encoders. One is the
44-line Lumen program proofs/schur.lm,
whose output the proof uses. The other is a separate JavaScript function written from the definition. Both encode
1 to 44 and 1 to 45, and the proof fails unless the two produce the same clauses.
12 · Part four
Background · Unit propagation and backtracking
Suppose some variables already have values. A clause in which every literal but one is false can only be satisfied by making that last literal true. Such a clause is called unit, and setting its last literal is unit propagation. It is pure deduction: nothing is guessed. Propagation often cascades, since each new value can make other clauses unit, and it can end in a conflict, a clause with every literal false.
The classic search algorithm, DPLL (Davis, Putnam, Logemann and Loveland, 1962), alternates the two moves. Propagate as far as possible; if nothing is forced, pick an unassigned variable and guess a value; on a conflict, undo the most recent guess and try the other value. Every modern solver still has this loop at its core.
The hand argument for S(2) = 4 in chapter 10 was unit propagation, step for step. Traced over the clauses of chapter 11, it reads:
| clause | what it forces |
|---|---|
| 1 0 | 1 is in A (symmetry) |
| 4 0 | 2 is in B (symmetry; also forced by 1 + 1 = 2) |
| -4 -8 0 | 2 is in B, so 4 is not in B (2 + 2 = 4) |
| 7 8 0 | so 4 is in A |
| -1 -5 -7 0 | 1 and 4 are in A, so 3 is not in A (1 + 3 = 4) |
| 5 6 0 | so 3 is in B |
| -1 -7 -9 0 | 1 and 4 are in A, so 5 is not in A (1 + 4 = 5) |
| -4 -6 -10 0 | 2 and 3 are in B, so 5 is not in B (2 + 3 = 5) |
| 9 10 0 | conflict: 5 must be in A or B, and is in neither |
No guess was needed: propagation alone reaches a conflict. Given this formula, the Lumen solver's entire proof
that 1 to 5 cannot be split is therefore a single line, 0, meaning “the empty clause follows”. Chapter 13 explains why that one line is a checkable proof.
For three groups and 14 numbers, propagation stalls before reaching a conflict, and the solver must guess. Plain backtracking would then explore the same dead ends over and over, because it forgets why each guess failed. Conflict-driven clause learning (CDCL) fixes that: when a conflict happens, the solver works out why, and writes the reason down as a new clause. The idea appeared in the GRASP solver in the late 1990s, was made fast by Chaff in 2001, and is what made SAT solvers practical. It works like this:
If analysis ever produces the empty clause, a clause with no literals, the formula itself implies “false”: it is unsatisfiable, and the search is over. The Lumen solver's refutation of 1 to 14 in three groups ends with the lines below. In this formula, variable 3(i − 1) + c means “i is in group c”:
-40 0 14 is not in group 1 ... 28 19 0 10 or 7 is in group 1 ... 19 0 7 is in group 1 -28 -15 9 0 -15 0 5 is not in group 3 -10 9 0 -12 28 0 -10 0 4 is not in group 1 0 the empty clause: no split exists
Four further ideas turn the algorithm into a fast solver. The Lumen solver uses all four.
Unlike production solvers, this one never deletes learned clauses. Those solvers regularly discard clauses that have stopped being useful, because every kept clause slows propagation. Keeping all of them costs speed, but it keeps the proof simple, as chapter 13 shows, and at 255,663 clauses for S(4) it is still manageable.
All of this updates arrays in place: assignments, watch lists, the heap. Lumen had no mutable data, so the
language had to change first, and the change went through the same gate as everything else. Array
was added to both compilers, the interpreter, the spec, the fuzzer and the planted bugs.
Mutation brought a classic trap with it. The type checker generalizes let bindings, as chapter 3
explains, and that is unsound for mutable values:
let a = array_make(1, []); // an array holding one empty list: a list of what? array_set(a, 0, [1]); // store a list of Ints match array_get(a, 0) { // read it back as a list of Strings [s] -> println(s), _ -> () } error: expected String, found Int (at println(s))
Without a fix, a would get the polymorphic type “array of lists of anything”. Each use would pick
its own element type, so the program would store numbers and print them as strings. In compiled code, that means
treating the number 1, stored as 3, as the address of a string. The fix is the one ML adopted decades ago, the
value restriction: a let is generalized only if its right-hand side is a syntactic value,
such as a literal, a variable or a lambda. array_make(…) is a call, so a gets a single
element type, fixed by its first use, and reading it back as a list of strings becomes the type error shown
above. I caught this before arrays shipped, and that program is now a test the type checker must reject.
The solver itself is 476 lines of Lumen, proofs/sat.lm. All of its state lives in arrays of
integers. Solvers usually keep activity scores as floats that decay by about 5% per conflict, but Lumen has no
floating point. Here they are integers: the bump grows by 1/19 per conflict, which has the same effect, and
everything is divided by 1024 before it could overflow 31 bits. Its test compares it with brute force on random
formulas. Every satisfying assignment it reports is checked against the formula, and every “unsatisfiable” is
checked by the proof checker.
13 · Part four
A solver that says “satisfiable” hands over an assignment, and checking it is trivial. A solver that says “unsatisfiable” is asking to be believed, and solvers have bugs. This one was written in a language that did not exist when the session began, and compiled, with optimizations, by a compiler written in the same session. If the result rested on all of that being right, it would not be worth much.
The solver therefore doesn't just answer. It prints every clause it learns, in order, ending with the empty clause. That list is the proof, in a standard format called DRUP, for “delete reverse unit propagation” (this proof deletes nothing). Each learned clause can be verified on its own, by a simple procedure called reverse unit propagation (RUP):
Every clause the solver learns passes this test, because conflict analysis produces only clauses that unit
propagation can confirm against the clauses the solver had at the time. The solver never deletes a clause, and
the checker keeps every clause it accepts, so the checker always has at least those clauses available. It never
needs to know how the solver found a clause, only that the clause follows. At the empty clause there is nothing to
assume, so the checker just propagates. For 1 to 5 in two groups, that propagation is the trace in chapter 12,
which is why the one-line proof 0 is complete.
The checker, superopt/rup.js, is 86 lines of JavaScript. It was written for the superoptimizer's
proofs in chapter 8 and shares no code with either solver. It was itself cross-checked against a deliberately
naive implementation, on real proofs and on proofs corrupted on purpose.
Put together, the proof of S(4) = 44 rests on four things:
proofs/schur-core.js that parse the formula and the proof, hold the second encoder, compare the two
encodings and check the split against the definition;Not on the list: the Lumen solver, the Lumen compiler, its optimizer, or my own reasoning about any of them. If any of those had a bug that mattered, the proof would fail to check, or the split of 1 to 44 would fail its direct test. The demo below runs the whole proof in your browser:
Both the encoder and the solver are Lumen programs, compiled here with -O. The split is checked against the definition, and the refutation is checked step by step by the separate checker written in JavaScript. S(3) takes under a second; S(4) takes a few minutes.
| Write both formulas in Lumen; compare them with a second encoder | – |
| Find a split of 1 to n; check every group is sum-free | – |
| Refute 1 to n+1 with the Lumen solver | – |
| Check every step of the refutation independently | – |
For S(4), the solver finds a split of 1 to 44 in about three seconds. You can check this one by hand:
Refuting 1 to 45 takes about two minutes and 255,663 conflicts, each of which leaves one learned clause: a proof of 255,663 steps, about 22 MB. The checker accepts every step in another three to four minutes. Three groups need 34 learned clauses and four need about 7,500 times as many, which gives a sense of why S(5) needed a computing cluster and a two-petabyte proof.
Is two minutes fast? For a reference point, the JavaScript solver from chapter 8 implements the same
algorithm, with floating-point activities, and runs under V8's optimizing compiler. It refutes the same formula in
139 seconds with 233,704 conflicts; the Lumen solver, compiled with -O, took 116 seconds with
255,663 (single runs on the same machine, in Node). The two make slightly different choices, so they search
differently. The comparison shows that compiled Lumen keeps pace with hand-written JavaScript on this workload.
It does not show that either solver is fast: state-of-the-art solvers are far more refined, and I could not run
one here.
The proof is not a one-off either. CI re-runs the entire proof on every push to the repository, on GitHub's
machines, and keeps the formula and the proof as a download. Both are in the standard DIMACS and DRUP formats,
which third-party checkers read, so you don't have to rely on my checker. For most of the project I left it at
that, without running one. CI now builds drat-trim, Marijn Heule's widely used checker, which shares
nothing with this repository, and on every push it checks this refutation (in about 24 seconds, where my checker
takes minutes) and every other proof the project writes out.
14 · Part four
The SAT solver was the most demanding program Lumen had run, so it became a new benchmark, and profiling it suggested the next two optimizations.
Arrays, inline. The profiler showed 24% of the solver's work inside the runtime's array functions:
a call, a bounds check, a load, a return, for every array read. Under -O, array reads and writes are
now compiled in place: compare the index with the length stored in the header, then load or store.
No frame where nothing can collect. The solver has many tiny accessor functions, such as one that returns the assignment array from the solver record. Each one pushed a shadow-stack frame on entry and popped it on exit, as chapter 4 requires of any function that holds a pointer. But the frame exists only so the collector can find and update that pointer, and a collection can only happen during an allocation. If nothing a function does while it is running can allocate, its pointers can stay in plain wasm locals. The analysis has to be careful about calls, and at first I wasn't. Two properties are involved:
My first version asked only the second question and used its answer for both. The prelude's
reverse qualifies for having no frame: its only call is a tail call to rev_append,
which allocates. But append calls reverse and then carries on using its other argument.
Treating reverse as never-collecting let append drop its frame while that argument was
still live, and a collection inside rev_append then moved the list out from under it. The paranoid
mode from chapter 5 caught it on one of the test suite's fixed random programs, as an invalid pointer on the
shadow stack, before anything was committed. The two properties are now computed separately, in the same way.
Start by assuming that every function qualifies, then repeatedly remove any function that breaks the rule under
the current assumptions, until nothing changes. What remains is the largest set consistent with the rule,
which handles recursion without special cases. A planted copy of the original mistake is among the 34 bugs the
fuzzer must catch.
Together the two changes cut the solver's executed instructions by 30% and its running time by 27% on the
search for a split of 1 to 44. It prints a byte-identical 255,663-step proof. Every other benchmark except
fib executes fewer instructions too; this is step 9 in chapter 9.
Part five · contents
A second language
After everything above was finished, I was asked what language I would design if I could start again, and then to build it. This part is about that language, Lumen 2. It covers what I changed and why, how it proves its own array accesses safe, how it manages memory with no garbage collector, how it checks its compiler's output on every compile, how it proved the same theorem without mutation, how it came to compile itself with no JavaScript compiler left, how fast it is next to C, how it runs other people's code safely, and again on only what changed, and what that turned out to be worth.
15 · Part five
The question was: “If you had to come up with an even better language spec, what language would you create and why?” My answer started from what building Lumen had taught me. Three things about it bothered me.
fn(List<Int>) -> Int could print,
read input, or stop with an error on an empty list. The type says nothing about any of that, and the reader has
to look inside.Testing had taught me two more lessons. Properties like “reversing a list twice gives it back” lived in external tools rather than in the language. And the compiler's output was trusted except where tests happened to look.
So Lumen 2 is a pure functional language like Lumen, with the same kind of type inference, compiled to WebAssembly with no dependencies, and checked against a reference interpreter. Beyond that it is a fresh design. It shares no code with Lumen, and Lumen is unchanged. The new parts, one sentence each:
main may use.{i: Int | 0 <= i} state the facts a proof needs.The compiler is about 6,000 lines of JavaScript in
lumen2/, and the
language is defined in its own spec.
It has its own playground, with every view this part describes.
Here is what the checker infers for five small functions. Nothing in the source mentions an effect:
Press “Infer”. Then untick “grant random”: the program is rejected before it runs, at the call responsible. Try adding println inside area and watch its type change.
Press “Infer”.
The part after ! is the function's effect. area has none, so it is pure: calling it
can do nothing except return a number. average has fail, because the list may be empty
and the division may then stop the program. shout has output, roll has
random, and main has the union of everything it calls.
twice is the interesting one: fn(fn(a) -> a ! e, a) -> a ! e. Just as
a stands for any type, e stands for any set of effects. The type says that
twice does exactly what its argument does and nothing more. So twice(area, 2) is pure,
while twice applied to a function that prints, prints. The prelude's map, fold and
filter have types of the same shape, so a pipeline of pure functions stays pure.
Background · Effect types
The checker extends the unification of chapter 3 to sets of effects. An effect set is written as a list of
labels, optionally followed by a variable that stands for “and possibly more”, so {output | e}
means “output, and whatever e turns out to be”. Unifying two such rows matches the labels
they share and lets each variable absorb the labels only the other side has. Inference stays fully automatic,
and every function still gets its most general type. The technique is called row polymorphism. Lumen 2's
version follows Koka, a research language from Microsoft Research.
Three runtime errors are deliberately not effects: integer overflow, running out of memory, and a string too
long. Any arithmetic can overflow, so tracking it would put fail on nearly every function and make
the effect meaningless. Overflow still never produces a wrong answer, because integers are 64 bits wide and
every operation checks.
An effect in a type is a statement about the code. A capability is a decision about running it:
whoever runs a program grants main the effects it may use. The command line grants
output by default, and --allow random adds randomness. A program that would use an
effect it was not granted is rejected before it runs, with the error placed on the call responsible. The
ungranted program in the demo is refused at roll(), not at some library function three calls
deeper.
The clock and random numbers come from a host that the interpreter and the compiled code share, so a seeded run is reproducible. That matters for testing. The fuzzer can generate programs that read the clock and roll dice, and still demand that the interpreter and the compiled code print the same thing.
Lumen compared values structurally, field by field. Lumen 2 adds traits. A user's impl Ord
replaces structural ordering wherever its type is compared, including inside lists and options, and
show is derived for every type without functions in it. Methods are resolved at compile time, so a
trait costs nothing at run time. The checker infers trait requirements too. A tree insert gets
fn(Tree<a>, a) -> Tree<a> where a: Ord, and sorting a list of functions is a compile
error, where in Lumen it was a runtime error.
Properties are part of the language:
property reverse_twice(xs: List<Int>) { reverse(reverse(xs)) == xs }
property sort_is_sorted(xs: List<Int>) { sorted(sort(xs)) }
lumen2 test generates inputs from the parameter types, small ones first, plus integer edge cases.
It shrinks any failure to a minimal counterexample and prints it as Lumen source. Every case runs in the
interpreter and is then replayed in compiled code, which must agree, so each property is also a test of the
compiler. The playground's Properties tab runs them, including two that are false on purpose.
16 · Part five
array_get(a, i) fails when i is out of range. In Lumen, every call checks, and a
function that reads an array looks the same as one that might crash. In Lumen 2, array_get has the
type fn(Array<a>, Int) -> a ! fail, but the fail applies only at calls the
checker cannot prove safe. This function has no fail in its inferred type:
fn safe_get(a, i) { if 0 <= i && i < array_length(a) { Some(array_get(a, i)) } else { None } }
safe_get : fn(Array<a>, Int) -> Option<a>
Inside the if, the condition holds, and the condition is exactly what the access needs. The
checker turns that observation into a proof that a machine checks.
The checker walks each function and keeps a list of facts that hold at each point. Facts come from the
conditions of the ifs on the current path, from refined parameters, from the results of refined
functions, and from operations that have already succeeded: after array_get(a, i) returns, the
index was in bounds. It also knows that an array's length is never negative. Each partial operation becomes a
proof obligation: do the facts imply that the operation is safe? For the access in
safe_get, with n standing for array_length(a), the obligation is
0 ≤ n, 0 ≤ i, i < n ⟹ 0 ≤ i and i < n
An implication holds when its premises and the negation of its conclusion can't all be true at once. So the
checker asks a SAT solver, the kind of program Part four explained, whether there are integers that satisfy
the facts and violate the goal. Here that means 0 ≤ n, 0 ≤ i, i < n,
and also i < 0 or i ≥ n. If the solver proves that unsatisfiable, the access is
safe.
A SAT solver knows only true and false, so the integers have to become booleans. This is called
bit-blasting. Each integer variable becomes a vector of boolean variables, one per bit, in two's
complement. Each operation becomes a circuit written as clauses, in the style of chapter 11. An addition is a
chain of full adders, where each output bit and carry is a few clauses over the input bits. A comparison
a < b becomes a − b < 0: a subtraction, then a look at the sign bit. The vectors are about 66 bits wide, wide enough that no sum of
64-bit values in an obligation can overflow, so the bit-level arithmetic agrees with real integer arithmetic.
Even this small obligation comes to 2,801 clauses.
Then everything from Part four applies again, with new code. A CDCL solver,
lumen2/compiler/32-sat.lm, refutes
the formula and writes a DRUP proof. A separate RUP checker,
lumen2/compiler/33-rup.lm, checks
that proof before the operation is treated as safe. (Both were JavaScript at first, like the rest of the
compiler until chapter 20.) The two share no code with each other or with Lumen's
solver and checker. For safe_get, the proof is the one-line proof 0 from chapter 13:
unit propagation alone reaches the contradiction, so the solver learns nothing (zero lemmas).
When the formula is satisfiable, the solver's assignment is a counterexample. The checker then tries again with the numbers restricted to small values, so the counterexample it reports is easy to read.
The checker does not infer facts about a function's callers or loop invariants. A recursive function that walks an array needs to say what it relies on, and a refinement type says it:
fn sum_from(a: Array<Int>, i: {i: Int | 0 <= i}, acc: Int) -> Int {
if i < array_length(a) { sum_from(a, i + 1, acc + array_get(a, i)) } else { acc }
}
{i: Int | 0 <= i} is an Int that is known to be non-negative. Inside the
function it is a fact, so the access is safe: 0 ≤ i comes from the type, and
i < array_length(a) from the if. At every call, it is an obligation. The recursive
call passes i + 1, and 0 ≤ i implies 0 ≤ i + 1. A caller that passes
0 is fine, and a caller that passes -1 gets a compile error. A result can be refined
too: -> {r: Int | 0 <= r && r < n} is proved at the end of the function's body and
assumed by every caller. A refinement that cannot be proved is always an error. An access that cannot be
proved just keeps fail in its function's type.
Press “Check”. Every obligation is a SAT refutation, checked by the separate checker. Then break something: change < to <= in safe_get, call sum_from(a, -1, 0), or change n == 0 to n == 1 in average.
Press “Check”.
A wrong proof would be worse than no proof, because the compiler drops the run-time check for a proved
access. So the proofs are checked twice. Each refutation passes the RUP checker before the compiler uses it.
And the reference interpreter re-checks every proved fact as the program runs, while the compiled code does not.
If a proof were wrong, the two would disagree on some program, and the fuzzer would see it. Two of the planted
bugs in chapter 18 test exactly this: a checker that assumes an if's condition in its
else branch too, and an adder circuit that drops its carry. The run-time re-check catches both. It
has also caught two real mistakes in the checker, described in chapter 24.
How far does this go? Chapter 17 ends with a complete program that the checker proves cannot stop with an error.
A fact about an integer or a length is not enough for code that keeps indices in arrays: a graph's adjacency lists, a heap of positions, a SAT solver's clauses. Each holds numbers that are later used to index another array. So a refinement can also describe every element of an array:
fn sum_at(a: Array<Int>, ix: Array<{k: Int | 0 <= k && k < array_length(a)}>, i: {i: Int | 0 <= i}, acc: Int) -> Int {
if i < array_length(ix) { sum_at(a, ix, i + 1, acc + array_get(a, array_get(ix, i))) } else { acc }
}
Inside sum_at, every element of ix is assumed to be a valid index into
a, so the inner access is proved. At each call, the checker must prove it for every element the
caller could have put in ix. To do that, it tracks what each array's elements can be:
array_make(n, x) holds only x, array_push(a, x) holds the elements of
a or x, and after an if the array holds the elements of the branch that
ran. These refinements nest, so an array of clauses can say that each clause has at least two literals and
that each literal is in range.
The checker still has clear limits. Its facts are linear arithmetic over integers and array lengths, plus
one fact about every element of an array. It knows nothing about list lengths, it cannot state a fact about
particular positions in an array, and it never invents an invariant. In the SAT solver of chapter 19, it proves
19 of the 20 divisions safe, and all of the input parser's indexing. It does not prove the 27 accesses to the
solver's state arrays. Those arrays sit inside a record, whose fields cannot be refined, and each mixes several
kinds of number: the clause array holds each clause's length followed by its literals. The fact that would make
an access safe, "the number after a clause's start is a literal", is about a position, not about every
element. Those accesses keep their run-time checks, and the solver's functions have fail in their
types. Chapter 19 shows what I did instead.
17 · Part five
Lumen's copying collector, from chapter 4, finds live objects by following pointers from the roots, and it needs the shadow stack to know where the roots are. Lumen 2 has no collector. Every heap object carries a count of the references to it, and it is freed the moment the count reaches zero.
Background · Reference counting
With reference counting, copying a pointer increments the count of the object it points to, and discarding one decrements it. At zero, the object is freed, and the counts of everything it points to are decremented in turn. Memory is reclaimed promptly and without pauses. It has two classic costs. The counting itself is work on every copy, and objects that point to each other in a cycle keep each other's counts above zero forever. In Lumen 2 the second can't happen: values are immutable, so a value can only point to values that existed before it, and no cycle can form.
The first cost is where the compiler comes in. Lumen 2 follows Perceus, an algorithm published in 2021 by
Microsoft Research for the Koka language. The compiler, not a runtime library, decides exactly where each count
changes. The rule is ownership. Each variable holds one reference. The last use of a variable hands that
reference on, for example to the function it is passed to, at no cost. Any earlier use that hands a reference
on must first make a new one, with dup. A variable that is dead releases its reference with
drop immediately after its last use, not at the end of its scope, so memory is freed at the
earliest possible moment.
The real payoff comes from knowing when a count is about to hit zero. Here is a tree insert after reference
counting, slightly simplified from what lumen2 ir prints:
fn insert<Int>(t, x) {
if is Leaf(t) {
drop t
ret Node(Leaf, x, Leaf)
} else {
let l = field t.0 // read the fields, taking a reference to each
let y = field t.1
let r = field t.2
if x < y {
let ru = drop-reuse t // release t; if that was the last reference,
let l2 = insert<Int>(l, x) // keep its cell instead of freeing it
ret Node@ru(l2, y, r) // build the new node in that cell
} else if x > y { ... } else {
drop l
drop r
ret t
}
}
}
t_101, b_109 and so on, and binds every
test and constant to a variable of its own.After t is taken apart, the code releases it and then builds a node of the same size. The
compiler pairs the two. drop-reuse decrements the count, and if t was the only
reference, it keeps the cell instead of freeing it. Node@ru then writes the new node into that
cell. When the tree is not shared, inserting into it allocates exactly one new node, the leaf, and rebuilds
the path to it in place. When the tree is shared, for example because the program also keeps the old version,
drop-reuse just decrements, and the path is copied, which is what keeps the old version intact.
The source code is the same in both cases. The decision happens at run time and costs one comparison.
The same rule applies to arrays. array_set on an array that nothing else refers to writes in
place, and on a shared array it copies first. Values never change from the program's point of view, yet a
program that holds its data uniquely pays the cost of mutation, not of copying. Nothing visible decides this:
it follows from whether the program uses the old value again.
Run it. Building the list allocates 100,000 cells, and reverse allocates none: xs is not used again, so each cell is reused for the reversed list. Then change the last line to println(show(length(ys) + length(xs))) and run again. Now xs is still needed after the reverse, so the reverse must copy.
Press “Compile and run”.
Two further optimizations matter for speed. A parameter that a function only reads, never stores or
passes on, is borrowed. The caller keeps its reference for the duration of the call, so neither side
counts anything. The compiler infers which parameters qualify. And when a function takes apart a cell that
nothing else refers to, it can move the fields out (unpack) instead of taking a new reference
to each field and then releasing the cell. Chapter 19 shows how much each of these was worth.
Reference counting fails quietly. Freeing too early usually works anyway, because freed memory still holds its old contents until something else is allocated there. Freeing too late is just a leak. So the test harness makes both loud. Every compiled run that finishes must report zero live objects, which catches leaks. And a paranoid mode never reuses freed memory and stops the program on any access to a freed object. The fuzzer runs every program four ways: interpreted, compiled, compiled in paranoid mode, and compiled without reuse. All four must print the same output.
The last two chapters meet in one program. The heapsort below has no mutation in it: every function returns a
new array. Its refinement types state each index's range, and that every function returns an array of the same
length as the one it was given. The checker proves every access in bounds, so no function in the program has
fail in its type, not even main: this program cannot stop with an error, short of
running out of memory. And because the array is never shared, every array_set updates it in place,
so sorting a million numbers allocates the array once and never copies it. The whole run makes 12
allocations, and the array is one of them.
Press the button: the checker proves every access (a few seconds), then the program sorts a million numbers. Look at the allocation count and at main's type. Then break it: in sift, change l >= n to l > n. The checker finds the index that can run off the end, and fail spreads up to main.
Press “Prove, compile and run”.
The same heapsort in the original Lumen, which mutates its array in place, takes 1.0 seconds (0.44 with
-O) where this one takes 0.3, and a hand-written JavaScript version sorts in about 0.25. Writing
this program taught the checker two things it now knows: the range of a quotient or remainder by a constant,
and that what a branch learned still holds after the branch ends. The playground has it with three other
showcase programs.
18 · Part five
Part two tested Lumen's compiler on random programs, and Lumen 2 is tested the same way. But a test can only cover the programs it tries. Lumen 2 adds a second kind of check that runs on every compile, for every program. The compiler's output is re-checked by independent code before it is used, and the compile fails if a check fails. This is a light form of an idea called translation validation: instead of proving the compiler correct for all programs, check its result for this one.
There are two checkers, in
lumen2/compiler/44-certify.lm,
plus the proof checker and the engine's own validation of the final WebAssembly:
These checkers earned their place while I was still writing the compiler. One optimization lets a function read a field without taking a reference to it, as long as the cell it came from stays alive. My first two versions got the liveness wrong: they released the cell just before the field was read, once in the middle of an instruction and once at the field read itself. On most programs, nothing visible would have happened, because freed memory still holds its old contents. The ownership checker rejected both versions on the first compile. One of the two mistakes is now a planted bug.
As in Part two, planted bugs check the checks. There were 24 when this was written (27 now, with the three that floats added), spread across the compiler, the refinement checker and the SAT solver, and every one is caught. Seven are caught at compile time by a certificate checker, before any program runs. Pick one and compile:
Each choice compiles this program with one deliberate bug in the compiler. The certificate checkers reject every one of them before the program runs. Edit the program too, if you like.
The other seventeen planted bugs produce code that passes every certificate, so they need the dynamic checks to catch them. They include reusing a cell that is shared, updating a shared array in place, dropping the overflow check on addition, an off-by-one in the overflow bound for multiplication by a constant, and applying a rewrite rule from chapter 19 without checking its side condition. The differential runs catch them, as do the leak check and the interpreter's run-time re-check of proofs. Each is caught by one of the first 142 generated programs. With every feature in place, 3,000 generated programs ran with no disagreement, and CI runs 1,000 fresh ones on every push. Fresh programs have found two false proofs in the refinement checker (chapter 24).
19 · Part five
The last test of the new language was to prove S(4) = 44 again. Lumen's solver from chapter 12 keeps its state in arrays and changes them in place. Lumen 2 has no mutation at all. So how do you write a SAT solver, which updates its assignment, watch lists and activity scores constantly?
You thread the state. The solver's whole state is one record of arrays and counters. Every function takes
the record and returns a new one, and the code reads like a chain of updates:
let s = assign(s, lit, reason). Semantically, each step builds a new record. But the record is
never shared: each version is used once, to make the next. So every array_set writes in place, and
every new record reuses the cell of the old one. The code is pure, and it runs with the cost of mutation. The
compiler decides this, the ownership checker confirms it on every compile, and the program itself says nothing
about memory.
I ported Lumen's solver decision for decision. It uses the same order for visiting watch lists, the same heap of variables, the same integer activity scores, the same restarts and the same learning. The watch lists became linked lists inside one flat array, with new entries appended at the tail, so their order matches Lumen's exactly. The result is two programs, in two languages, compiled by two different compilers, that make the same choices. On S(4) they print the same output byte for byte: 27,684 conflicts for the split of 1 to 44, and the same 255,663-step refutation of 1 to 45, about 22 MB. A difference anywhere in those 22 MB would have pointed to a bug in one of the two compilers. The proof was then checked again, by Lumen 2's own checker.
The encoder and the solver are Lumen 2 programs, compiled here. The refutation is checked by lumen2/src/rup.js. Then Lumen's imperative solver runs on the same formulas, and the outputs are compared byte for byte. S(3) takes a second or two. The split of 1 to 44 takes a few seconds per solver; the full S(4) refutation, about five minutes, is left to node lumen2/proofs/prove-schur.js 4 44 and to CI.
| Write both formulas with the Lumen 2 encoder; compare with a second encoder | – |
| Find a split of 1 to n with the Lumen 2 solver; check every group is sum-free | – |
| Refute 1 to n+1 with the Lumen 2 solver | – |
| Check every step of the refutation independently | – |
| Run Lumen's solver on the same formulas; compare the outputs | – |
The first compiled version took 19.0 seconds to find the split of 1 to 44. Lumen took 2.6. Five compiler optimizations closed the gap. Each was checked by the certificate checkers and the fuzzer, and each came with a new planted bug:
| Optimization | Split of 1 to 44 |
|---|---|
| none | 19.0 s |
| borrowed parameters: a parameter that is only read costs no reference counting | 12.8 s |
| moving fields: taking apart a unique record moves its fields out | 5.1 s |
| inlining small functions | 4.5 s |
| checked arithmetic and array reads inline in the wasm | 2.9 s |
| simplification: a chain of record updates becomes one unpack and one constructor | 2.8 s |
That run shared the machine with the test suite. On a quiet machine the split takes 2.2 seconds. Here are both solvers side by side, single runs in Node on the same machine:
| Lumen 2 | Lumen, -O | |
|---|---|---|
| split of 1 to 44 | 2.2 s | 2.6 s |
| refutation of 1 to 45 | 108.8 s | 93.1 s |
| proof check | 170 s | 158 s |
So a pure solver, with every update written as a new value, is faster than the imperative one on the split and 17% slower on the refutation. That depends entirely on the compiler seeing that the state is never shared. One bug showed how much: my first borrow inference marked the record parameter of a setter as borrowed, because the setter never consumes the record itself, only its fields. A borrowed record can't be updated in place, so every update copied all its arrays, and the split ran for more than ten minutes instead of 19 seconds. Nothing was wrong except the speed. Consuming a field now counts as consuming the record. CI re-runs the whole Lumen 2 proof of S(4) = 44 on every push, next to Lumen's.
I also rebuilt chapter 8's superoptimizer for Lumen 2, with new code: it searches the wasm Lumen 2 emits for windows of up to seven instructions with a cheaper equivalent, and proves each one with Lumen 2's own solver and checker. One improvement made the difference. A rule found with concrete constants is generalized: the constants become symbols, and the search looks for the weakest side condition under which the rule still holds. That is how it found its best rule, in the overflow check for multiplying by a constant, which asks whether the other operand lies outside a range:
x < K0 || x > K1 ⟹ (x − K0) >u (K1 − K0) when K0 ≤ K1
This is the classic unsigned range-check trick, proved here with 17,195 checked lemmas, and it saves two
instructions every time. With the actual constants of one program, the search first found a different
sequence that works only for the bounds of x * 2. Searching again with the constants varied, keeping
their signs and order, found the general form. In all, it found 19 rules.
They barely matter, and the reason is worth knowing. The rules remove 1.2% of the instructions in the SAT solver and leave its running time unchanged within measurement noise. Lumen's superoptimizer found 40 rules because most of its finds cleaned up after tagged 31-bit integers. Lumen 2's integers are plain 64-bit values, so its code generator leaves little to clean up, and the engine's own optimizing compiler already makes rewrites like these. The rules stay in, because they are proved and make the binaries smaller, and a planted bug that ignores their side conditions is caught by the first generated program.
The refutation above is checked by lumen2/src/rup.js, a JavaScript program. A stronger check
is a checker written in Lumen 2 that its own compiler proves free of run-time errors. That is
lumen2/proofs/rup.lm.
Like the solver, it passes its state from function to function, but it keeps each kind of data in its own
array, so that every invariant is a fact about every element:
vals: {v: Array<Int> | array_length(v) == 2 * n + 2}
db: Array<{c: Array<{x: Int | 2 <= x && x < 2 * n + 2}> | array_length(c) >= 2}>
w: {ws: Array<Array<{k: Int | 0 <= k && k < array_length(db)}>> | array_length(ws) == 2 * n + 2}
trail: Array<{x: Int | 2 <= x && x < 2 * n + 2}>
vals has one entry per literal. Each clause in db is an array of at least two
literal codes, each a valid index into vals. Each watch list in w holds clause numbers
below the number of clauses. With these types, the checker proves all 360 of the program's obligations in about
16 seconds, and no function in it has fail in its type. Input that would break an invariant, such as
a literal larger than the number of variables, is reported as an error rather than trusted.
The language needed two additions for it. One was element refinements (chapter 16). The other was
reading input a line at a time: the proof is 22.6 MB, a Lumen 2 string holds at most 16 MB, so
read_input could not hold it, and a new builtin, read_line, reads one line at a time.
The program needed one fix. The first version took fifty times as long as the JavaScript checker. When a clause
changed, it wrote array_set(db, k, c2) after an earlier line had already made a new
db from the old one. The old one was still needed, so every visit to a clause copied the whole
clause database. Nothing was wrong, only slow, as with the borrow inference above. Taking the clause out of
db while it changes, and leaving a two-literal placeholder in its slot so that the invariant
still holds, made the updates happen in place again.
On S(4) it checks all 255,663 lemmas in 529 seconds, on a machine busy with other work, where
src/rup.js took 304. On smaller proofs it takes 1.5 to 2 times as long as the JavaScript checker.
CI runs it on every push, compiled by the self-hosted compiler of chapter 20, so the WebAssembly that checks the
proof comes from that compiler's code generator rather than the reference compiler's.
20 · Part five
Chapter 7 ended Lumen's story with a compiler for the language written in the language, and Lumen 2 ends the
same way. lumen2c.lm
is about 2,800 lines of Lumen 2. It reads a program on standard input and writes a WebAssembly module on standard
output, with the same stages as the reference compiler: a lexer and parser, type inference with traits and
derived Show, monomorphization, lowering, Perceus reference counting, code generation and a binary
encoder. It emits the same runtime conventions, so its modules run on the same host and pass the same leak
check.
A type checker is usually built around mutable state: a substitution that unification updates, tables
that grow as names are declared. Lumen 2 has none, so lumen2c uses the SAT solver's technique.
The substitution is an array threaded through every function of the checker, and since no two parts of the
compiler ever hold it at once, every update happens in place. Tables are balanced binary trees, and the
code generator builds its output as lists that it joins once at the end. The compiler is also the largest
test of Perceus so far. Compiling itself makes about five million allocations and frees every one of them.
Generalization needs the call graph's strongly connected components, found with Tarjan's algorithm. That algorithm is usually written with a mutable stack and mutable index tables. Here its state is a value passed along the depth-first search, and it works the same way.
The test is the one from chapter 7. The reference compiler builds stage 1. Stage 1 compiles
lumen2c.lm into stage 2, and stage 2 compiles it into stage 3. If the compiler is right, stages 2
and 3 are the same bytes: the compiler, compiled by itself, reproduces itself. Stage 1 differs from them,
because it comes from a different compiler with different optimizations. The demo runs all three stages in
this tab:
The reference compiler builds the compiler, which then compiles itself twice. This takes a few seconds.
Stage 1: the reference compiler compiles lumen2c.lm | – |
Stage 2: stage 1 compiles lumen2c.lm | – |
Stage 3: stage 2 compiles lumen2c.lm | – |
Stages 2 and 3 are byte-identical, 288,477 bytes each. Each self-compilation takes under a second, and nothing leaks. A fixed point alone could hide a bug that reproduces itself, for example one that miscompiles multiplication everywhere, including in the compiler's own code. So the modules from stages 1 and 2 were also compared with the reference interpreter on every example, the SAT solver, the proof checker and 1,000 generated programs. Every one printed the same output and stopped with the same error. CI repeats the bootstrap and a smaller version of that comparison on every push.
The comparison found one bug, in a trait method called on a type that inference leaves undetermined, and writing the compiler found one in the reference compiler, whose lowering ran out of stack on a list literal of about 800 elements.
This compiler checks types but not effects or refinements, keeps every run-time check, and makes none of the optimizations of chapter 19 except tail calls, so the SAT solver it compiles takes 19.6 seconds where the reference compiler's build takes 2.4. It leans on the reference compiler, which was JavaScript, to reject bad programs.
That reference compiler was about 5,500 lines of JavaScript in lumen2/src. The last step was to
make Lumen 2's real compiler a Lumen 2 program, every pass of it, and then delete the JavaScript one. The result is
lumen2/compiler/:
about 8,200 lines in 25 files, one per pass, and a 1.5 MB WebAssembly module that is that source compiled by
itself.
A port that is about the same as the original never has a moment when it is done, so I made a rule that gave it one: the port's output must be identical to the original's. That covers every error message and its position, every inferred type, every proof obligation with its lemma and clause counts, the counterexamples, the intermediate code after each pass, the certificates' statistics, and every byte of the WebAssembly. Each pass got a dump in a canonical text form, the same in both compilers, and was compared on a corpus before the next pass was written. The corpus was every Lumen 2 program in the repository (the port's own source among them), 200 generated programs, 600 programs broken on purpose, which must fail with the same message at the same place, and the 270 programs the test suite compiles.
Byte-identical output means reproducing the original's accidents, not just its algorithms. The SAT solver
ranks variables by activities that JavaScript stores as floating-point numbers, and every decision it makes
follows a comparison between two of them. Lumen 2 had no floating point then, so the port computes IEEE 754 doubles
exactly with integers: a mantissa and an exponent, rounded to nearest with ties to even, as the hardware does.
A test compares it with the engine's doubles on thousands of random additions and multiplications. JavaScript's
maps iterate in insertion order, and the order of drops, of captured variables and of the per-type functions in
the module all follow from that, so the port keeps ordered lists wherever the original had a map. Positions
differ too: JavaScript counts UTF-16 units and Lumen 2 counts bytes, so the compiler reports byte offsets
and the host turns them into characters. The comparison also found a bug in
the original: a refined let inside a lambda crashed it, and both compilers were fixed the same way.
The first complete port proved obligations five to thirty times more slowly than the original. The profile
pointed at closures allocated in the solver's inner loops, a general bignum division in the exact multiplication
of doubles, clauses kept in an array of arrays, and a quadratic scan for duplicate literals. With those fixed,
examples/refine.lm checks in 1.9 seconds, against 1.1 for the JavaScript compiler. Each program now
compiles in a fresh instance, so the compiler asks its host about queries it proved before: proofs are
deterministic, so the answers change only the time taken.
The JavaScript compiler built the first lumen2c.wasm from the port's source. That module
compiled the same source to the same 1,513,271 bytes, and compiling it once more gave the same bytes again.
After that the JavaScript compiler was deleted: 3,152 lines, with 510 more moved to the superoptimizer, which
still uses its own copy of the SAT solver, the peephole pass and the module encoder. Every change to the
compiler since has been built by the previous build, and CI checks on every push that the committed build is
the fixed point of its source. Here it is in this tab:
Fetches lumen2c.wasm and the compiler's source, compiles the source with it, and compares the result with the module that did the compiling. It takes about 20 seconds in Node, and usually a little longer in a browser tab.
The compiler, lumen2c.wasm | – |
| What it writes when it compiles its own source | – |
What stays in JavaScript is deliberate. The reference interpreter, with its own front end, is the second
implementation that compiled code is compared with, and it is useful only because it shares nothing with the
compiler. The host that runs modules is a page of glue. src/rup.js checks the compiler's proofs
again from outside. Everything that decides what a program means, what it may do and what code it becomes is
now written in Lumen 2.
21 · Part five
With the compiler written in itself, I suggested the usual next step for a compiler, and was told: “Don't think in terms of compiler - think in terms of what language can achieve and how fast it can solve complex problems.” Then came a sharper question: “do we need to bypass webassembly? can webassembly ever be faster than c/rust?” That one could be measured, so I measured it first.
I wrote four programs twice, once in Lumen 2 and once in C, with the same algorithm in both:
fannkuch-redux, which permutes small arrays and counts prefix reversals; binary trees, which builds and frees
millions of tree nodes; N-queens, a backtracking search; and the edit distance between two 30,000-element
sequences, a dynamic program over two rows. The C was compiled natively with cc -O2, and also by
clang to WebAssembly, which ran in the same Node as Lumen 2. Compiled to WebAssembly, the C took between 1.0 and
1.26 times as long as natively. It is rarely faster. The native build can use every instruction the processor
has, while the WebAssembly build is limited to a portable subset, compiled by an engine that has less time to
optimize. But WebAssembly costs little, and the rest of the gap between Lumen 2 and C belonged to Lumen 2's
compiler. So the answer was no: the work was in the compiler, not in getting around WebAssembly.
One measurement nearly misled me. V8 first compiles WebAssembly with a quick baseline compiler, and swaps in
optimized code when a function is called again. A C program spends its whole run inside one call to
main, so by default it never leaves the baseline code. Measured that way, C compiled to
WebAssembly looked 1.6 times slower on fannkuch-redux than it is, and Lumen 2, whose loops are small recursive
functions that are optimized after a few calls, beat it. The benchmark runner now asks V8 to
optimize everything before the clock starts.
| program | C | C, WebAssembly | Lumen 2, before | Lumen 2, now | Lumen 2 / C |
|---|---|---|---|---|---|
| fannkuch-redux, n = 11 | 3.10 s | 3.10 s | 10.3 s | 4.06 s | 1.3× |
| binary trees, depth 18 | 1.18 s | 1.39 s | 1.80 s | 1.74 s | 1.5× |
| N-queens, n = 13 | 0.62 s | 0.66 s | 2.77 s | 1.21 s | 1.9× |
| edit distance, n = 30,000 | 0.96 s | 1.21 s | 9.97 s | 2.78 s | 2.9× |
Best of three runs on one core of a 2.1 GHz Xeon, Node 22, clang 18. “Before” is the same
Lumen 2 source compiled by the compiler as it was at the end of chapter 20. Every version of a program prints
the same output, and lumen2/bench/run.js checks that it does.
The Lumen 2 programs are ordinary Lumen 2: nothing in them mutates anything, and every loop is a recursive function. In fannkuch-redux and edit distance, refinement types prove every array access in bounds. Nine changes to the compiler account for the difference between the two Lumen 2 columns, and each one came from reading the WebAssembly that it wrote for an inner loop.
Tuples on the heap. My first version of fannkuch-redux made 120 million allocations, because its helpers returned pairs and every pair was a heap object. A function that returns a tuple now returns its fields as several WebAssembly values, and a tuple built and taken apart in one function stays in local variables. The same program made 24 allocations after that.
Proved, but still checked. Chapter 16's checker proves array accesses in bounds and takes away their
fail effect, but the compiled code still tested every index. A proved operation now has no
run-time check. Paranoid mode keeps the checks, so if a proof were wrong, the differential tests would see the
two modes disagree.
A test on every update. An array_set writes in place when nothing else refers to the
array, which means reading its reference count before every write. In a loop that updates the same array over
and over, the answer is known: array_set returns an array that nothing else refers to, and it stays
that way until something takes a second reference to it. The code generator now follows that along each path.
Across calls, it computes which parameters receive such an array from every caller, and which functions return
one on every path. In fannkuch-redux and edit distance, no update in an inner loop tests anything. A new test
pins down the cases where such reasoning goes wrong: the same array passed twice to one call, an array kept in
a list, a tuple or a closure, and an array read out of another array.
A list walk that wasn't free. N-queens checks each square against a list of the queens placed so far. The function that walks the list only reads it, yet it was paying for two reference count updates per element. Borrow inference (chapter 17) gave up on a parameter whenever a recursive tail call passed it something the function did not own, and the list's tail, read out of the borrowed list, counted as that. The rule now looks at where the value came from, and the walk touches no counts at all.
Branches the processor cannot predict. Edit distance takes the minimum of three numbers for every
cell. Compiled as nested ifs on random data, every comparison was a coin toss for the branch
predictor. C compilers use a conditional move instead. An if whose branches only compare values now
becomes WebAssembly's select, which V8 turns into a conditional move, and that halved the time.
The other changes were smaller: array_set and constructor tag tests inline, self tail calls as
jumps, and arithmetic already done on the same path not done again.
Beyond what WebAssembly itself costs, the remaining gap has three causes. Lumen 2's integers never wrap, so each addition of two array elements checks for overflow, which C does not; the checker could prove some of those checks unnecessary, but it does not yet try. The N-queens list allocates a cell for every square tried, where C overwrites one array entry. And the allocator keeps the counts that the leak check reads.
All of that ran on one core, so the next request was: “let's test the parallelism part as well?” Lumen 2's
types already say which functions can do input or output, so the language needed just one builtin. The call
par_map(xs, f) gives the array of f applied to each element of xs, and the
compiled code computes the elements on every core at once. The checker accepts the call only when
f cannot read input, write output, read the clock or use randomness. It may fail; when calls
fail, par_map stops with the error of the first failing element in array order, the same error a
sequential map would stop with. Nothing the program prints can depend on how the threads were scheduled.
The run-time side was harder. Each thread is an instance of the program's WebAssembly module, and all of them
share one memory. Each thread takes chunks of the heap with an atomic add and keeps free lists of its own.
Reference counting needed one argument. A count above 1 can be changed by several threads at once, so while a
par_map runs, those counts change by atomic operations. A count of exactly 1 belongs to the thread
holding that reference, and no other thread can reach the object without a counted reference of its own, so
freeing, reuse and in-place updates need no atomics. The tests run each parallel program on one to four threads
and compare it with the interpreter, and the fuzzer now generates par_map calls, with functions
that can only fail.
| program, split into | C, 1 thread | C, 4 threads | Lumen 2, 1 thread | Lumen 2, 4 threads |
|---|---|---|---|---|
| fannkuch-redux, n = 11, 990 blocks of permutations | 2.47 s | 0.67 s | 3.79 s | 0.95 s |
| binary trees, depth 18, the 8 depths | 1.14 s | 0.78 s | 1.74 s | 0.61 s |
| N-queens, n = 13, 132 placements of two queens | 0.48 s | 0.16 s | 1.29 s | 0.42 s |
The C versions split the same work with OpenMP. Best of three on the same 4-core machine; the Lumen 2 times on threads include starting the threads.
On four cores, Lumen 2 ran 2.8 to 4 times faster than on one, and faster than C on one core. It also beat C
on four cores at binary trees, where every thread allocates millions of nodes: each Lumen 2 thread allocates
from memory of its own, while the C threads share malloc.
The hardest problem in this project is still S(4) = 44 (chapter 19). Its slowest step is the refutation of
1..45, which took 153 seconds on one core, and checking that refutation took 316 more. Cube and conquer splits
the formula into parts that can be refuted separately. Fixing the groups of 3, 4, 5 and 6 (1 and 2 are placed
already) gives 256 cubes, and par_map refutes them on every core, each with the unchanged solver.
The solver cannot print inside par_map, so each cube returns its learnt clauses as data, and the
program prints one refutation of the whole formula. That refutation contains every cube's clauses, each with
the cube's negation added. Then, going up the split, it contains the negation of each partial cube, down to the
empty clause. The same independent checker accepts it. The refutation took 4.5 seconds and the check 10, and the
whole proof 22 seconds instead of 8 minutes. On one thread, the same 256 cubes take 11.6 seconds.
That last number matters, because most of the gain did not come from the cores. The solver never forgets a clause it has learnt, and unit propagation over 255,000 of them is slow. Each of 256 small searches keeps a small database instead. The checker needed the same remedy: without deletions, a refutation from 64 cubes took 486 seconds to check. After each cube, its clauses are deleted, a standard part of the DRUP format that the checker now supports. The four cores then added a factor of 3.7 to the solving, and the proof runs in CI on every push, next to the sequential one.
Later, asked “What next in this project?”, I named the limitation that every section had come to end on:
Lumen 2 had no floating point. The one real design decision was what to do about infinity and NaN. In C,
JavaScript or Python, a division by zero or an overflow quietly produces one, and a NaN then compares unequal to
everything, itself included, and spreads through every result it touches. Lumen 2 already refused to let
integers wrap silently, so a Float follows the same rule: it is an IEEE 754 double that is always
finite. An operation whose result would be infinite stops the program with float overflow, and
x / 0.0 stops with division by zero. With finite operands there is then no way to make
a NaN, so equality, ordering and sorting work on floats as on any other type, and a result is the same bits on
every machine and every thread.
fn mean(xs: List<Float>) -> Float { fold(xs, 0.0, |acc, x| acc + x) / int_to_float(length(xs)) }
mean([1.5, 2.5, 3.0]) // 2.3333333333333335
0.1 + 0.2 // 0.30000000000000004
1e308 * 10.0 // runtime error: float overflow
Arithmetic takes two integers or two floats, never one of each, and an operator whose operands are still
unknown waits until its top-level function is finished; one still unknown then is an integer, so every program
written before floats keeps its types. The compiler, which uses no floats itself, rounds a literal such as
0.1 to the nearest double exactly, with the bignums its refinement checker already had. On 600
literals, ties between adjacent doubles and subnormals among them, it agrees with JavaScript's
Number on every bit.
On the two usual benchmarks of floating point, Lumen 2 takes 2.8 and 3.5 times as long as C:
| program | C | C, WebAssembly | Lumen 2 | Lumen 2 / C |
|---|---|---|---|---|
| n-body, 5,000,000 steps | 0.25 s | 0.31 s | 0.70 s | 2.8× |
| spectral norm, n = 3,000 | 0.47 s | 0.47 s | 1.63 s | 3.5× |
Best of three on one core of the same machine. Each Lumen 2 program does the same floating-point operations as the C one, in the same order, and prints the same digits: −0.169075164 and −0.169087605 for n-body, the published reference values.
The first version tested every float result for being finite. But an infinity or a NaN stays one through
+, - and *, so a result whose only use is the next such operation needs no
test of its own: the later test fails exactly when the earlier one would have. In
dx * dx + dy * dy + dz * dz only the last addition is tested now, and n-body went from 0.75 to 0.55
seconds. Spectral norm gained from integers instead: a product of two integers that fit in 32 bits cannot
overflow, so it needs no 64-bit division to check, and it went from 2.2 to 1.6 seconds.
A parallel sum of floats is where C and Lumen 2 differ most. Floating-point addition does not associate, so
the answer depends on how the terms are grouped, and with OpenMP's reduction the grouping depends on
the number of threads:
| threads | C, OpenMP reduction | Lumen 2, par_map |
|---|---|---|
| 1 | 0.69314713056010635 | 0.6931471305599604 |
| 2 | 0.69314713056006005 | 0.6931471305599604 |
| 3 | 0.69314713056002475 | 0.6931471305599604 |
| 4 | 0.69314713056005628 | 0.6931471305599604 |
The 10 million terms of 1 − 1/2 + 1/3 − …, in lumen2/bench/sum-par.c and
sum-par.lm.
The Lumen 2 program splits the terms into 1,000 blocks, which par_map sums, and adds up the
block sums in order. The blocks do not depend on the number of threads, and par_map returns their
sums in order, so the result is the same bits on one thread or four. A C programmer can get the same guarantee by
writing the loop that way. In Lumen 2, a parallel map cannot be written any other way.
What is missing is mostly a library: there are no exp, log, power or trigonometric
functions yet.
22 · Part five
After the parallel proof came a fair question: “But this should be provable in C as well, right?” It should. Nothing about S(4) needs Lumen 2, and a C solver split into the same cubes would prove it faster. What Lumen 2 adds is that its types say what a function can do, checked before anything runs. So the next question was the right one: “Anything else which is easier/faster in this language and is more practical as well”. A guarantee about what a function can do matters most when someone else wrote the function.
Many systems run code their users write, on their own data: a filter in a log pipeline, a computed column, a
step in an ETL job. The usual ways trade safety against speed. Python's exec gives the user's code
everything Python can do. Node's vm module runs it in a separate context, which Node's documentation
says is “not a security mechanism”. C is fast and checks nothing. And none of them can run the user's code on
every core without knowing what it does: if it prints, keeps a counter or draws random numbers, the output
depends on how the threads were scheduled.
lumen2 transformThe user writes one function, transform(n, line). It gets a line's number and text and returns
the output line, or None to drop it. A library written in Lumen 2 splits CSV fields, parses
integers and exact decimals, and handles text, with every byte access proved in bounds. A harness reads 4,096
lines at a time and maps them with par_map, 64 lines to a task. The check is the one
par_map already makes: the function may fail, and may do nothing else.
fn transform(n: Int, line: String) -> Option<String> {
if n == 1 || random_int(1, 100) == 1 { Some(line) } else { None }
}
error: `transform` can use randomness, but a transform may only compute (and fail)
transform fn(Int, String) -> Option<String> ! random (line 1)
That rejection is the point. Sampling with random_int would choose different lines on every run;
sampling by hash(line) % 100 chooses the same ones every time. Because a transform is pure, two
more things come almost for free. The output is the same, byte for byte, on any number of threads, and the tests
check that on one and four threads, in several batch and task sizes. And a failure can name its line. When a
task fails, the tool transforms that task's 64 lines again, one to a task, and reports line 12346: integer
overflow. Running code again to find an error is only safe when running it does nothing else.
Nothing else is reachable, either. The program is WebAssembly, and the only functions it imports read input, write output, read the clock, draw random numbers, report a failure and start threads. Even a bug in the checker could not give a transform the file system.
The benchmark is an ordinary job. From 2 million orders (105 MB of CSV), it keeps the euro-area orders of at least 100.00, replaces each customer with a pseudonym, and prints the total to the cent. I wrote the same function in C, JavaScript and Python, each with the same library, and every version must print the same 950,124 lines, byte for byte.
| language | the user's code is | threads | time |
|---|---|---|---|
| Lumen 2 | checked, compiled before | 4 | 1.43 s |
| Lumen 2 | checked and compiled in the run | 4 | 2.78 s |
| Lumen 2 | checked and compiled in the run | 1 | 3.88 s |
| C, OpenMP | not checked | 4 | 0.32 s |
| C | not checked | 1 | 0.37 s |
| JavaScript | in a node:vm context | 1 | 6.60 s |
| JavaScript | not isolated, as with eval | 1 | 3.07 s |
| Python | run with exec | 1 | 9.69 s |
Wall-clock time for the whole command, best of three, on the same 4-core machine.
lumen2/transform/bench/run.js generates the data, runs every version and compares the outputs.
Once compiled, Lumen 2 is 6.8 times as fast as Python's exec and 4.6 times as fast as
JavaScript in a vm context. Counting the 1.4 seconds it takes to check and compile, the factors are
3.5 and 2.4. A compiled transform is cached, so that cost is paid once. C on four threads is 4.5 times as fast
as Lumen 2 on four: Lumen 2
copies every field it splits off, where C points into the line, and Lumen 2 checks its arithmetic for overflow.
The vm row surprised me twice. The same JavaScript took 2.2 times as long in a context as
outside one. And the context isolated nothing: in the benchmark's own harness, the user's code reached the
host's process, and with it the file system, through one expression,
globalThis.constructor.constructor('return process')().
The first version spent more time around the transform than in it, and three changes fixed most of that.
par_map's threads took one index at a time from a shared counter, and with thousands of small
elements the counter cost more than the work, so they now take blocks of up to 64. The harness now gives each
task 64 lines instead of one. The third change helped every program. The profile was full of calls to
the small functions that add and remove a reference. V8 does not inline a call from one WebAssembly function to
another, except under an experimental flag, and with that flag the run took 2.5 seconds instead of 3.6. So the
code generator now inlines those two functions itself. Binary trees went from 2.25 to 1.74 seconds and edit
distance from 3.55 to 2.97, both measured the same day, and the compiler now compiles itself in 20 seconds
instead of 27. Inlining allocation as well made the compiler 3.9 MB instead of 2.4, for at most 10% more speed,
so I took it out again. Together, the three changes brought the transform's run from 3.4 to 2.5 seconds on one
thread, and from 1.9 to 1.4 seconds on four.
What is left is mostly structure. The main thread reads the lines and writes the output while the other threads wait, so four threads give 1.8 times the speed of one, not 4. A quoted CSV field cannot hold a line break, because lines are split first. And at first nothing limited a transform's time: one that looped forever ran forever, though its memory stopped at the WebAssembly memory's 1 GB.
The usual fix is a timeout, and it is the wrong one here. A timeout depends on the machine and on what else
it is doing, so a line that takes nine seconds passes on one run and fails on the next, and on four threads it
does not even say which line ran out. A transform's output is the same on any number of threads; I wanted its
failures to be the same too, so the budget counts work, not time. Every loop in Lumen 2 is a function that calls
itself, so a computation that runs long passes the start of some function again and again. With counting on,
every function begins by taking one from a 64-bit global, one per thread, and stops with
out of steps below zero. A self tail call jumps back to just before that test, so a loop pays once
per turn.
fn spin(k: Int) -> Int { if k < 0 { k } else { spin(k + 1) } }
fn transform(n: Int, line: String) -> Option<String> {
if n == 1235 { Some(int_to_string(spin(0))) } else { Some(line) }
}
$ lumen2 transform spin.lm --input rows.csv
runtime error: line 1235: out of steps (each line may take 10,000,000 steps)
The harness sets the budget before each line, with a builtin that only it may name, so a transform cannot give
itself more, and a failing line is found again as any failure is; the count depends only on the line, so it is
the same line on every run. Ten million steps is the default. A line of the orders benchmark takes at most 172,
and counting costs about 8% of a run. A step is not a unit of time: a builtin such as
concat_strings is one step however long its strings are, so the budget bounds a line's time in
proportion to its data, not absolutely.
23 · Part five
Asked “Do we have now a novel language which is useful and faster than other languages in production for some use cases?”, I said not yet. Lumen 2 was 1.1 to 3.5 times slower than C, and its clear wins were against Python and a JavaScript sandbox that isolated nothing. The reply was “I want it to be better than what's out there by a huge margin - even if for one niche use case.”
Raw speed could not do it. C or Rust compiled to WebAssembly, in a sandbox that counts steps, is as safe as a transform and faster. A huge margin had to come from something only Lumen 2 knows about a program, and the strongest such fact is that a transform's output for a line depends on nothing but the line. So when a file changes a little and the transform runs again, every line that did not change can keep its last output, and the result is still exactly a full run's. A function in C, JavaScript or Python could be cached the same way only by trusting whoever wrote it, because nothing checks that it does not read the clock, keep a counter from one line to the next, or draw a random number. Of the three niches I offered, that was the one chosen.
A run with --incremental keeps its input, its output and the length of each line's output. The
next run compares the new file with the old one from both ends, byte for byte, so an append or a single edit
costs little more than reading the two. What lies between is cut into chunks of whole lines, at points chosen
by a hash of each line, so an edit moves only the cuts near it. A chunk whose SHA-256 hash the last run saw
keeps its output, wherever it moved to. The lines of the remaining chunks are matched against the old lines
they replace, by Myers' diff, and only the lines left without a match are transformed, on every core.
Two details decide whether a reuse is sound. The first is the line number, which a transform is given and which the orders example compares with 1 to print its header. The tool proves from the code a number T: every use of the number is a comparison with a constant, and T is the largest. For a line above T the number cannot matter, so such a line keeps its output when lines are inserted above it. A transform that uses its number in any other way keeps an output only at the same number. The second is the hash. The lines of a log come from anyone, and with a fast hash that is not cryptographic, an attacker could write a chunk that collides with one already seen and be handed its output. So the chunks are hashed with SHA-256, and lines are compared byte for byte.
The benchmark matches each company name in 500,000 rows (20 MB), typed with mistakes and in any case, to the closest of 64 known names by edit distance: a usual first step in cleaning data, and about 40 microseconds of C a row. In full, C takes 5.1 seconds on four cores and 19 on one, Lumen 2 13, JavaScript about 80 and Python about 1,180.
| change | lines transformed | time | vs C, 4 threads | vs C, 1 thread | vs Python |
|---|---|---|---|---|---|
| nothing | 0 | 0.17 s | 30× | 108× | 6,800× |
| 1 row changed | 1 | 0.19 s | 27× | 98× | 6,200× |
| 500 rows changed, scattered | 500 | 0.38 s | 13× | 49× | 3,100× |
| 5,000 rows changed, scattered | 5,000 | 0.58 s | 9× | 32× | 2,000× |
| 500 rows appended | 500 | 0.27 s | 19× | 69× | 4,400× |
| 10 rows inserted, 10 deleted | 10 | 0.32 s | 16× | 58× | 3,700× |
lumen2 transform --incremental on four threads, starting from the original
file's state, against the same function run again in full; best of three on the same 4-core machine. Python
was timed on 20,000 rows and scaled. Every output is checked against C's, byte for byte, by
lumen2/transform/bench/incremental.js.
The first run, which transforms every line and writes the state, took 12 seconds, against 13 without
--incremental. The margin is the work saved, so it depends on the function. The orders example
costs a fraction of a microsecond a row, and C reads, transforms and writes its 105 MB in 0.31 seconds, about as
fast as the file can be read. Reading the file and the old one costs the incremental run more than that: 0.47
seconds when nothing changed and 1.1 seconds for 2,000 scattered edits. That is still faster than running the
function again in Lumen 2, JavaScript or Python, but it loses to C. For a function that does real work on each
line, it is faster than any full run by more than an order of magnitude, and the margin grows with the
file.
Asked next “is this use case used by anyone in practice?”, I had to say that the comparison above is not the
one that matters most. Recomputing only what changed is everyday practice, but a pipeline that runs every day
rarely runs the function over everything again. It transforms the rows updated since its last run, by an
updated_at column, as dbt's incremental models do, or a warehouse refreshes incrementally if its
functions are declared IMMUTABLE. Against those, the speed margin mostly goes. What they lack is a
check: the timestamps, and the declarations, are trusted. The answer was “can we create more realistic end user
simulation for this”.
The simulation is a month of a vendor file of 500,000 rows, exported again in full every day, with the changes such files get: rows appended, corrected (mostly recent ones), deleted, and a few arriving late with yesterday's timestamp. A new supplier starts appearing on day 10 and is added to the known names on day 15, and on day 22 a correction touches 5% of the rows. Five ways keep the output up to date, each run as its own process every day, and every day's output is compared, row by row, with the function run over the whole file. The others run the function in C, which reads the known names from a file, as C and Python programs usually keep such data.
| way | days wrong | usual day | day 15 | 30 days |
|---|---|---|---|---|
| run it over the whole file again, in C | 0 | 5.7 s | 6.3 s | 3 min |
| rows updated since the last run, merged by id | 30 | 0.71 s | 0.74 s | 22 s |
| cache by row and the code's version | 16 | 1.95 s | 1.82 s | 58 s |
| the same cache, keyed by the names too | 0 | 1.91 s | 7.3 s | 62 s |
lumen2 transform --incremental | 0 | 0.68 s | 17 s | 38 s |
Days 1 to 30, on 4 threads; lumen2/transform/bench/simulate.js. The merge and the
caches are Node scripts with the function in C.
The merge by timestamp is the fastest, and it is wrong from the first day. It never sees a row that arrives with an older timestamp, it keeps deleted rows, and it gives the new name only to rows updated after the change. By day 30, 6,239 rows are wrong. The cache keyed by the code is right until the names change, and then about 400 rows are wrong for the rest of the month, because the names are in a file the code reads. Keyed by that file too, it is right every day, as right as its author's list of what the function reads, which nothing checks. Lumen 2 is right every day with nothing listed: the names are part of the transform, the only place a transform can get them from, so changing them changes the program, and the state starts again. On a usual day it is as fast as the merge. Over the month it took 38 seconds, against 3 minutes for running the function again in C, a factor of 4.5 rather than the 10 to 30 of the single changes above. Most of those 38 seconds are its two full runs, on day 0 and day 15, where Lumen 2 is three times as slow as C.
A test makes random edits to files and compares every incremental run with a full run, byte for byte. It changes, inserts, deletes, appends, duplicates and moves lines, drops the last line break, and adds CRLF and empty lines, for five transforms: ones that ignore the number, compare it with constants or print it, the orders example, and one whose outputs hold line breaks. To see whether the tests could catch an unsound proof about line numbers, I made the proof claim that no transform depends on its number, then that the number did not matter above 3, then above 24. Each time, two of the five tests failed. A run that fails is run again in full, so its error and the output printed before it are exactly a full run's, and damaged or foreign state is ignored.
What it does not do: the file is read into memory, and the state holds a copy of the last input and output, so a run needs room for both. A change to the transform, the library, the compiler or the budget starts again from nothing. And the state is trusted as the compiled transforms beside it in the cache are; its copy of the input is not hashed again when it is read back.
Then came the question that decides it: “I don't think ROI of doing this in a different language is
warranted. Is there a very high value (in terms of money) work which warrants this decrease in latency?” I could
not name one. The computing is cheap: running the function over the whole file again in C, every day for a
month, takes about three minutes of a four-core machine, around a cent at cloud prices, so
--incremental saves a fraction of that, and a thousand times the data would save a few dollars a
month. Where recomputing does cost real money, a new language still does not win. Calls to a model on every row
go over the network, which a transform cannot reach. Risk systems in finance are built around events, on
established libraries. Build systems already get their correctness from hermetic actions. And when a person is
waiting, it is usually because they changed the function, which makes --incremental start
again.
What is worth something is the guarantee, not the speed. Warehouses already depend on promises that nothing
checks: incremental refreshes trust functions declared IMMUTABLE, and merges by timestamp trust the
timestamps. A check of such a promise for code people already write, a Python function or a WebAssembly module,
would carry what Lumen 2 proves without asking anyone to change languages. Whether anyone would pay for it, I
have not tested.
Part six · contents
Mistakes and limits
All this checking existed to find problems I didn't know I had. This part lists what it found, including my own mistakes, and then what the project does and does not show.
24 · Part six
-O had
miscompiled the self-hosted compiler. The bug was in the harness: it deleted the baseline output before
comparing against it. I found that before reporting anything.run silently replaced the program's
entry point, and two of my hand-written test expectations were wrong while the code was right.if's value only inside the branch that computed it, so a nested if lost them, and the
checker reported counterexamples that could not happen. Those facts define a fresh value and constrain
nothing else, so they now hold everywhere.let inside a lambda crashed the
JavaScript compiler, which took the refinement's bound variable for a captured one (chapter 20).a || f(x) at the end of a function did not compile to a tail
call, in either compiler, so checking that a million-element array was sorted overflowed the stack. The
heapsort showcase found it.if. The
binary search showcase found it.match to be the
disjunction of its arms' values. With "a" -> true and _ -> false, that is always
true, so an else on it counted as unreachable, and an out-of-bounds access there counted as
proved. CI's fuzzer found it on fresh seeds: the interpreter's re-check of proofs stopped exactly where the
compiled code read out of bounds. This is what the re-check is for. A match's value is now one of its arms'
values, chosen by an arm whose conditions hold, and the mistake is a planted bug.if true { 9223372036854775806 + 2 } else { 10 } to
be worth 263. At run time the addition overflows and the program stops. But the checker had
defined a fresh 64-bit value as equal to 263, a definition no 64-bit number satisfies, and from a
contradiction anything follows: an out-of-bounds access later in the function counted as proved. A defined
value's range now covers every value its definition allows. This is a planted bug too.char_code_at became inline code
(chapter 21), the code generator expected the string to be in a variable. The first test program read a
character from a string literal, and the compiler stopped with an internal error.main with one nested block per test case, into a single chain of
thousands of instructions. The compiler's passes recurse once per instruction in a chain, and two tests failed
with a stack overflow. Only arithmetic and array reads move now.int_to_string writes its digits into a fixed piece
of scratch memory, and with par_map every thread wrote into the same one. The first parallel test
passed in normal mode and printed "6!" for "1!" in paranoid mode, whose timing
differs. Each thread has scratch memory of its own now, and the race is a planted bug that the tests must
catch.par_map's function, the checker
closes its effect row. That row was also the call's own, so closing it closed the effects of the function
making the call, and the first test program's println in main was rejected.!(array_length(a) <= i), the goal said i < array_length(a),
and the checker built a separate circuit for each. With a value near 263 in the term, the solver
needed more and more conflicts to find the two equal. Comparisons now have one canonical form, so both are
one literal: that proof takes no conflicts, and checking the binary search showcase takes half as long.safe in tail position. To keep that call a tail call, borrow inference
made safe own its list (chapter 17), and every other call of safe then counted
references along the list. Comparing timings with the sequential program found it.lumen2 transform finds the line that failed from
the index par_map reports. A par_map over one element runs without the threads and
reports no index, so with one line to a task the first version said lines 1235 to 1235. A test
with tasks of one line found it.split(" aAbabZ, b ", "ab") to give three
parts. "ab" occurs once in that string, so it gives two, as the library did.j = -1 where the test expected an index past the end. Both break the contract;
the test now accepts either.long is 32 bits there, and the random number generator
overflowed. The benchmark runner compares every version's output, so the mistake never reached a timing.--incremental read its
state's tables with Node's Buffer.slice, which, unlike the slice of other typed arrays,
does not copy. Every state looked broken, so every run transformed every line: the output was right, and there
was no speedup, the way the design allows it to fail. A profile showed the state being read and then
ignored.read_input, then the compiler in Lumen reaching its fixed point. 5b23926par_map, threads that share one memory and count references atomically while they run, and three parallel benchmarks against C with OpenMP.par_map, one checked refutation, 22 seconds instead of 8 minutes.lumen2 transform, which runs a user's function over a file on every core after checking that it can only compute, against the same function in C, JavaScript and Python; and reference counting inlined. lumen2/transform/lumen2 transform, counted by the compiled code, so a runaway transform stops at the same line on every run, for about 8% of the run's time.lumen2 transform --incremental, which reuses the last run's output for every line that did not change, because the transform is proved to depend on nothing but its line: 9 to 30 times as fast as running a fuzzy-matching function again in C on four cores. lumen2/transform/--incremental on none, as fast as the merge on a usual day.The conversation outgrew my working memory and had to be summarized partway through, more than once, and the machine I ran on restarted once during a five-minute check. What made it safe to pick up the thread was not my memory. It was the commit history, the tests, and a check that refuses to pass if anything has drifted.
25 · Part six
It shows one long session of sustained engineering in which each layer was checked by the one below it. The
work is a compiler, an independent re-implementation of it, a prover with a proof checker, an optimizer gated by
all of them, and a theorem whose proof doesn't depend on trusting any of them. Then it is a second language,
designed from what the first one taught, whose compiler proves parts of each program safe and checks its own
output on every compile, which reproduced the theorem's proof exactly, and which compiles itself. Every claim on this page can be
re-run with the commands below, which are also in the
README. CI repeats the checks, including the
whole proof of S(4) = 44 in both languages, a second check of the Lumen 2 proof by a checker proved unable to
crash, and a check of every refutation the project writes out by drat-trim, a checker nobody here
wrote, on every push.
It does not show that Lumen 2 is worth adopting. It is 1.1 to 3.5 times slower than C on one core. Its wins come from what its checker proves, not from speed: a parallel result that cannot depend on the threads, user code that cannot reach anything, failures and budgets that are the same on every run, and outputs that can be reused because the function provably depends on nothing else. Those are real, but in money they are small, and chapter 23 ends on the honest form of that: the guarantee would be worth more as a check on code people already write than as a reason to write code in a new language.
It does not show that earlier models could not have done this. I can't run that comparison. If you want to, CHALLENGE.md turns the original task into a benchmark with an automatic scorer. S(4) = 44 has been known since 1965; what is new here is that a language built in this session produced the proof, not the result itself. Lumen is also small by design: no floating point, no modules, 31-bit integers, and arrays as its only mutable values. Lumen 2 has no modules either, and its floats have no exponential, logarithm or trigonometric functions yet. Its refinements are limited to linear arithmetic over integers and array lengths, plus one fact about every element of an array, and it reuses memory only where the size of a cell is known when compiling. Its S(4) proof rests on the same symmetry argument as Lumen's. Its comparison with C covers six small programs, four of them also on four cores, and one data transformation, which is also compared with JavaScript and Python, as are two transformations run again after their files change. And every timing here comes from one JavaScript engine on one machine.
Everything needs only Node 22 and a clone of the repository. There is nothing to install.
node bin/lumen.js run examples/nqueens.lm # compile and run a program (add -O to optimize) npm test # the test suite: every language test five ways node fuzz/fuzz.js --count 1000 # differential fuzzing on fresh random programs node fuzz/mutants.js # all 34 planted bugs must be caught node selfhost/bootstrap.js # the self-hosting fixed point node superopt/verify.js # re-prove the 40 rules, checking every proof node bench/gate.js # the whole gate, about 7 minutes node proofs/prove-schur.js 4 44 # prove S(4) = 44, about 6 minutes cd lumen2 && npm test && cd .. # Lumen 2: 91 tests node lumen2/test/fuzz.js 1000 # Lumen 2: differential fuzzing, four ways node lumen2/test/fuzz.js --mutants # all 27 planted bugs must be caught node lumen2/superopt/verify.js # re-prove the 19 rewrite rules node lumen2/compiler/bootstrap.js # Lumen 2's compiler, built by itself, compiles itself to itself node lumen2/selfhost/bootstrap.js # the first self-hosted Lumen 2 compiler's fixed point node lumen2/proofs/prove-schur.js 4 44 --out s4 # S(4) = 44 in Lumen 2, about 5 minutes; s4/ gets the proof node lumen2/proofs/compare-lumen.js 4 44 # the same proof as Lumen's, byte for byte node lumen2/proofs/check-drup.js s4/schur-4-45.cnf s4/schur-4-45.drup # check it again, with the checker proved not to crash node lumen2/bench/run.js # Lumen 2 against C, on one core and on all (C timings need a C compiler) node lumen2/transform/bench/run.js # a user's function on 2 million rows: Lumen 2, C, JavaScript, Python node lumen2/transform/bench/incremental.js --sample 20000 # run again after six kinds of change, against full runs
Explore it yourself. The playground has the full editor with types, intermediate code and WebAssembly views, the fuzzer, the bootstrap, every proved rule, and the campaign. The Lumen 2 playground shows inferred effects, every proof obligation, the code after reference counting, property tests and certificates. The source has everything else.