Bet 2: refinement types + automated proofs erase bounds checks
Question. Can Trine keep every array access safe (no out-of-bounds reads, ever) without paying for a run-time check on each one, and without asking the programmer for annotations?
Kill criterion (from the charter). Most bounds checks erased on the golden programs, at under 50 ms of solver time per function.
Verdict: passed. 99.97% of run-time bounds checks are erased (189,884 of 189,935) and 75 of 84 index sites are proven statically. The slowest function takes 24 ms in any analysis pass, with zero work-budget hits. Z3 independently confirms all 1,358 proof obligations. Every one of the 9 remaining checks guards an access that really could fail given what the program knows.
How it works (src/bounds.rs)
- Inferred refinements, no annotations. The verifier optimistically assumes that every parameter, return value and constructor field that could be an Int is
>= 0, and that every function returning a list might havelen(result) == norlen(result) == len(xs)for each parameter. It analyzes the program, discards every assumption some producer can't justify, and repeats. What survives is a greatest fixpoint, so it is sound: every producer was proven to respect it. For example, onjson.trit infers that parse positions are never negative (Parsed field 1 >= 0,skip_ws: result >= 0). Onmatmul.trit inferszeros: len(result) == n. - Symbolic execution of the ownership IR tracks Int values as linear expressions, the lengths of lists and strings, and path conditions from branches. For example, after
if j >= len(cs): return ...the factj < len(cs)holds. It knowslen(range(n)), that elementkofrange(lo, hi)islo + k, thatsplitnever returns[], thatx*y >= ywhenx >= 1, y >= 0, the bounds ofmin/max/%, and that a value merged from two branches equals one of them. - Loop invariants (Houdini). Candidate facts are proposed for each loop variable and kept only if the loop body preserves them: -
x >= entry,x <= entry,x >= 0; - relational facts such aslen(out) - i == entry difference("they move together") andbest_i - i <= -1("one stays ahead"); - bounds by unchanged values, e.g.i <= len(xs). - Prover. Linear integer arithmetic. Facts relevant to the goal are selected through a symbol index, equalities are solved by substitution, and the rest goes to Fourier–Motzkin elimination with integer tightening. Disjunctions are case-split only when the plain facts aren't enough. The prover is sound (a contradiction means no integer solution exists) and incomplete (anything unproven keeps its check).
- Deterministic budget. Each function gets a budget of 5,000 proof attempts, counted, not timed, so results are reproducible on any machine. Running out only means "keep the check".
Results
| program | index sites proven | run-time checks erased |
|---|---|---|
| json | 25 / 25 | 30,308 / 30,308 (100%) |
| primes | 5 / 5 | 47,499 / 47,499 (100%) |
| raytrace | 7 / 7 | 10,821 / 10,821 (100%) |
| server | 18 / 20 | 100,123 / 100,125 (99.998%) |
| values | 4 / 5 | 1,003 / 1,004 (99.9%) |
| shapes | 1 / 1 | 3 / 3 |
| higher_order | 3 / 4 | 35 / 39 (89.7%) |
| matmul | 12 / 17 | 92 / 136 (67.6%) |
| calc, fbip, hello | no index operations | — |
| total | 75 / 84 (89%) | 189,884 / 189,935 (99.97%) |
The 9 checks that remain, and why they should
| site | why it can fail |
|---|---|
w[0] (higher_order) | w is any string; it could be empty |
b[0] (matmul) | b is any list of rows; it could be empty |
| 4 inner-row accesses (matmul) | rows of a nested list can have any length; needs shape refinements |
ys[0] (values) | zero_first accepts any list |
load[0], load[len(load) - 1] (server) | the list's length depends on what the request handler did |
Closing these takes information the programmer has and the program doesn't state: "non-empty", "rectangular". That is where optional written refinements (xs: List[Int] where len(xs) > 0) come in. The inference engine already supports them.
Soundness: how we know the erased checks are safe
- An independent referee.
trine bounds file.tr --smt out.smt2exports every proof obligation (facts plus negated goal) as SMT-LIB.tools/z3_check.pyconfirms each one is UNSAT with Z3: 1,358 / 1,358. - Run-time re-validation. The VM still validates every erased access and would report a "verifier bug" if one ever failed. None does: all golden programs produce byte-identical output with checks erased.
- Negative tests. Real out-of-bounds bugs keep their check and fail normally. These are an off-by-one loop (
tests/errors/off_by_one.tr) and a constant index past the end. - **Locked into
cargo test:**bet2_erased_checks_preserve_behaviour,bet2_most_bounds_checks_erased,bet2_proofs_cross_checked_by_z3andbet2_never_erases_a_needed_check.
Engineering notes (what went wrong on the way)
- Analysis time blew up to 19 s on matmul at first. The causes were invariant candidates for every float temporary, expanding every disjunction before checking relevance, quadratic DNF copying,
BTreeMap-based linear terms, and re-running inner-loop invariant search for every outer trial. All were fixed (relevance index, plain-facts-first, sorted-vector terms, cheap inner trials). The slowest function went from 19,396 ms to 24 ms. - The first budget was in milliseconds, which made results depend on machine speed. In SMT-export mode (slower) JSON proved 25% instead of 100%. The budget is now counted in proof attempts, and results are identical with or without
--smt. - Violations recorded during trial runs wrongly discarded true refinements. Producers are now only judged in final passes, which still visit every reachable operation.
Threats to validity
- The solver is in-house (Fourier–Motzkin), not Z3. Z3 is used as a referee, not in the compiler. Integrating an SMT solver could prove more, at the cost of a large dependency.
- Golden programs are small, and the loop patterns are the common ones. Unusual loops (stride tricks, index arithmetic through multiplication) will keep more checks.
- "Erased" is measured in the VM. The speedup is realized only when the native backend (roadmap #23) compiles erased accesses to plain loads.
Extension: overflow checks (speed re-evaluation, 2026-11-27)
The same prover now also removes integer overflow checks. Trine Ints never silently wrap, so every +, - and * on Ints is checked. Measured on the generated C, those checks were the largest single cost in call-heavy integer code: in fib, the two checks on n - 1 and n - 2 stop the C compiler's recursion optimizations (55 ms with them, 9.4 ms without; C is 19.8 ms).
Rule. Every Int lies in [MIN, MAX], and every symbolic fact is exact, because each arithmetic step either traps on overflow or was proven not to. So for x + y:
- no overflow below MIN if
x >= 0ory >= 0(or the result is provably >= -2^62); - no overflow above MAX if
x <= 0ory <= 0, or the result is at most some other Int or length (i + 1wherei < n), or provably <= 2^62.
x - y is x + (-y) with one correction: x - y <= MAX needs y >= 0 or x <= -1, since 0 - MIN overflows. * keeps its check (nonlinear).
What gets removed. Loop counters bounded by a length or a limit, decrements under a sign guard (if n < 2: ... else: fib(n - 1)), differences of non-negative values. What stays: sums of unbounded values (fib(n - 1) + fib(n - 2), n + 1 for an arbitrary parameter n). trine bounds reports the count (arithmetic: N Int +/- proven unable to overflow).
Soundness checks.
- The VM still computes every erased operation with overflow detection and reports a
verifier bugif one would have overflowed; native debug builds (TRINE_VERIFY_BOUNDS) do the same, and the differential fuzzer runs both. - The fuzzer generates sign-guarded arithmetic at the edges (guards like
v <= -1, operands likev - 9223372036854775807, arguments near MIN and MAX). - Mutation test: two deliberately unsound versions of the rule (forgetting the
0 - MINcase; dropping the lower-bound condition) were each caught by the fuzzer within 3,000 cases.
Cost. Proofs are only attempted in the final marking pass, over facts connected to the operands: no measurable change in fuzzing throughput (90 programs/s before and after).
Also: list accesses proven in bounds now skip the range comparison in the inline fast paths too (before, a proof removed only the error branch).
Extension: multiplication (27a)
x * k with a constant k loses its overflow check when |x| ≤ 2^60 / |k| is provable (so i * 4 for an index i is free: lists and strings have at most 2^44 elements, a fact the prover now knows); x * y when both are provably within ±2^31. Same re-validation (VM, debug native builds) and the fuzzer's edge prelude gained bounded guards and products; a mutation that allowed |x| up to 2^62 was caught within 1,200 cases.