# Verify (/docs/experiments/verify)

Built-in verification of user programs (`marmot verify`, `marmot check -verify`) and the independent checks of the compiler's garbage collector contract. Each section gives what was tried, why, how it was measured, the verdict and the next step. Revisions are commits on main. Unless a section says otherwise, the Linux numbers come from a 16-core test machine and the macOS numbers from an 11-core machine.

## 1. Engine A: difference bounds over SSA [#1-engine-a-difference-bounds-over-ssa]

What: an abstract interpreter over the SSA form. It proves that index, slice, nil, divide, shift, make, append, assert, convert and close operations cannot panic. The domain is difference bounds (a - b &lt;= c) over SSA values, lengths and capacities. It has edge refinement from branch conditions, widening at loop headers, load numbering and callee summaries.

Why: most run-time checks in Go code are safe, and a proof makes them a fact the user and the compiler can rely on. Engine A had to be fast enough to run on every `marmot check`.

Measurement: `marmot verify` over 9 std packages (strconv, encoding/binary, bytes, strings, unicode/utf8, encoding/base64, encoding/hex, net/url, path), revision 4a438809.
- 476 functions, 2256 obligations, 1518 proved, 0 manifest reports.
- Index and slice sites, compared with gc's bounds check elimination (`-d=ssa/check_bce`): both prove 619 sites and only engine A proves 60. Only gc proves 30 (4.6% of the 649 sites gc proves). Neither proves 347.
- Speed on a 186-function package (macOS): a one-line edit costs 2.2 s against 1.85 s for `marmot check` (1.17x, the target was 1.5x). An unchanged rerun takes 0.1 s, a cold run 27 s.

Verdict: on by default inside `marmot verify`.

Next: a per-function cache keyed on normalized SSA, so that a large package does not reanalyze every function after a one-line edit.

## 2. Manifest reports and their guard rules [#2-manifest-reports-and-their-guard-rules]

What: a finding is "manifest" when the code's own guard lets the bad value through. For example, the code tests `len(b) < 2` and then reads `b[2]`. Other findings are latent preconditions. Only manifest findings are meant to be shown by default.

Why: a verifier that reports the precondition of every internal helper is noise. A guard that is visibly off by one is almost always a bug.

Measurement: `marmot verify ./...` on copies of two large open source trees.
- tuios (22506 functions): 7 false manifest reports during development, all removed by the guard rules (derived guards, guards tested elsewhere, other nodes in the guard). 0 since.
- golars (7099 functions): 2 false manifest reports found on 2026-11-16. A length equality guard (`if len(a) != len(b) { panic(...) }`) sat on the shortest path to the implicit `len(a) >= 0`, so the guard looked like a lower bound. Fixed in 9c897d24: a constant index or slice bound mismatches only when the guarded lower bound is above the implicit one. After the fix: 0 manifest, and every other count unchanged (24467 proved, 1896 latent, 13083 unknown).
- Rules "always" (fails on every input that reaches it) and "call-always" (a call that makes a same-package callee always panic): 0 findings on both trees.

Verdict: the guard rules are kept. Manifest findings stay notes until a labeled sample reaches 90% precision. The sample cannot be taken yet because there are too few manifest reports.

Next: manifest rule 3, callee preconditions that same-package callers violate.

## 3. Directed search and sandboxed confirmation [#3-directed-search-and-sandboxed-confirmation]

What: for open obligations, the search generates inputs: ints, bools, strings, byte slices, scalar slices, readers and zero values of package types. Each function runs in its own sandboxed process. A counterexample counts only when 3 reruns confirm it. The confirmation runs under both gc and marmot. A difference between them is reported as a likely compiler bug.

Why: a confirmed input turns "may panic" into a reproducible bug with a test.

