56. Tests are generated by metaprograms from contracts, types and theories; a case the verifier can decide is proved, and only the rest is run¶
Date: 2026-11-23
Status: Accepted (Dean, 2026-11-23), with his answers to the three questions, recorded at the end.
Context¶
Dean asked (2026-11-23) for a unit testing framework that is "a little more special than the usual": test case generators, written as metaprograms, driven by a theory of what the unit under test should support, with cases derived from the contracts of its interface and from combinatorial generation over the static properties of the modules under test. He asked whether that is feasible with Pia's metaprogramming, and for a sketch.
It is feasible, and most of the parts exist. This ADR says what testing is for in a language whose programs are already proved, where the cases come from, what decides whether a case passed, and the metaprogram builtins that are missing.
What testing adds when the code is proved¶
A proof says the code meets its contracts on every input, assuming everything the proof rests on. Tests are for what the proof rests on, and for what the contracts do not say:
| Gap | Example | What a generated test does |
|---|---|---|
| Trusted boundaries | an extern whose ensures is trusted; an assume in a @trusted file; a theory imported trusting (ADR 0036); a goal accepted with --allow-unproved |
runs the code across the boundary on generated inputs and checks the trusted facts at run time |
| Foreign code | C and C++ called through FFI, and the generated POSIX bindings (ADR 0051) | the same, plus differential runs against the C++ it replaces |
| The compiler | a wrong lowering in IRGen or codegen, which the proof cannot see (ADR 0023) | runs the compiled code on cases whose answers the verifier already knows; under a sanitizer, a report in proved code is a compiler bug (ADR 0025) |
| Behaviour the contract leaves out | complexity clauses, which ADR 0040 documents and does not prove; time, memory, throughput | benchmarks and scaling runs with budgets |
| A specification that says the wrong thing | a contract that is proved but too weak (ensures result <= len xs on a search that always returns 0) |
examples that pin the intent: an expected output the contract allows but does not imply is reported as "not implied by the contract", which says the contract is too weak |
| Change over time | a contract weakened in a refactor, a slower proof, a different result on the other target (ADR 0049) | a regression corpus kept with the module, run on both targets |
| Floats | tolerances proved against real-valued specifications (ADR 0038), and devices that cannot prove one | runs against a reference at higher precision |
The standard library already does this by hand. Each module in tests/std has a goal-count test, an _edges.pia file of facts an importer can prove from the interface alone, and a _run.pia program whose exit status is the number of the first wrong answer, with the edge cases of the C++ standard written out (ADR 0040, section 12). ADR 0054 plans differential tests against giflib and zlib and fuzzing for the codecs. All of these are written by hand today, and they are what this ADR generates.
What exists¶
- Metaprograms can read the program.
listing ()returns every item, and on a function itemhypotheses,conclusionandparamsgive itsrequires, itsensuresand its parameter names.children,opandkindwalk any syntax, including a parameter's type, andmake_callbuilds calls (docs/meta.md). Tactics (ADR 0036, step 6) are built on exactly this, so contract-driven generation needs no new kind of metaprogram. - Expansion runs to a fixed point (ADR 0007), and what a metaprogram produces is type checked and proved like hand-written code. So a generated test is ordinary Pia, and can be read with
--dump-expanded. - Types carry the static properties. Integers are ranges (
int{lo..hi},u8), arrays have lengths, records have fields, variants and error sets are closed (ADR 0028), and the type-level builtins (type_kind,field_types,element,size_of) read them. - Theories say what a unit should support. A
let theorydeclares sorts, operations and axioms, and a model proves the axioms (ADR 0036). Concepts carry laws (ADR 0034). The prelude'smachinebuilds a theory from a table of transitions. - Interfaces carry contracts across modules. A
.piaiholds every exported signature with its contracts (ADR 0039), so a black-box test of a module needs only its interface. - The verifier finds counterexamples, and models are tried first for them (verifier.md). A counterexample is a test case.
- The REPL proves and runs cells (ADR 0031), and a session file replayed through
pia replis already a test.pia mcpexposes the same to agents.
Decision¶
1. Prove what can be proved, and run the rest¶
A generated case is an input together with an oracle, a fact that must hold of the output. Every case is first offered to the verifier as a goal, with the inputs as constants:
- Proved. The case holds for the source program. It is reported as proved, and by default not run. It costs one cached query, and it guards against regressions for as long as it stays in the corpus: if a later change makes it fail, the build fails with the counterexample.
- Not decidable statically. The answer depends on something outside the proof: an
extern, a trusted axiom, the compiled code itself, a float on a device, a timing. The case is compiled into the test binary and run. - Refuted. The verifier shows the case fails. That is a bug found at compile time, reported like any failed goal, before anything runs.
This is what makes the framework different from QuickCheck or a unit test runner: the generator produces many cases, and most of them never execute, because a fully proved unit decides them all. What is left to run is exactly the part the proof cannot vouch for. Proved cases stay available to test the compiler (Dean, 2026-11-23). --run-proved runs every case anyway, and the compiler's own test suite, the sanitizer jobs and both targets' CI run with it, so the cases generated for the standard library also check IRGen and codegen.
2. Where cases come from¶
Each source is a metaprogram in a new prelude module, Pia.Test.Gen, written in Pia. A user can write more, since they are ordinary metaprograms.
| Generator | Reads | Produces |
|---|---|---|
edges |
each parameter's type: a range int{lo..hi} or an integer type, an array's length, a record's fields, a variant's constructors |
boundary values per parameter: lo, lo + 1, hi - 1, hi, zero where it is in range, and the constants that the requires compare a parameter with, on both sides (from i < len xs, the cases len xs - 1 and len xs) |
combine |
the per-parameter domains | their product, filtered by the requires; above a budget, a pairwise covering array instead of the full product |
paths |
the function's branches and match arms, through the verifier | one witness per feasible path: Z3 is asked for a model of the requires together with the path condition. An infeasible path is reported as dead code |
errors |
the closed error set of a result t e |
for each constructor of e, an input that returns it, found by the solver; or a proof that none does, reported as an error constructor that is never produced. The same for each arm of a handle block |
laws |
a theory's axioms, or a concept's laws | property tests: each axiom instantiated over generated values of its sorts, for a model that is trusted or foreign and so is not proved |
walks |
a machine theory, or module state with an invariant (ADR 0006) |
sequences of operations that cover every transition, and every pair of transitions up to a depth, with the invariant checked after each step |
against |
a reference implementation, usually C++ through FFI | differential cases: the same inputs to both, outputs compared |
corpus |
the module's checked-in case file | the regression cases: every counterexample the verifier ever reported for the module, every failing run, and hand-picked examples |
edges, combine and corpus read only syntax and types, so they are ordinary expansion-time metaprograms. paths and errors need the solver, so they run in a test stage after verification (section 5).
3. What decides a case¶
- Postconditions. The
ensuresof the unit is the default oracle. In a test build, the compiler checks eachensuresof a unit under test at run time, together with theensuresof everyexternit calls. This is thecontractsmode of--sanitizefrom ADR 0025, restricted to the units a test names. The generator does not have to rewrite contracts into code itself. - Laws and axioms, for
lawsandwalks. - A reference, for
against: equal outputs, or outputs within a stated tolerance for floats (the~=form of ADR 0038). - Round trips, as a law between two functions:
decode (encode x) = x. - Expectations the author writes, for intent the contract does not state.
- Budgets, for performance (section 6).
4. The surface¶
Tests can be written in two places, and both work the same way (Dean, 2026-11-23):
- In the module, in test mode, as Rust does. A top-level generator call, or a hand-written test, carries
@test. It is expanded, proved and compiled only bypiac --test(and the REPL's:test), and an ordinary build drops it before expansion, so it adds nothing to the module's interface, its proofs or its object code. It sees the module's private functions. - In a separate test module that imports the interface under test, as
tests/std/*_edges.piadoes, so it sees only what the module exports. This is the black-box form, and the standard library uses it.
Cases are top-level calls of generator metaprograms, with no new keyword. A sketch, in proposed syntax, of a separate test module:
import Pia.Core.Clamp.Clamp as C
import Pia.Test.Gen { cases, edges, paths, errors, laws, against, corpus }
\ Boundary values from the types and the requires, combined, filtered by the
\ precondition, checked against the ensures. Proved cases are reported, not run.
cases C.clamp [edges; paths]
\ For a function returning `result t e`: one case per error constructor.
cases Json.Lex.next [edges; errors]
\ Pia.Algo.sort against libc++'s std::sort, through a generated binding.
cases Algo.sort [edges; against Cpp.std_sort; corpus "tests/std/cases/sort.piac"]
\ A foreign type claims Ord: its laws are tested, since its model is trusted.
laws Ord Posix.timespec
In the module itself, the same call is marked for test mode:
let clamp (v : u8) (lo : u8) (hi : u8) : u8
requires lo <= hi
ensures lo <= result && result <= hi
= if v < lo then lo else if v > hi then hi else v
@test cases clamp [edges; paths]
In the REPL, :test C.clamp runs the same generators on a definition in the environment, and pia mcp gives agents the same command. piac --test builds and runs a test file, and a pia_test Bazel rule in tools/piac/pia.bzl does the same in the build.
5. Stages¶
- Expansion. Generators that read only syntax and types run with every other metaprogram, and produce the case items.
- Verification. Each case is a goal (section 1). The verifier's results decide which cases are compiled.
- Witness generation.
pathsanderrorsask Z3 for models. Whether the answers are kept is the user's choice (Dean, 2026-11-23):piac --test --cases=DIRwrites them to a case file per module and reads them back on later builds, and without it they are found again on each build. A case file makes a build deterministic, keeps a change of solver from changing the tests silently, and shows in review what was added. This repository checks its case files in, so that what was generated can be inspected and debugged. Either way, what was generated can always be seen:piac --test --dump-casesprints every case with its source (which generator, which parameter's boundary, which path or error constructor) and how it was decided, and:sourcein the REPL shows a generator call's expansion. - Run. The undecided cases are compiled into one binary per test file, which reports each case. Under
--sanitize=address,undefinedit doubles as the sanitizer run.
A metaprogram that calls the solver is not total in the sense of ADR 0035: it depends on a solver's answers. So it may not be called from a type, a where predicate, a theory builder or a tactic, only from a test file.
6. Beyond functional cases¶
- Performance.
bench f [sizes 1000; 10000; 100000] within ns 50 per nrunsfon generated inputs of each size and checks a budget, and a complexity claim in a doc comment ("at mostlog2 n + 1comparisons") is checked by fitting the measured counts. Budgets live in the same baseline file style as the proof benchmark (ADR 0032,tools/bench/baseline.json). - Fuzzing. The case file is the seed corpus for libFuzzer once
--sanitize=fuzzerexists, and the generators' domains describe the input's structure, so a fuzz harness is generated rather than written. - Both targets. The run stage runs on arm64 macOS and x86_64 Linux (ADR 0049), so a case that passes on one and fails on the other shows a target difference the theory did not model.
7. The report¶
The report follows the other reports of the project: wall-clock time for generation, proof and run; for each unit, the number of cases from each generator, and how many were proved, ran and passed, ran and failed, or were skipped by the precondition; the costliest case goals; every trusted fact a run checked; and the error constructors and paths that no input reaches. A failing case is printed as a call with its arguments, which can be pasted into the REPL.
Prototype¶
The generator below was prototyped in pia repl on 2026-11-23 (macOS arm64, a build of main near #321), using only the metaprogram builtins that exist today. It reads clamp's parameters, parameter types, requires and ensures from listing (), forms the product of the boundary values, and generates one function, clamp_cases, that returns 0 when every case passes and otherwise the number of the first case that fails. A case whose requires is false is skipped. The oracle is the ensures, with the call substituted for result.
let clamp (v : u8) (lo : u8) (hi : u8) : u8
requires lo <= hi
ensures lo <= result && result <= hi
ensures (lo <= v && v <= hi) ==> result = v
= if v < lo then lo else if v > hi then hi else v
\ List helpers the interpreter lacks, written with fold. A pair is a function of a bool.
let meta nth (xs : list) (i : int) : syntax =
(fold (let (acc) (x) =>
let k = acc true in
(let (b) => if b then k + 1 else if k = i then x else acc false))
(let (b) => if b then 0 else fail "nth: index out of range") xs) false
let meta drop1 (xs : list) : list =
(fold (let (acc) (x) =>
let seen = acc true in
let got = acc false in
(let (b) => if b then true else if seen then concat got [x] else got))
(let (b) => if b then false else []) xs) false
let meta indices (xs : list) : list = fold (let (a) (x) => concat a [length a]) [] xs
let meta reverse (xs : list) : list = fold (let (a) (x) => concat [x] a) [] xs
let meta product (doms : list) : list =
let none = [] in
fold (let (acc) (d) =>
fold (let (sofar) (tuple) => concat sofar (map (let (x) => concat tuple [x]) d)) [] acc)
[none] doms
let meta find (n : string) : syntax =
let it = fold (let (acc) (i) => if kind i = "LetItem" && name i = n then i else acc)
`( 0 ) (listing ()) in
if kind it = "LetItem" then it else fail (concat "no item named " n)
\ Substitution of `result`, rebuilding operators as calls of their builtins.
let meta builtin_of (o : string) : string =
if o = "&&" then "and" else if o = "||" then "or" else if o = "==>" then "implies"
else if o = "<==>" then "iff" else if o = "=" then "eq" else if o = "<>" then "ne"
else if o = "<" then "lt" else if o = ">" then "gt" else if o = "<=" then "le"
else if o = ">=" then "ge" else if o = "+" then "add" else if o = "-" then "sub"
else if o = "*" then "mul" else if o = "/" then "div" else if o = "%" then "rem"
else fail (concat "subst_result: no builtin for operator " o)
let meta subst_result (e : syntax) (r : syntax) : syntax =
if kind e = "Name" && op e = "result" then r
else if kind e = "Apply" then
make_call (op e) (map (let (c) => subst_result c r) (drop1 (children e)))
else if kind e = "Binary" then
make_call (builtin_of (op e)) (map (let (c) => subst_result c r) (children e))
else e
let meta conj (xs : list) : syntax = fold (let (a) (h) => `( $a && $h )) `( true ) xs
let meta param_type (p : syntax) : syntax = nth (children (nth (children p) 0)) 1
\ The generator: the contract of `n`, the implementation `impl`, a domain per parameter.
let meta cases_for (n : string) (impl : string) (doms : list) : item =
let it = find n in
let ps = params it in
let tys = map param_type (children (nth (children it) 0)) in
let idx = indices ps in
let pre = conj (hypotheses it) in
let call = make_call impl ps in
let post = subst_result (conclusion it) call in
let check = `( if $pre then $post else true ) in
let one = (let (tuple) =>
fold (let (body) (i) =>
let p = nth ps i in
let t = nth tys i in
let v = nth tuple i in
`( let $p : $t = $v in $body ))
check (reverse idx)) in
let rows = product doms in
let fname = concat impl "_cases" in
let case_name = (let (k) => concat (concat impl "_case_") (k + 1)) in
let chain = fold (let (rest) (k) =>
let cn = case_name k in
let num = k + 1 in
`( if $cn then $rest else $num ))
`( 0 ) (reverse (indices rows)) in
let run = fold (let (body) (k) =>
let cn = case_name k in
let c = one (nth rows k) in
`( let $cn : bool = $c in $body ))
chain (reverse (indices rows)) in
`( let $fname () : u32 = $run )
let meta cases (n : string) (doms : list) : item = cases_for n n doms
cases "clamp" [[0; 255]; [0; 255]; [0; 255]]
What the REPL reported:
| Run | Result |
|---|---|
cases "clamp" over [0; 255] for each parameter (8 cases) |
clamp_cases : u32 = 0, 24 goals proved (the precondition of clamp at each call in the substituted postcondition); 271 ms in the solver, 10.5 s verifying, 13.4 s for the cell |
over [0; 1; 255] (27 cases) |
0, in about 2 minutes 12 seconds |
over [0; 1; 254; 255] (64 cases) |
not finished after 9 minutes, and stopped |
cases_for "clamp" "clamp_bad", where clamp_bad is if v < lo then lo else v with no ensures |
clamp_bad_cases : u32 = 5: case 5, v = 255, lo = 0, hi = 0, breaks result <= hi |
the same run function with ensures result = 0 |
for clamp, proved (25 goals) from clamp's contract alone; for clamp_bad, refuted at definition, so nothing is committed |
The last row is section 1 in miniature: for a proved unit, the generated cases are decided by the verifier and add nothing at run time, and for an unproved one they are refuted before anything runs. The bad implementation had to be a separate function tested against clamp's contract (cases_for spec impl), because a proved unit cannot be given a bug: --allow-unproved accepts an unproved goal, not a refuted one.
What is missing¶
The prototype works, and it shows what a real generator needs that the metaprogram language does not have:
- More than one item from a metaprogram. A metaprogram returns one item, and a quote cannot splice a variable number of items. So every case went into one function, where one function per case would let the verifier and the report treat each case separately, and in parallel.
- Speed. 8 cases took 13 seconds, 27 about 2 minutes, and 64 did not finish in 9 minutes. The solver took 271 ms of the 13 seconds: the cost is in the verifier around it, and the REPL appears to verify the environment again on every cell. Generated tests multiply goals, so this is the first thing to fix, and it is a verifier issue more than a testing one.
- Signature reflection.
paramsgives names only. The prototype reaches each type by position (Params, thenParam, then its annotation's second child). Generators needparam_types f,return_type f, for a type the bounds of its range (range_of t, givingloandhi), and the constructors of a variant or an error set (constructors t, with payload types). - List operations. The interpreter's lists have
map,fold,lengthandconcat. The prototype writesnth,drop1,indices,reverseandproductwithfold, quadratically. They belong in the interpreter or in a prelude module of list metaprograms.[[]]does not parse, andfold's initial value is evaluated eagerly, so afailthere fires even when it is not needed. - Substitution.
subst e name valuereplaces a name in syntax. The prototype substitutes the call forresultby walking the syntax, and has to handle two forms of the same operator, becausehypothesesreturns operators already expanded to calls (le a b) whileconclusionjoins clauses with an unexpanded&&. Both should return the same form. Substituting the call also calls the function once perresult, where a binding would call it once. - Contracts as code mean something different. A contract is evaluated over unbounded integers, but a case that copies it into code runs it at the operands' types.
ensures result + 1 = dondec (d : int{-2..2}) : int{-3..1}proves as a contract, and fails as a case (found in step 1,tests/meta/generators.pia):1 + 1overflowsint{-3..1}. So an oracle copied from a contract must be checked in the contract's own semantics, as a goal overintor by the run-timeensurescheck below, not as ordinary code. - Interfaces.
listing ()lists the current program. A black-box test needsexports I, the items of an imported interface with their contracts, read from the.piai. - Solver access, for stage 3:
witness f pathandreach f constructor, which return a model ornone, cached in the case file. - A run-time check of an
ensures, in codegen, which is thecontractssanitizer of ADR 0025 limited to the units under test. With it, a generator produces inputs only and needs no substitution for the oracle. - Seeing what was generated. Every goal of a generated case is located at the generator's call, so a failure cannot name its case, and the REPL has no
--dump-expanded. A generated item should carry the location of the case that made it, and:sourceshould show the expansion. - Smaller things. A parameterless
let f () : u32is a value, computed when it is defined, so the cases ran at definition (which is useful, but should be a choice).outandroware reserved and cannot name a lambda's parameter, with the unhelpful error "expected a pattern".listingmakes a generator impure, so it can never be a tactic or a theory builder, which is consistent with section 5.
Implementation steps¶
Each step is one PR with its tests, and each replaces some hand-written test in tests/std.
- What the prototype needed: several items from one metaprogram, list operations,
param_types,return_type,range_of,constructorsandsubst, one form for expanded contracts, and generated items located at their case, insrc/meta/Interpreter.cpp,Expand.cppand a prelude module, with tests intests/meta. The verifier cost per cell in the REPL is a separate issue, #334. Done, except for locating generated items at their case: several items from one metaprogram (a list),nth,zip,range,reverse,filter,product,param_types,return_type,range_of,constructors,subst, andconclusionjoined in the form its clauses are in (meta.md,tests/meta/generators.pia). Pia.Test.Genwithedgesandcombine, generating cases whose oracle is written out bysubst, and the proved, refuted and run triage of section 1. The first user is onetests/stdmodule whose_run.piabecomes generated.- Test mode:
@testitems dropped from ordinary builds, run-timeensureschecks in test builds,piac --test,--run-proved,--dump-casesand thepia_testrule. - Case files (
--cases=DIR) and the regression corpus, with every verifier counterexample offered to the corpus. pathsanderrorsthrough the solver, cached in the case file.lawsandwalks, for concept laws, trusted theories andmachines.against, differential tests against C++ through generated bindings, starting with thetests/stdmodules that map C++23 components.:testin the REPL and the MCP server.bench, then fuzz harnesses once--sanitize=fuzzerexists.
Consequences¶
- Tests of proved code are cheap: most cases cost a cached query and never run, and the run binary holds only what the proof cannot vouch for.
- Every trusted fact gets a test without anyone writing one: an
extern's contract, a trusted theory's axioms and a foreign type's concept laws are all checked on generated inputs. - An error constructor that is never produced, and a path that is never taken, become findings, which a proof alone does not report.
- The regression corpus grows by itself from counterexamples, and lives next to the module in review.
- Metaprograms gain a stage that may call the solver. Keeping it to test files, and caching its answers in the case file, keeps ordinary expansion total and builds deterministic.
- Generated cases can grow combinatorially.
combinehas a budget and falls back to pairwise coverage, and the report says when it did.
Questions for Dean¶
- Surface. Top-level generator calls in a separate test module that imports the interface, or an attribute on the definition itself, which also reaches private functions?
- Proved cases. Report a proved case and not run it by default, with
--run-provedfor CI and sanitizer jobs, or always run every case? - Solver-found cases. Write them to a case file checked in beside the module, or find them again on each build?
Answers (Dean, 2026-11-23)¶
- "It should be doable in either. I see value in having test cases in the module themselves, like what Rust does, in test mode." Section 4 now has both:
@testitems in the module, built only in test mode, and separate test modules over the interface. - Yes, proved cases are not run by default, "but they should be available for the compiler testing cases." Section 1:
--run-provedis what the compiler's own tests, the sanitizer jobs and CI use. - "That should be up to the user. For us, I think it's worth seeing what it generates so that we can inspect and debug it." Section 5:
--cases=DIRis the user's choice, this repository checks its case files in, and--dump-casesalways shows what was generated.
Prior art¶
- QuickCheck and Hypothesis: property tests with generators and shrinking. Here the properties are the contracts, and most cases are proved rather than run.
- Pex and IntelliTest, KLEE, and concolic testing generally: inputs found by a solver, one per path. Here the solver is the verifier's own, and it already has the path conditions.
- Dafny's test generation (
dafny generate-tests) and SPARK's combination of proof and test (DO-178C credit for proof): cases from verified specifications, with tests kept for what is not proved. - Category partition and pairwise covering arrays (Ostrand and Balcer; NIST ACTS): boundary values and combinations from the input domains.
- Csmith and translation validation: differential testing of a compiler against a reference.