The Problem
An AI assistant generates a transfer_funds(from_account, to_account, amount) function. The code works: it deducts from from_account and adds to to_account. But it doesn't check that from_account != to_account (allowing self-transfers that double the balance), it doesn't check that amount > 0 (allowing negative transfers that reverse the flow), and it doesn't ensure the transfer is atomic (allowing partial transfers if the add fails after the deduct).
Example-based tests catch some of these: test_transfer_100_dollars verifies the happy path. But example-based tests are only as good as the examples the developer thinks of. A behavioral contract catches all of them automatically because it defines properties that must always hold, not specific examples.
What is a behavioral contract?
A behavioral contract has three components:
| Component | What it specifies | Example |
|---|
| Preconditions | What must be true before the function is called | from_account != to_account, amount > 0, from_account.balance >= amount |
| Postconditions | What must be true after the function returns | from_account.balance + to_account.balance == original_total (conservation) |
| Invariants | What must always be true, before and after | all account balances >= 0, total system money is conserved |
The key insight: contracts are properties, not examples. Instead of testing transfer(A, B, 100) and checking the result, you define the invariant "total money is conserved" and let Hypothesis generate thousands of transfer scenarios to verify it always holds.
Contracts catch what examples miss
Example-based testing: "I tested transfer(A, B, 100) and it worked." -- But what about transfer(A, A, 100)? transfer(A, B, -50)? transfer(A, B, 999999999)? Example-based testing checks the cases you thought of. Contract-based testing checks ALL cases by verifying properties that must hold for every possible input. This is why contract-based testing is more powerful for AI code: the AI's blind spots are cases you also didn't think of, but contracts catch them automatically.
Expressing contracts in code
Preconditions as pytest fixtures
import pytest
@pytest.fixture
def valid_transfer_args():
"""Precondition: transfer arguments must be valid."""
return {
"from_account": Account(balance=500),
"to_account": Account(balance=300),
"amount": 100,
}
def test_transfer_requires_different_accounts(valid_transfer_args):
args = valid_transfer_args
args["from_account"] = args["to_account"] # Same account
with pytest.raises(ValueError, match="Cannot transfer to same account"):
transfer(**args)
def test_transfer_requires_positive_amount(valid_transfer_args):
args = valid_transfer_args
args["amount"] = -50
with pytest.raises(ValueError, match="Amount must be positive"):
transfer(**args)
Postconditions as assertions
def test_transfer_conserves_total_money(valid_transfer_args):
args = valid_transfer_args
original_total = args["from_account"].balance + args["to_account"].balance
transfer(**args)
new_total = args["from_account"].balance + args["to_account"].balance
assert new_total == original_total # Postcondition: money is conserved
def test_transfer_deducts_from_source(valid_transfer_args):
args = valid_transfer_args
original_balance = args["from_account"].balance
transfer(**args)
assert args["from_account"].balance == original_balance - args["amount"]
Invariants as Hypothesis properties
from hypothesis import given, strategies as st
class Account:
def __init__(self, balance=0):
self.balance = balance
@given(
from_balance=st.integers(min_value=0, max_value=10000),
to_balance=st.integers(min_value=0, max_value=10000),
amount=st.integers(min_value=1, max_value=10000),
)
def test_invariant_total_money_conserved(from_balance, to_balance, amount):
"""Invariant: total money in the system never changes after a transfer."""
if amount > from_balance:
return # Skip invalid transfers (precondition not met)
from_acc = Account(balance=from_balance)
to_acc = Account(balance=to_balance)
original_total = from_acc.balance + to_acc.balance
transfer(from_acc, to_acc, amount)
new_total = from_acc.balance + to_acc.balance
assert new_total == original_total, f"Money not conserved: {original_total} -> {new_total}"
@given(
from_balance=st.integers(min_value=0, max_value=10000),
to_balance=st.integers(min_value=0, max_value=10000),
amount=st.integers(min_value=1, max_value=10000),
)
def test_invariant_no_negative_balances(from_balance, to_balance, amount):
"""Invariant: no account balance goes negative after a transfer."""
if amount > from_balance:
return
from_acc = Account(balance=from_balance)
to_acc = Account(balance=to_balance)
transfer(from_acc, to_acc, amount)
assert from_acc.balance >= 0, f"Negative balance: {from_acc.balance}"
assert to_acc.balance >= 0, f"Negative balance: {to_acc.balance}"
An AI generates a sort_list(items) function that modifies the list in place. A developer writes example-based tests: test_sort_integers, test_sort_empty, test_sort_single. All pass. Which contract invariant would catch a subtle bug that example-based tests miss?
The multiset equality invariant ('sorted list contains the same elements as the original') catches a class of bugs that example-based tests systematically miss: sorting functions that drop or duplicate elements. An AI might generate a sort that works correctly on distinct elements but mishandles duplicates (e.g., using a set instead of a sort). Example-based tests with [3, 1, 2] would pass (sorted: [1, 2, 3] -- same elements), but [3, 1, 3, 2] might produce [1, 2, 3] (dropping a duplicate). The invariant, tested with Hypothesis generating thousands of lists including many with duplicates, would catch this automatically. This is the power of contract-based testing: it verifies properties that hold for ALL inputs, not just the examples you thought of.
Contract-based testing vs example-based testing
| Aspect | Example-based | Contract-based |
|---|
| What it tests | Specific inputs and outputs | Properties that must hold for all inputs |
| Coverage | Limited to examples the developer thinks of | Unlimited -- Hypothesis generates thousands of inputs |
| AI blind spots | Shares the AI's blind spots (developer writes tests after seeing code) | Independent of the AI's implementation (contracts from spec) |
| Edge case discovery | Manual -- developer must think of each edge case | Automatic -- Hypothesis explores the input space |
| Maintenance | Each new edge case needs a new test | New inputs are generated automatically |
| Defect detection | Catches bugs in tested cases | Catches bugs in untested cases |
Contract-based testing does not replace example-based testing -- it complements it. Example-based tests are fast, readable, and good for documenting expected behavior. Contract-based tests are thorough, automated, and good for catching edge cases. Use both.
Using contracts to prevent AI defect patterns
Each AI defect pattern from Lesson 1 can be addressed with a specific contract:
| AI Defect Pattern | Contract that prevents it |
|---|
| Variable assignment errors | Invariant: "function output depends only on inputs (no hidden state)" |
| Repetitive logic | Postcondition: "function output matches the abstract specification, not a duplicated implementation" |
| Hallucinated APIs | Precondition: "all imported modules exist and are verified" (checked at import time) |
| Missing exception handling | Postcondition: "function never raises on valid inputs" (tested with Hypothesis) |
Your team uses AI to generate a deduct_from_account(account, amount) function. You want to prevent the AI from generating code that allows negative balances (a common AI defect). Which contract approach is most effective?
The invariant approach with Hypothesis is most effective because it tests ALL valid (balance, amount) pairs, not just the 10 the developer thought of. This catches: (1) floating-point rounding errors (e.g., 0.1 + 0.2 != 0.3 in Python) that could make a balance go slightly negative, (2) edge cases at the boundary (amount == balance exactly), (3) concurrent deduction scenarios if the invariant includes thread safety, and (4) any future code changes that break the invariant. The invariant is also self-maintaining: when Hypothesis is updated with new strategies, it generates new inputs automatically without the developer writing additional tests. Example-based tests would need 100+ tests to achieve similar coverage, and they would still miss cases the developer didn't think of.