Programming
The formal verification arc
AI coding agents have changed the cost of writing code. Generating an implementation, a test suite, and a refactoring pass used to take days; now it takes minutes. That shifts the bottleneck from typing code to knowing whether the code actually holds under every edge case.
Unit tests check examples that a human or a model remembers to write. When code generation gets cheap, example-based tests stop being enough on their own. Formal verification gives an AI workflow a referee that cannot be charmed, nudged, or argued into approving a broken edge case: either the proof type-checks in the kernel and the state space holds, or the build fails.
That is why I have been on a formal verification arc across my open-source libraries, starting with Lean 4 proofs for bin-packing and electroacoustics, and expanding into Lean and TLA+ for abi-typegen, lru-cache-clustered, adaptive-cache, and more.
Formal verification: past, present, and future with AI
Formal methods have a long history. Hoare logic, TLA+, Coq, Isabelle, and Lean have verified microkernels like seL4, compilers like CompCert, and distributed consensus protocols at companies like AWS. For most everyday libraries, though, formal verification stayed out of reach because proof engineering took specialized teams months of manual work.
AI coding agents invert that math. Today, models write fast, idiomatic code that often reaches 100% line coverage while still hiding subtle floating-point, overflow, or concurrency bugs. At the same time, those same agents are surprisingly strong at proof engineering. You can point parallel agents at Lean 4 modules or TLA+ specifications, let them grind through case splits and invariants, and point a separate model at the result to try to break the specification with counterexamples.
Looking ahead, formal verification is the natural backbone of AI-assisted software development. An LLM can write a convincing code review and miss a boundary condition in a single line of arithmetic. A theorem prover kernel does not care how persuasive the explanation sounds. If a branch is missing, a type overflows, or an invariant slips, the kernel rejects it. Pairing fast agent generation with adversarial review and machine-checked proofs turns correctness into a mechanical gate instead of a gut check.
Proving bin-packing in Lean 4
My first deep push into this workflow on a Rust codebase was bin-packing, the Rust and WebAssembly cut-list and packing optimizer I originally built for subwoofer enclosure panels. For version 0.6.2, I added a pinned Lean 4 formal verification suite (Lean v4.35.0 and Rust 1.99.1) with zero Mathlib dependency so the entire verification pipeline builds cleanly and reproducibly.
The proof suite spans 22 Lean 4 modules and 48 --verify certificate tags across 1D linear stock, 2D rectangular sheets, 3D boxes, sloped and irregular polygons, guillotine and staged cutting plans, saw schedules, stack loading, offcut reuse, and exact optimization objectives. Every run replays real solver outputs through the Lean checkers: 287 Rust certificate cases plus 145 Node.js and WebAssembly cases (73 in Node.js and 72 in WebAssembly).
Because verifying a mathematical model is stronger when it also binds to compiled code, I wired production rustc MIR extraction into the suite. Six core Rust arithmetic predicates (end_with_gap_at_most, effective_axis_bound, fits_trimmed_axis, area_u64, scale_threshold, and scale_floor) are lowered from rustc MIR to Lean and proved in both dev and release profiles, alongside Node.js and wasm32 MIR proofs for the JavaScript safe-integer guards (is_safe_js_integer and is_safe_js_sum). In total, the audit checks 1,788 local Lean theorems with zero sorry placeholders, depending strictly on Lean's three standard axioms (propext, Quot.sound, and Classical.choice).
Running the full verification suite locally takes two commands:
./scripts/check-proofs.sh
./scripts/check-proofs.sh --bindingsBugs the proofs and adversarial reviews caught
Before I wrote the first Lean file, bin-packing already had over 600 passing Rust tests. Proving the invariants still turned up three real production Rust bugs:
- Signed-zero ranking in
solve_1d_min_cost: Rust'sIterator::sum()onf64starts its accumulator at-0.0. For zero-cost stock, bars summed to-0.0and outranked+0.0solutions that used fewer bars underf64::total_cmp. Folding explicitly from+0.0fixed it. - 3D
placement_feasibleu32::MAXoverrun: Near the top ofu32,u32::MAX.saturating_add(1) <= u32::MAXevaluated totrue, masking an extent overflow. Widening the check tou64throughend_with_gap_at_mostfixed it. - 1D
PackedBin::delta_for_pieceboundary check: The sameu32::MAXsaturating-add pattern hid in 1D placement bounds and moved onto the same provedu64helper.
Just as valuable were the six bugs that two rounds of independent adversarial AI review found inside the Lean checkers and audit scripts before 0.6.2 shipped:
- Incomplete open-extent incumbents:
exact_open_*accepted a zero-cut incumbent at the minimum extent before requiringmissingRequested == 0. - Phantom kerf offcuts in reuse:
Reuse.leaninitially accepted a blade-removed kerf strip as a recoverable offcut. Binding every offcut to a distinct live non-part workpiece through a verifiedSaw.checkSawreplay closed the gap. - Binary64 rounding divergence: An exact decimal cost model let
0.1 + 0.1 + 0.1diverge from IEEE 754f64(0.30000000000000004), and a second counterexample at the2^53boundary (2^37 + 2^-16) diverged in knapsack slot totals. Locking certificates to an exact2^-16dyadic domain with<= 2^53total and slot-sum caps kept Lean and Rust aligned. - Zero-width degenerate polygons: A polygon where
hole == exteriorproduced zero-width tiles whose overlap predicate held vacuously. Strict integer ring and hole containment checks now reject degenerate geometry. - Unbounded row expansion on infeasible inputs: Infeasibility checks expanded demand copies before enforcing search budgets. Moving those checks directly onto demand rows fixed it, verified at
1_000_000copies. - Audit script escapes: A Lean file could weaken kernel verification with
set_option debug.skipKernelTC trueor guillemet-escaped options likeset_option «warningAsError» false. Normalizing guillemets, enforcing a strictset_optionallowlist, passing-DwarningAsError=true -Ddebug.skipKernelTC=false, and auditing the full compiled environment closed that hole.
That second list is the biggest lesson from doing formal verification with AI. A theorem prover guarantees that your proof matches your specification, so you still have to attack the specification itself. Running a second model whose job is to forge certificates and break the audit catches specification bugs before they look like solved math.
How bin-packing compares to other libraries
Before investing in a multi-domain solver and a Lean proof suite, I looked closely at existing bin-packing and cutting-stock libraries across Rust, C++, Python, and JavaScript. Several of them are strong at what they target, and comparing them clarifies where bin-packing fits.
Rust libraries
- jagua-rs and sparrow: High-performance 2D irregular collision detection and nesting engines. If your primary problem is large-scale industrial irregular nesting,
jagua-rsandsparroware stronger specialized tools. They rely ondebug_assert!checks and benchmark suites rather than a theorem prover. - guillotiere and etagere: Fast dynamic 2D texture-atlas allocators built for GPU graphics pipelines, with O(1) coalescing for allocation and deallocation. They are designed for real-time rendering rather than saw kerf, trim margins, or staged cutting schedules.
- crunch and rectangle-pack: Focused options for static 2D sprite atlases (
crunch) or general 2D and 3D heuristic placement (rectangle-pack), without cutting-plan witnesses or formal certificates.
C++ and Python solvers
- PackingSolver: Florian Fontan's C++, Python, and WebAssembly suite is the broadest multi-domain industrial packing reference I found, covering 1D, 2D guillotine, 2D rectangular, 2D irregular, and 3D box-stacking problems. It validates results with benchmark suites and solution checkers, without a proof assistant.
- Google OR-Tools: General-purpose MILP and CP-SAT optimization. OR-Tools scales exact optimization far beyond small exhaustive search caps using branch-and-bound and solver-internal optimality bounds, though its guarantees rest on a large C++ solver rather than an independently replayed kernel proof.
- rectpack and py3dbp: Lightweight Python heuristic packers for 2D rectangles and 3D boxes, handy for quick scripts without kerf-aware saw plans or formal verification.
JavaScript and npm packages
- maxrects-packer, potpack, bin-pack, guillotine-packer, and binpackingjs: Popular browser and Node.js packages for sprite atlases, layout packing, and basic cut lists. They are lightweight heuristics without multi-dimensional exact modes, Rust safety guarantees, or machine-checked certificates.
Where bin-packing sits
bin-packing combines 1D, 2D, 3D, and irregular packing, kerf and trim margins, guillotine and staged cut plans, saw schedules, and explicit objectives inside one #![forbid(unsafe_code)] Rust core that ships as a native crate, a Node.js N-API package, and WebAssembly. For massive irregular nesting benchmarks or large integer-programming models, specialized tools like PackingSolver, jagua-rs, and OR-Tools still win on raw scale. Where bin-packing stands apart is pairing a self-contained Rust, Node.js, and browser solver with a pinned Lean 4 certificate verifier and rustc MIR refinement proofs.
Honest boundaries of the proof
Formal verification is only useful if you state the trusted computing base plainly. In bin-packing, the proof pipeline trusts pinned rustc, the MIR-to-Lean translator, the pinned Lean 4 kernel, the Serde, N-API, and wasm-bindgen serialization glue, and the host JavaScript or WebAssembly runtime.
Scope limits matter too. Exact exhaustive modes carry finite search caps, such as 64 or 128 demand copies and 65,536 grid or crop states. Above those limits, heuristic solvers still produce solutions whose feasibility, bounds, and cutting plans can be checked, without claiming global optimality.
Adding Lean and TLA+ across my libraries
bin-packing is one part of a wider push to match the right formal tool to each library I maintain. Pure math, geometry, parsing, and binary invariants fit Lean 4; concurrent workers, invalidation races, and stateful caches fit TLA+.
- bin-packing: 1,788 audited Lean 4 theorems covering 1D, 2D, 3D, and irregular packing certificates, saw plans, exact objectives, and
rustcMIR arithmetic. - electroacoustics: 160-bit dyadic interval certificates and 629 audited Lean 4 theorems verifying loudspeaker headroom, tapered Webster ducts, and impedance-fit diagnostics directly in the Lean kernel.
- abi-typegen: Adding Lean proofs for ABI signature parsing, canonical selector hashing, and type-mapping invariants across the generated language bindings.
- lru-cache-clustered: Adding TLA+ specifications to model cross-worker IPC cache coherence, invalidation races, eviction ordering, and worker restart recovery across Node.js cluster workers.
- adaptive-cache: Adding TLA+ specs for TTL adaptation state transitions, refresh-in-flight coordination, and stale-read bounds, paired with Lean checks for the lifetime-adjustment arithmetic.
The pattern is consistent across all of them. When AI agents make code cheap to generate, writing down exact specifications in Lean and TLA+ turns into the highest-leverage engineering work available. Agents can explore implementations fast, adversarial reviewers can try to break the specs, and the proof kernel or model checker decides what is ready to ship.