Measurement: a recall corpus of 34 fixed real panics from open source projects with their fix commits. 24 entries run (the 10 std entries need older Go source trees).
- `marmot verify -search` found 8 of 24 with a confirmed input at the real bug site.
- With engine B models as seeds: 10 of 24 hit the buggy function, 8 at the real bug site.
- 378 confirmed counterexamples on the recall packages and yaml.v3. Of the 23 API-level ones, 7 were real. The other 16 were documented explicit panics or zero values of types that have constructors. Both kinds are excluded since 4a438809. After that: 7 API counterexamples, all 7 real (5 distinct bugs).
- Function level, a seeded sample of 50 labeled by reading the callers: 8 reachable (16%) and 42 internal preconditions. This class stays off by default.
- Library bugs found this way, checked against current upstream: excelize EDATE (fixed upstream) and x/image/tiff empty strip (fixed). Also gjson `@this` (fixed), and excelize TEXTBEFORE and TEXTAFTER on multi-byte text (still present, report drafted).

Verdict: opt in (`-confirm=sandbox`, `-search`). Nothing runs without the flag.

Next: more input shapes for structs and maps.

## 4. Engine B: z3 for what engine A leaves open [#4-engine-b-z3-for-what-engine-a-leaves-open]

What: an SMT encoding of loop-free regions (bit-vectors with Go's wrapping, division and shift rules, strings and byte slices with their bytes). Loops are cut at their headers with invariants that the solver checks itself (base and step, Houdini style). An unsat answer is a proof. A sat answer is a model that the search tries first.

Why: difference bounds cannot express bit operations, modular arithmetic or byte contents.

Measurement: the same 9 std packages, z3 with a deterministic resource limit, 2 s of solver time per function.
- 1559 proved, against 1518 for engine A alone. The gap to gc on index and slice sites shrank from 30 to 16 sites.
- Cost: about 8% over engine A.
- Encoder differential test against gc: 23 functions of every integer width, 9200 random and boundary inputs, 0 disagreements. While it was written, it found 2 encoder bugs.
- One wrong proof was found on the recall corpus (uint256 udivremBy1). A loop header invariant that holds only after a read before the loop was used to prove that read. Fixed in c8c96163: each query assumes only the invariants of headers that dominate its block.

Verdict: opt in (`MARMOT_VERIFY_SMT=on`). The fuzz day is clean, but on golars it costs 5x the CPU time for 0.45% more proofs (section 5).

Next: engine B for changed files only, with a budget.

## 5. Soundness fuzzer [#5-soundness-fuzzer]

What: `TestSoundFuzz` generates functions with indexing, slicing, division, signed shifts, branches, nested bounded loops and early returns. It runs engines A and B on them, then runs the functions under gc on random and boundary inputs. A panic at a line whose obligation of that kind was reported proved is a soundness bug.

Why: a wrong proof is the worst failure a verifier can have, and a single wrong proof was already found by hand (section 4).

Measurement: 100 programs per batch, 2 shards in parallel, 3 GB address space cap per process.
- First long run: one process grew to 6 GB and was killed (section 6).
- Run of 2026-11-16, 6 hours of run time per shard (12 CPU hours): 7600 programs and 175190 obligations proved. 128420 panic sites reached, 0 soundness bugs, no crash.
- Second half of the day (other seeds, test binary built from 11b186ca, which includes sections 7 and 2's golars fix): running.

Verdict: the fuzzer is the release gate for engine B as the default.

- Second half, 2026-11-17: 7400 programs, 170025 obligations proved, 124565 panic sites reached, 0 soundness bugs. The full day: 24 CPU hours, 15000 programs, 0 soundness bugs.

Cost on a large tree, measured before asking for the default: `marmot verify -nocache -j 4 ./...` on golars, on a loaded machine. Engine A alone: 529 s wall, 428 CPU s. With engine B: 3709 s wall, 2115 CPU s (5x). Gain: 109 more proofs (24467 to 24576, +0.45%), 106 fewer unknown obligations, 0 manifest reports either way.

Verdict: engine B stays opt in. It is sound as far as a day of fuzzing can show, but costs 5x for 0.45% more proofs on a real tree.

Next: run engine B only where it pays: the functions of changed files (the latent report for edited files), with a per-package solver budget.

## 6. SMT scripts with shared subterms [#6-smt-scripts-with-shared-subterms]

What: the SMT-LIB printer wrote every term as a tree. Loop-free code with many joins builds a DAG of if-then-else terms that share subterms, and the tree form is exponential in the number of joins. The printer now writes each shared non-leaf term once (`define-fun`) and refers to it.

Why: one fuzz program needed 6 GB of memory and the batch was killed.

Measurement: the failing seed (one program) took 6 GB and did not finish before. After 6fdfff80 it takes 7.5 s. A unit test with 80 levels of shared if-then-else needs a script under 64 KB and an answer from z3. It timed out at 60 s on the old printer.

Verdict: landed (6fdfff80).

## 7. Engine A stops when its work budget is spent [#7-engine-a-stops-when-its-work-budget-is-spent]

What: engine A has a per-function budget of edge relaxations. The budget was checked only after the fixpoint, so a function over budget still ran to the end and was then reported unknown. Now the fixpoint loop stops as soon as the budget is spent. The result is the same (the function is unknown either way), only faster.

Why: verify on a large dependency tree did not finish in an hour.

Measurement: `marmot verify -nocache -j 4` on the golars root package (it imports most of the tree), CPU time:
- Before (f731893f^): more than 1800 CPU seconds, stopped by the limit.
- After (f731893f): 223 CPU seconds (83 s wall). Functions over budget now cost about 1 s each.
- Whole trees, cold, `marmot verify -nocache -j 4 ./...`: golars 114 s wall (327 CPU s), tuios 307 s wall (503 CPU s). Before, golars ran for more than 62 minutes without finishing.
- A CPU profile showed 74% of the time in the shortest path search behind the join of two states. Almost all of it was in functions that were over budget.

Verdict: landed. Results are unchanged by construction.

Next: the per-function cache (section 1). A cheaper join for wide states would reduce the number of functions that exhaust the budget (13083 unknown on golars, 35531 on tuios).

## 8. marmot check -verify [#8-marmot-check--verify]

What: the flag was parsed but never copied into the check options, so `marmot check -verify` ran the other checks and skipped verify.

Measurement: a regression test runs `marmot check -verify` on a package with a known finding and fails without the fix.

Verdict: fixed (693a3404).

## 9. Verify policy for CI [#9-verify-policy-for-ci]

What: `marmot verify -write-policy` records per function how many obligations are proved, open and assumed in a committed file. Later runs fail when a function gets worse. A partial write keeps the baselines of packages it did not analyze, and a policy that does not parse is a usage error.

Verdict: landed (f4de98ee).

## 10. Independent check of the GC pointer bitmaps [#10-independent-check-of-the-gc-pointer-bitmaps]

What: a separate tool computes the layout of every type from the gc layout rules. It shares no code with the compiler. It compares the layout with the size, ptrdata and pointer bitmap of each type descriptor that the compiler emits. It also checks allocation sites and pointer stores against their descriptors.

Why: a wrong bitmap bit lets the collector free live memory. Such a bug shows up much later as memory corruption.

Measurement and findings:
- 2026-11-12, corpus of 430 programs: 29178 descriptors, 3716 allocation sites, 5333 stores, no mismatch.
- 2026-11-16: a wasm bug (one bitmap bit per 8 bytes on a target with 4-byte pointers) was not caught. There were three reasons. The tool modeled only the host target. Its model assumed 8-byte words. And since descriptors moved to a one-line encoding on 2026-11-13, it read almost no descriptors and still passed.
- Fixes: the layout model takes the target's pointer and integer sizes (988b8d6a). The tool reads the new encoding and fails when it finds a descriptor it cannot decode, or references without any descriptor (463a3ec3, 67d53b36). The driver script fails when a program does not build or when it checks nothing (11b186ca).
- Before the compiler fix, on the wasm target: 113 of 150 core programs had mismatches. After it: 149 of 149 buildable programs clean.
- The gate run found one more compiler bug on every target. The ptrdata of very large pointer arrays was cut at 8193 words (an 8 MB array of pointers had ptrdata 65544 instead of 16777216). The collector was safe because such types are scanned conservatively, but reflection composes ptrdata from it. Fixed in the compiler (1e5d699c).
- Gate result on bec6915b: host 166 programs, 1484 descriptors, 0 mismatches. wasm 165 programs, 1467 descriptors, 0 mismatches.

Verdict: the check now runs in the landing gate for both targets.

Next: the linked-binary check reads only Mach-O today. A wasm reader would also cover the backend's handling of the data.

## 11. Schedule exploration for tests (tier 3 lite) [#11-schedule-exploration-for-tests-tier-3-lite]

What: `marmot test -explore[=random|pct][:N]` and `-schedule=S` run a test's goroutines under a controlled scheduler. One goroutine runs at a time, with decision points at channel and sync operations. A failing schedule replays exactly.

Measurement: random and PCT schedules find a lost update and a lock-order deadlock, and the replay is identical. 80 of 80 schedules of 8 correct tests pass. The default scheduler is unchanged: the hooks build only with a tag, and ping-pong timing stayed within noise.

Verdict: landed, opt in.

Next: decision points inside sync.Mutex, a report of goroutines left running when the test returns, and partial order reduction (DPOR).

## 12. go-bce rule B4: lengths of slices made in the function [#12-go-bce-rule-b4-lengths-of-slices-made-in-the-function]

What: take `s := make([]T, x+K)` with K >= 0 and a nonzero element size. After it, len(s) is exactly x+K and at most 2^47. Otherwise makeslice panics, and x+K can only wrap to a negative value. A check i &lt; len(s) goes when a guard gives i &lt; x (K >= 0) or i &lt;= x (K >= 1). i >= 0 must follow from an unsigned guard, or from an induction over adds of bounded non-negative values. It also covers the form go-bool-pack leaves for a []bool. Opt in: MARMOT_BCE_B4=1.

Why: research (verify-research.md) showed nsieve spends 57% of its instructions in checks that no pass removes, gc's included. The check `flags[j]` with `j <= n` and `len(flags) == n+1` needs exactly this fact.

Measurement: in the per-package object, B4 removes nsieve's inner-loop check (12 instructions per iteration down to 10). In the linked -release binary the instruction count does not move: 37.168 G with and without B4 (callgrind, both counts within 0.0001%). The whole-program build already keeps that check out of the hot path. And the 57% ceiling for nsieve was confounded. Without index ops, go-bool-pack does not apply. So the no-check build used a byte array instead of bit operations. Two more findings came from the measurement. The backend's object cache key lacked MARMOT_BCE_B4, so a B4 build reused objects from a build without it (fixed on the branch). And with the switch off, hello and all 44 bench programs are byte-identical to main.

Review and testing: backend reviewed the pass, tier0 read the Lean lemmas and the programs. Three soundness bugs were found before landing, each now a test:
- an unsigned guard i &lt;u y with y = len - K, which can be negative (backend).
- a lower-bound guard (i >= n) taken as an upper bound in the non-negativity induction: an index stepping by 2^40 wraps negative (tier0).
- a crash: the pass asked for the dominator tree of a single-block region. The adversarial programs found it. MLIR only asserts it, and release builds compile the assert out. Independent re-check: verify/check re-derives every B4 removal from the MLIR and rejects the out-of-rule ones (TestB4). verify/lean/B4.lean proves the arithmetic. madelen.go matches Go in dev, go dialect and release, with and without B4, plain and with poison and GC stress. tests/fuzz generates the shapes of all three findings.

Verdict: not landed. It is sound as far as review, the second check and the tests show. But it brings no measured gain on the bench programs, so it would be code without a benefit. It stays on the branch.

Next: Rule V's misses (section 13), where the ceiling is not confounded (matmul's float loops).

## 13. Rule V's misses [#13-rule-vs-misses]

Rule V (loop versioning for bounds checks, LLVM level) runs only inside the parallelize pass, and backend/lib/Loops/Register.cpp adds that pass only with -par. So default release builds version no loop at all. Within -par it is all-or-nothing, and it only versions a loop when the fast copy would also run in parallel, or when the loop appends. The precondition costs time on every loop entry, and fannkuch's 2 to 3 iteration flip loop showed it. Experiment: a private switch that skipped the parallel requirement left matmul, fannkuch, quicksort and heapsort byte-identical. So these loops are rejected for another reason. matmul's inner loop checks j against len(b[k]), a length loaded from a base that changes in the loop, which rule V cannot bound. quicksort's and heapsort's checks are data dependent.

Verdict: dropped as a policy change. It gains nothing on these programs.

Experiment (2026-11-17, private build): a versioning-only pass (MARMOT_LOOPS_VERSION=1, a backend option in the cache fingerprint) on the 18 bench programs that have checks. All outputs are equal to the default build. matmul's loops were first rejected because rule V's loaded-bound support is off by default (-loops-bcv-loaded). With it on, both matmul loops are versioned (check loops per entry, no hoisting). Instruction counts (callgrind, default against version-only) are UNVERIFIED. They were built with a kept cache by a rebuilt backend (the cache key gap of 2026-11-18). Cycle counts from perf stat replace them. fannkuch 13.54 G to 17.98 G (+33%, worse), generic 7.00 G to 8.50 G (+21%, worse). matmul with loaded bounds 133.3 G to 118.1 G (-11.4%), matmul without them unchanged. regexpbench, sortslice, stringsearch, nbody, wordfreq, parse and quicksort within 0.4%. Versioning short loops costs more than it saves (the precondition runs on every entry), which is why rule V was limited to parallel loops. Verdict: not without a cost policy that keeps short loops out.

A first cost policy versions only two kinds of loops. One kind has a maximum trip count that is a known constant of at least 16. The other is a top-level loop whose trip count is not a small constant. With it, fannkuch is back to its baseline (13.539 G), matmul -11.4% (118.06 G, with -loops-bcv-loaded), and generic still +21% (8.49 G). Generic versions one loop of main.main and two loops of the runtime's fdecimal.leftShift. Cause of the +1.5 G: the versioned loop is the pop loop (s.items[len(s.items)-1] with a shrinking length). (a) Its precondition contains "i + len + 1 &lt; 0" (icmp slt), which is false in every run. So the fast copy never runs: sound, but useless. Rule V's precondition for a decreasing index is too strong. (b) The guard is expanded from the push loop's exit values. So LSR keeps extra induction variables live in the push loop (not versioned). That loop now spills about 8 values per iteration (about 10 instructions x 150M iterations). The slow copy's IR equals the original loop. Skipping loops that call growslice changed nothing (8.489 G).

Fixes after the backend review (10:16): -loops-bcv-stride and -loops-bcv-pin. With -loops-bcv-stride, equal-step sides compare the difference once, x != 0 with x affine needs min(x) > 0, and nil_sound holds. With -loops-bcv-pin, precondition SCEVs use IR values that exist before L. First a header phi with a constant offset, then any outside value with an equal SCEV, and the latch count too. RuleV.lean: stride_sound, Aff.start_small (break test: weakening slt to 0 &lt;= d fails). Lit test backend/test/loops/versioning-stride.mlir. With both and -loops-bcv-loaded: generic 7.00 G to 5.83 G (-16.7%, below the no-check ceiling of 6.10 G: the fast pop loop vectorizes). The push loop still spills (register allocation over the larger function, not the guard, which now uses only the push loop's final values). All 18 bench outputs equal. Binaries up to +0.6%. Bench set counts: job verify-vo-cg7.

Next: remeasure the bench set, then a perfcmp gate. Hoisting only if it adds at least 3%.

Perfcmp at 381316a0 (2026-11-18, -b-env MARMOT_LOOPS_VERSION=1, O2 and release): INCONCLUSIVE (load 11.3), would have said WORSE: O2 matmul 1.353 wall, mapstr 1.137, bintrees 1.055. Release iface 1.180. Every bench binary differs because cold runtime loops are versioned (goargs, MemProfile, memprofRecords, fdecimal.leftShift), so rows without a hot change are layout or noise. Matmul O2 is real. The loaded-bound check loop runs on every entry of the inner k loop: 400 iterations of a serial cmov min chain over the row lengths. The fast loop is bound by the float add latency. So fewer instructions give more cycles. Callgrind cannot see this. Lesson: measure wall time (perfcmp) before trusting instruction counts for a versioning change. Loaded bounds need the check hoisted out of the loop nest to pay.

Next: first, rule V in versioning-only mode for default release builds, with no parallelization. A cost policy takes the place of the parallel requirement. Measure it on the bench set. Then partial versioning, which removes the covered checks and keeps the rest (in matmul, 2 of 3 checks per inner iteration). The fast copy then has several exits and no longer vectorizes, so its gain is the compare and branch per removed check. The Lean proof must cover the mixed case, and backend reviews it.

Cached check loops (f0cd1ac2, 12779e92, 2026-11-18): the loaded-bound check loop runs at the guard of L. It runs only on the first entry of L in a run of M (done flag), not per entry. Matmul, perf stat cycles:u, 9 interleaved runs through at.sh, medians: O2 84.4 G to 64.6 G cycles (-23.6%), release 79.4 G to 66.5 G (-16.3%). Instructions 133.3 G to 61.7 G, equal to the no-check ceiling (61.6 G). Outputs equal. Busy host (runs from 57 to 142 G): the perfcmp decides. Generic (pin, stride), 11 runs: O2 -8.2%, release -2.6% cycles (noisy). No-check ceiling in cycles (release, 5 runs): matmul -14.6%, fannkuch -10.4%, regexpbench -10.0%, heapsort -6.2%, quicksort -4.4%, generic -2.0%, sortslice +1.2%.

## 14. Where the fannkuch and regexpbench ceiling checks sit (2026-11-19) [#14-where-the-fannkuch-and-regexpbench-ceiling-checks-sit-2026-11-19]

fannkuch (ceiling -10.4% cycles, gc keeps 6 index checks, all in main.fannkuch):
- line 23, perm[i], perm[j] in the flip loop (i up, j = k down): the hottest. A short inner loop (k/2 iterations, k = perm[0] &lt;= 10), its bound k is loaded from perm. Rule V can cover it with an O(1) precondition (k &lt; len(perm), no check loop). But the cost policy skips it: it is a nested loop with a max trip count that the policy cannot see. The +33% instructions of 11-17 (first version-only try, before pin and stride) came from this loop's guard and the spills it caused.
- line 21, perm[0] once per flip. Lines 17, 41, 43: rare (permutation step), not worth versioning. Next step (experiment): a cost policy by precondition cost instead of trip count. It allows a nested short loop when its precondition is a few compares and has no check loop. Measure fannkuch cycles (and the bench set) through the queue.

regexpbench: the ceiling is -10.0% cycles. gc keeps 1 index check in main and about 300 in regexp and regexp/syntax. These are onepass.go 74, regexp.go 63, syntax/parse.go 60, compile.go 29, backtrack.go 18 and exec.go 17. So the gain is in the standard library. 12779e92 excludes it from versioning on purpose, because it is cold in most programs. Most of these checks index by instruction numbers or input positions loaded from memory, which rule V cannot bound. Not a rule V target. PGO (hot std code) or a different rule would be.

## Dropped or deferred [#dropped-or-deferred]

- Showing function-level counterexamples by default: dropped for now, because only 16% were reachable in a labeled sample (section 3).
- Manifest findings as errors: deferred until a labeled sample shows at least 90% precision.
- A per-package wall clock limit inside long verify jobs: replaced by CPU time limits. Wall clock limits counted the time that a benchmark froze the job, and gave false timeouts.

### fannkuch short-loop versioning, cycles (2026-11-19, job verify-sh-0607e43159-1119-181546) [#fannkuch-short-loop-versioning-cycles-2026-11-19-job-verify-sh-0607e43159-1119-181546]
perf stat cycles:u, 11 interleaved runs, medians. 0 = default, 1 = MARMOT_LOOPS_VERSION=1, 2 = 1 plus -loops-version-short -loops-version-short-conds=12. Variants 0 and 1 build identical binaries at both modes, so 0 vs 1 (-3.5% O2, -1.0% release) is the noise floor. All outputs match.
- O2: 2 vs 0 +24.7% cycles, +15.5% instructions.
- release: 2 vs 0 +13.1% cycles, +25.5% instructions. Verdict: versioning the flip loop loses. The loop runs few iterations per entry, so the guard runs on almost every entry and costs more than the checks it removes. Keep -loops-version-short off (it is opt-in only). Implied-condition pruning stays (it shrinks every guard and changes nothing when the switch is off).