Formal Verification and Testing Foundations
You cannot prove what a language model will say. You can often check, exhaustively or systematically, what your system will let it do.
Testing runs chosen cases; formal verification reasons about all cases within a stated model. Neither proves that a language model behaves well. Both are very useful for the deterministic parts around it: permissions, approvals, budgets, state machines and tool code. Write down what must always or never happen, enforce it outside the model, then check it with the lightest method that gives enough confidence.
What you will learn: specifications and invariants, model checking, solvers and proofs, property-based testing, test levels, reliability practices and how to combine them for agents.
Prerequisites: programming and basic testing. Distributed Systems, Networking and Databases helps.
Specifications and invariants
A specification states what a system should do. An invariant is a condition that must hold in every reachable state. Good ones are short and concrete.
| Kind | Meaning | Agent example |
|---|---|---|
| Safety | Something bad never happens | No payment above the approved amount |
| Liveness | Something good eventually happens | Every request is eventually completed, refused or escalated |
| Precondition | Must hold before an action | The caller is authenticated and allowed |
| Postcondition | Must hold after it | The ledger entry matches the instruction |
| Bound | A limit is respected | At most twenty tool calls per task |
"The agent behaves responsibly" cannot be checked. "A refund is issued only with an unexpired approval for that order and amount" can. Writing such sentences often exposes disagreement before any code exists.
The testing foundation
| Level | Checks | With models |
|---|---|---|
| Unit | One function or rule | Not needed |
| Contract | Interfaces between components | Not needed |
| Integration | Components working together | Scripted or recorded replies |
| End to end | A whole task | Real model, repeated runs |
| Evaluation | Quality of behavior over many cases | Real model with scoring |
| Adversarial | Behavior under attack | Real model and hostile inputs |
Keep as much behavior as possible testable without a model, because those tests are fast and repeatable. Test the model-dependent parts statistically. Agent Testing: Unit to End-to-End goes further.
Model checking
A model checker explores the states of a simplified model and reports a path to any state that breaks a property. The following small explorer checks an approval workflow.
"""Explore every reachable state of an approval workflow."""
from collections import deque
# state: (amount, approved_amount, paid_amount)
START = (100, None, None)
def moves(state, fixed):
amount, approved, paid = state
if paid is not None:
return
for new in (100, 900):
if new != amount:
kept = None if fixed else approved
yield f"edit to {new}", (new, kept, paid)
if approved is None and amount <= 500: # approver limit
yield "approve", (amount, amount, paid)
if approved is not None:
yield "pay", (amount, approved, amount)
def invariant(state):
"""Whatever was paid is exactly what was approved."""
_, approved, paid = state
return paid is None or paid == approved
def check(fixed):
queue, trace = deque([START]), {START: []}
while queue:
state = queue.popleft()
if not invariant(state):
return len(trace), trace[state], state
for label, nxt in moves(state, fixed):
if nxt not in trace:
trace[nxt] = trace[state] + [label]
queue.append(nxt)
return len(trace), None, None
for fixed in (False, True):
count, steps, bad = check(fixed)
name = "fixed design" if fixed else "first design"
if steps:
print(f"{name}: VIOLATED after {' -> '.join(steps)}")
print(f" approved {bad[1]}, paid {bad[2]}")
else:
print(f"{name}: invariant holds in all {count} reachable states")
Output:
first design: VIOLATED after approve -> edit to 900 -> pay
approved 100, paid 900
fixed design: invariant holds in all 4 reachable states
The first design lets someone obtain approval for 100, change the request to 900 and then pay. Each step looks reasonable, and a test of the normal path would pass. The checker finds the order of events that breaks the invariant and shows it as a short trace. The repair clears approval whenever the request changes, and the invariant then holds in all reachable states of this model.
Read that claim narrowly. The model has two amounts, one request and no concurrency. It says nothing about a real implementation that reads the amount twice, about several approvals in flight or about a bug outside the model. Tools such as TLA+, Alloy and P handle far richer models. Amazon engineers have described using TLA+ and P, together with lighter methods such as property-based testing and fault injection, on cloud services.
| Modeling step | Advice |
|---|---|
| Choose the risk | Model one protocol, not the whole product |
| Abstract | Replace values with a few representative ones |
| Make the environment hostile | Allow edits, retries, crashes and reordering |
| Let the model component be arbitrary | Assume the agent may attempt any allowed call at any time |
| Check the checker | Plant a known bug and confirm it is found |
| Connect to code | Turn counterexamples into tests |
The fourth row is the key idea for agents. If safety holds even when the model chooses actions adversarially, it does not depend on the prompt working.
Property-based testing
Instead of writing individual examples, state a property and generate many inputs. When one fails, shrink it to a smaller failing case.
"""Property-based testing with a shrinking step, using only the stdlib."""
import random
def spend_buggy(limit, requests):
spent = 0
for cost in requests:
if spent <= limit: # checks before, not after
spent += cost
return spent
def spend_fixed(limit, requests):
spent = 0
for cost in requests:
if 0 <= cost <= limit - spent:
spent += cost
return spent
def holds(function, limit, requests):
return 0 <= function(limit, requests) <= limit
def shrink(function, limit, requests):
changed = True
while changed:
changed = False
smaller = [(limit, requests[:i] + requests[i + 1:])
for i in range(len(requests))]
smaller += [(limit, requests[:i] + [v] + requests[i + 1:])
for i, r in enumerate(requests)
for v in (r // 2, r - 1) if 0 <= v < r]
smaller += [(v, requests) for v in (limit // 2, limit - 1)
if 0 <= v < limit]
for candidate in smaller:
if not holds(function, *candidate):
limit, requests = candidate
changed = True
break
return limit, requests
for function in (spend_buggy, spend_fixed):
rng = random.Random(1)
for case in range(1, 5001):
limit = rng.randint(0, 100)
requests = [rng.randint(0, 60) for _ in range(rng.randint(0, 6))]
if not holds(function, limit, requests):
print(f"{function.__name__}: fails on case {case}: "
f"limit={limit} requests={requests}")
print(" smallest found: limit=%d requests=%s"
% shrink(function, limit, requests))
break
else:
print(f"{function.__name__}: held in {case} random cases")
Output:
spend_buggy: fails on case 1: limit=17 requests=[54, 51, 48, 4]
smallest found: limit=0 requests=[1]
spend_fixed: held in 5000 random cases
The buggy budget guard checks the total before adding a cost, so a single large request passes. The random case that exposed it involves several numbers; shrinking reduces it to a limit of zero and one request of one, which makes the error obvious. The fixed version held in all generated cases. That is strong evidence for the tested ranges, not a proof: the generator never produced a negative cost, although the code rejects one. Check that generators cover the values you worry about, including boundaries and invalid input. Libraries such as Hypothesis provide generation and shrinking.
The range of formal methods
| Method | What it gives | Effort |
|---|---|---|
| Types and static analysis | Whole classes of errors excluded or flagged | Low |
| Property-based and fuzz testing | Broad automated exploration | Low to medium |
| Model checking | All states of a bounded model | Medium |
| Satisfiability solvers such as Z3 | Answers whether constraints can be satisfied | Medium |
| Deductive verification | Proof that code meets a specification | High |
| Interactive theorem proving | Machine-checked proofs of deep properties | Very high |
| Runtime verification | Checks actual executions against rules | Medium |
Every proof rests on assumptions: that the specification captures the intent, the model matches the system, and the underlying tools and environment behave as described. Record those assumptions with the result.
Analyzable authorization policies
Policy languages make rules explicit and separate from prompts. Cedar, an open source policy language from AWS, was designed so that policies can be analyzed mathematically, and AWS made a Cedar-based policy feature for its AgentCore agent platform generally available in March 2026. Analysis can reveal rules that allow too much or can never apply. It cannot tell whether the policy matches what the business intended, or protect a tool that bypasses the enforcement point.
What about the model itself?
Proving useful behavioral properties of large language models in general is not currently practical. Instead, constrain what their outputs can cause.
- Validate outputs against schemas and business rules.
- Enforce permissions and limits in code on every call.
- Separate untrusted data from control. Research such as CaMeL explores designs that track where data came from and enforce policies on how it may flow, with guarantees that depend on the design's assumptions.
- Verify results with tests, calculations or independent lookups where possible.
- Require approval for consequential actions.
Using a second model as a checker adds evidence but not proof. Its mistakes can resemble the first model's.
Runtime monitors
A monitor watches real events and checks the same invariants in production. For example: every payment event has a matching earlier approval event with equal amount. Run it independently of the component it watches, alert on violations, and for the most critical rules check before the action rather than after. Violations found at runtime should become test cases.
Working with a failing case
A counterexample is the most useful output of these tools, because it turns an abstract rule into a story that people can discuss. Handle each one in the same order.
| Question | If the answer is yes |
|---|---|
| Can this really happen in the system? | Fix the design or code and keep the case as a test |
| Is the model or generator allowing something impossible? | Correct it, and note which real control rules the event out |
| Is the stated rule wrong or too strict? | Agree the new wording with the accountable owner before changing it |
| Could similar paths exist elsewhere? | Add the same invariant to related tools and workflows |
Be careful with the second and third rows. It is tempting to adjust a model until the tool stops complaining. Each change should be justified by something true about the real system, not by the wish for a passing result. The same caution applies when a coding agent is asked to make tests pass: review changes to the tests and rules separately from changes to the code, and do not let the component being checked edit its own checker.
Record how the run was configured, including random seeds, bounds and tool versions, so that someone else can reproduce the failure and later confirm that the repair addresses it.
Reliability engineering foundations
| Practice | Purpose |
|---|---|
| Service level objectives | Define acceptable success, latency and quality |
| Error budgets | Decide when to favor stability over change |
| Fault injection | Rehearse slow, failing and lying dependencies |
| Staged rollout and rollback | Limit the effect of a bad change |
| Regression suites | Keep fixed problems fixed |
| Incident reviews | Learn without assigning blame, then change the system |
| Safe degradation | Fall back to read-only or human handling |
For model-dependent behavior, one passing run means little. Repeat cases, report rates with uncertainty as shown in Math, Search and Algorithms for Agent Engineers, and treat a rule that must never break as something code enforces, not something a pass rate hopes for.
Choosing how much rigor
A team lets an agent propose and run deployments. They write three invariants: only reviewed versions deploy, at most one rollout runs per service, and rollback is always possible. A small model reveals that two approvals arriving together could start two rollouts. A database constraint fixes it, a concurrent test reproduces the case, and a monitor checks the rule in production.
Introducing these methods to a team
- Write five invariants for the riskiest actions and agree them with the people accountable for those actions.
- Find where each is enforced. A rule that lives only in a prompt is a finding.
- Add ordinary tests for each rule, including attempts that must be refused.
- Add property tests for calculations, limits and parsers.
- Model one subtle protocol, typically approval, retry or hand-off, and look for bad orderings.
- Monitor the same rules in production and review every violation.
The first two steps need no new tools and frequently reveal the largest gaps. Keep specifications next to the code, review them when behavior changes and delete checks that no longer describe a real requirement. An outdated specification that still passes gives false comfort.
Common mistakes
- Vague requirements that no test can fail.
- Putting a hard rule only in the prompt.
- Testing only the expected order of events.
- Claiming a verified model means verified code.
- Random generators that never reach the dangerous values.
- Counting one successful run as proof.
- Using the agent's own report as verification.
Checklist
- Safety and liveness requirements are written plainly.
- Critical rules are enforced outside the model.
- Tests cover refusal paths and boundaries.
- Subtle protocols are explored systematically.
- Counterexamples become regression tests.
- Assumptions behind any proof are recorded.
- Runtime monitors check the most important invariants.
- Rollback and safe degradation are rehearsed.
Frequently asked questions
Is formal verification worth it for agents?
For selected rules with costly failure and tricky ordering, often yes. For general model behavior it is not practical, so combine enforcement with evaluation.
Which tool should a beginner try?
Start with property-based testing in your own language. Then model one small protocol to learn how model checking thinks.
Does full test coverage mean the system is correct?
No. Coverage shows which code ran, not whether the requirements are right or every order of events was tried.
Can a model write the specification?
It can draft candidates and examples. People accountable for the outcome must review them, since a wrong specification can be verified perfectly.
References and further reading
- Lamport: the TLA+ home page
- Brooker and Desai: systems correctness practices at AWS
- Alloy analyzer
- The P language
- Hypothesis property-based testing
- Cedar policy language documentation
- Debenedetti et al.: Defeating prompt injections by design (CaMeL)
Next steps
Testing and Evaluation
Build the wider test practice.
Action Guardrails and Policy Engines
Enforce rules on actions.
Tools and Function Calling
Move on to building with tools.