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)

  1. 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 have len(result) == n or len(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, on json.tr it infers that parse positions are never negative (Parsed field 1 >= 0, skip_ws: result >= 0). On matmul.tr it infers zeros: len(result) == n.
  2. 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 fact j < len(cs) holds. It knows len(range(n)), that element k of range(lo, hi) is lo + k, that split never returns [], that x*y >= y when x >= 1, y >= 0, the bounds of min/max/%, and that a value merged from two branches equals one of them.
  3. 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 as len(out) - i == entry difference ("they move together") and best_i - i <= -1 ("one stays ahead"); - bounds by unchanged values, e.g. i <= len(xs).
  4. 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).
  5. 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

programindex sites provenrun-time checks erased
json25 / 2530,308 / 30,308 (100%)
primes5 / 547,499 / 47,499 (100%)
raytrace7 / 710,821 / 10,821 (100%)
server18 / 20100,123 / 100,125 (99.998%)
values4 / 51,003 / 1,004 (99.9%)
shapes1 / 13 / 3
higher_order3 / 435 / 39 (89.7%)
matmul12 / 1792 / 136 (67.6%)
calc, fbip, hellono index operations—
total75 / 84 (89%)189,884 / 189,935 (99.97%)

The 9 checks that remain, and why they should

sitewhy 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

  1. An independent referee. trine bounds file.tr --smt out.smt2 exports every proof obligation (facts plus negated goal) as SMT-LIB. tools/z3_check.py confirms each one is UNSAT with Z3: 1,358 / 1,358.
  2. 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.
  3. 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.
  4. **Locked into cargo test:** bet2_erased_checks_preserve_behaviour, bet2_most_bounds_checks_erased, bet2_proofs_cross_checked_by_z3 and bet2_never_erases_a_needed_check.

Engineering notes (what went wrong on the way)

Threats to validity

  1. 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.
  2. Golden programs are small, and the loop patterns are the common ones. Unusual loops (stride tricks, index arithmetic through multiplication) will keep more checks.
  3. "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:

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.

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.