Predicate logic and formal specification
Review first-order logic: terms, quantifiers, free and bound variables, structures, and Tarski interpretation. The practical focus is writing precise specifications with preconditions and postconditions and checking them in finite models.
After this lesson you can
- Distinguish free and bound variables and apply substitution without capture.
- Evaluate first-order formulas in finite structures and interpret truth as a game between verifier and falsifier.
- Negate and reorder quantifiers correctly and put formulas in prenex form.
- Write complete formal specifications and find counterexamples to weak ones.
- Implement a first-order model checker for finite structures.
Before you start
Motivation: “the output is sorted” does not specify sorting
Ask someone for a sorting-function specification and they will likely say “the output is sorted.” Now consider this program:
def ordenar(a):
return []
The empty list is sorted. The program satisfies the specification, passes any test checking only all(b[i] <= b[i+1] for i in range(len(b) - 1)), and is completely useless. Add “and it has the same length as the input,” and an adversary responds with [0] * len(a). If you further require every output value to occur in the input and vice versa, an incorrect program still satisfies everything; you will find it yourself in this lesson’s third interactive. The problem is not lack of tests: the checked property does not say what we want.
This happens in real programs. In 2006 Joshua Bloch reported that Java’s standard-library binary search had had a bug for about nine years in int mid = (low + high) / 2: addition overflows above , possible for arrays with more than elements (Bloch, 2006); the algorithm was correct for mathematical integers in the book specification and false for the language’s 32-bit integers. In 2015 a team formally verifying TimSort, Python’s sorting algorithm adopted by OpenJDK for objects, discovered an invariant the implementation claimed to maintain did not hold, and built inputs making java.util.Collections.sort fail with an exception (de Gouw et al., 2015). In both cases the bug emerged by precisely writing what code must satisfy.
The tool for precise properties is first-order logic: the previous lesson’s propositional logic plus variables ranging over a domain, quantifiers and , functions, and relations. It is the language of definitions of limits, PAC learnability, and algorithm correctness, and annotations understood by verifiers. This lesson reviews syntax and semantics with rigor needed through the module, turning them into two tools: a finite-structure model checker and a systematic method for detecting weak specifications.
Syntax: terms, formulas, and variables
A first-order formula speaks about domain objects using symbols whose meanings are not fixed in advance. The vocabulary is fixed.
Terms denote objects; formulas denote true-or-false statements. With the arithmetic signature , term is a number and formula says “ is even.” With the graph signature containing one binary relation symbol , formula says “every node has a successor.” A relation of arity 0 is a propositional letter: propositional logic is the variable-free case.
Because formulas are inductively defined, they are trees; functions on them are defined by structural recursion and properties proven by structural induction, as in inductive definitions in lesson 7. To write fewer parentheses, retain the previous lesson’s precedence and, like Huth and Ryan, give quantifiers negation’s strength: , , and bind more strongly than , which binds more strongly than , then , then ; associates right. (Huth and Ryan give and equal precedence; when in doubt, parenthesize.) Thus is ; to make the quantifier cover the conjunction write . Both graph interactives read formulas under these rules.
Free and bound variables
In , formula is the quantifier’s scope, and occurrences of inside are bound by it. An occurrence outside every quantifier over its variable is free. Free variables are computed recursively:
where is any binary connective and are variables in term (equality is treated as another atom). A formula with no free variables is a sentence. The distinction matters: a sentence is true or false in a structure, whereas a formula with free variables such as is a property of whose value depends on which object is.
The same variable can have free and bound occurrences in one formula. In
the in is free and that in is bound by ; the in is outside the scope of and is free. Thus , although and also occur bound. Reusing names this way is legal and confusing, and causes substitution errors discussed below.
Tarski semantics: structures and satisfaction
A formula is not true or false by itself: it is so under an interpretation of its symbols. That interpretation is a structure.
The definition is only apparently circular: quantifiers in the clause (“for every ”) belong to mathematics used to discuss logic, the metalanguage, whereas is an object-language symbol. When is finite, “for every ” is a terminating loop and the definition is literally an algorithm: the model checker you implement below.
Two facts proven by induction on formulas and used constantly:
- Coincidence. If and agree on , then iff . Formula value depends only on free variables. In particular, a sentence has the same value under any assignment, written simply .
- Nonempty domain. The condition matters: it guarantees is valid and the prenex laws below work. With empty domains, would be true and false.
An example with two structures
Sentence says every element has an additive inverse. In structure it is true: the inverse of is (and 0’s is 0). In it is false: for , no satisfies . The sentence has not changed; the structure has. Sentence , “there is no maximum,” is true in and false in , where has no larger .
Truth as a game
The clause requires checking all elements and requires finding one. Jaakko Hintikka turned this asymmetry into a game between the verifier, seeking to show true, and falsifier, seeking to show it false. Play traverses the formula from the root:
- At the verifier chooses and play continues with and . At the falsifier chooses.
- At the verifier chooses the disjunct; at the falsifier chooses the conjunct. ( is treated as .)
- At players swap roles and continue with .
- At an atom inspect the structure: if true the current verifier wins, otherwise the other player does.
Proof
Induct on , simultaneously proving the dual claim: iff the falsifier has a winning strategy. Every move descends to an immediate subformula, so every game is finite and ends at an atom; both players cannot have winning strategies at once (playing them against each other would make both win). It suffices to prove the verifier wins if and the falsifier otherwise; both equivalences follow. At an atom there are no moves and the definition selects the winner. At : if , some has , and by induction the verifier wins from there; its strategy is “choose and follow the winning strategy for .” If false, every has , and by the dual hypothesis the falsifier wins after any verifier choice. The case is symmetric, and and are identical with two options instead of . At roles swap, so the verifier wins iff the falsifier wins , i.e. by the dual iff , the negation clause.
∎The game exposes what recursion hides: in , witness is chosen after seeing and can depend on it. A verifier winning strategy for is a function with for every . This is a Skolem function; replacing with a fresh function symbol is Skolemization used by automated provers. In instead, the verifier commits to one before seeing any .
On cycle , the verifier’s winning strategy for is “next node,” and falsifier cannot defeat it. For the verifier must find a node pointed to by all four; each cycle node has one predecessor, so whatever it chooses the falsifier finds an not pointing there. Both formulas share the quantifier-free part and have opposite values. In graph “Everyone points to d” both are true with the same witness for everyone: this illustrates entails , proven in the exercises.
Formulas on a graph you draw
For a finite domain Tarski’s definition is an algorithm; its decisions can be explained using the game: if true, verifier witnesses; if false, falsifier counterexample. The next interactive is that algorithm with its certificate.
Try three things in the interactive.
- Witnesses as a function. With “Every node has a successor,” the certificate gives a successor per node, and those edges form the graph of a function , the verifier’s strategy. Remove a node’s only outgoing edge and the certificate becomes a counterexample: that node, with all its absent edges red.
- Cost is exponential in depth. Evaluated-atom count grows as , where is quantifier nesting depth: transitivity with three quantifiers examines up to triples. Recursively evaluating formula on a finite structure costs : polynomial for a fixed formula and exponential if the formula is input (the general problem is PSPACE-complete).
- What a finite graph cannot satisfy. Select “Irreflexive, transitive, and no end,” , and draw any graph: it is always false. The next example explains why.
Quantifier laws
Formulas are logically equivalent, , if and agree in every structure and assignment: propositional logical equivalence with structures instead of valuations. Every propositional equivalence remains valid when letters are replaced by first-order formulas. New laws move quantifiers.
Proof
All follow from expanding satisfaction. (1) iff it is not true that holds under for every , iff some makes it fail. (2) “For every , and ” is equivalent to “for every , ” and “for every , .” (3) By coincidence, ‘s value under does not depend on ; hence , using . Others reduce to this and (1)–(2): for example . (4) Both express “for every pair .” (5) is the first guided exercise.
∎The other two distributions in (2) are false; keep the smallest counterexample handy. With , , and , every element satisfies or , so is true; but not all satisfy and not all satisfy . In the same structure someone is in and someone in , but nobody in both: does not imply . One-way implications do hold: and .
Continuity versus uniform continuity
Quantifier order is not style. Continuity of at every point and uniform continuity differ only in where occurs:
In the game, in the first the verifier chooses after seeing and : its strategy is a function . In the second cannot depend on the point. For , suffices and tends to 0 as grows; no fixed works for every : with , for any the falsifier plays and , giving . Definitions of PAC learnability have the same form, , and order decides whether sample size may depend on distribution.
Prenex form
A formula is in prenex form if it is with each and quantifier-free. Every formula is equivalent to a prenex one, and the proof is an algorithm like conversion to conjunctive normal form: eliminate , rename bound variables to be distinct from one another and free ones, and move quantifiers outward with laws (1) and (3), changing to whenever a quantifier exits an antecedent or negation. Renaming is mandatory, as this example’s second step shows:
If step 2 does not rename , pulling outward captures the free in and changes the formula’s meaning. Prenex form is not unique (independent quantifiers may be moved in either order), and prefix alternation, , …, measures logical complexity and reappears in computability.
Substitution and variable capture
Quantifier inference rules need instantiation: from derive with replaced by any term , written . The naive definition “replace every free occurrence of with ” has a flaw. Let , “ is not the maximum.” Replacing with should mean “ is not the maximum,” but literal replacement produces
which is false in any strict order. The inserted was free and got captured by . Meaning cannot depend on names of bound variables: and say the same. Rename before substituting.
With the correct definition, , exactly what we wanted. The justification is the substitution lemma: for every term ,
Syntactically substituting for equals evaluating with assigned the value of . Prove by induction on ; the only delicate case is a quantifier, exactly what forces renaming. With naive substitution the lemma is false; a later cell measures failures on random formulas.
Validity, consequence, and completeness
Propositional semantic notions generalize by replacing valuations with structures.
As with propositional consequence, is valid iff is unsatisfiable, and iff is unsatisfiable. The difference is that no finite truth table remains to traverse: there are infinitely many structures, many infinite. To refute a consequence one structure suffices (a counterexample, possibly small and finite); to prove it one must reason over all. The fundamental first-order result says finite syntactic rules can express that reasoning.
Direction is completeness proper, and soundness, proven by induction on derivations (see soundness and completeness). Two immediate consequences: derivations are finite, so if then follows from a finite subset of (compactness); and derivations are enumerable, so valid sentences are semidecidable: a program generating all derivations eventually finds one for any valid sentence. They are not decidable: Church and Turing proved in 1936 that no algorithm given a sentence always terminates and says whether it is valid. This is first-order logic undecidability, proven in the computability lesson. Earlier sentence illustrates a related phenomenon: by Trakhtenbrot’s theorem (1950), even whether a sentence has a finite model is undecidable.
Specify algorithms with first-order logic
A program specification is a pair of formulas: a precondition stating admitted inputs and a postcondition relating input to output. The program satisfies it if every input satisfying the precondition produces an output satisfying the postcondition. Hoare logic turns this idea into a calculus for proving programs; here we focus on writing formulas correctly.
Arrays are zero-indexed as in code, and properties use bounded quantifiers: , Python all(phi(i) for i in range(n)), and , any(...). Note connectives: bounded universal uses and existential uses . With arrays, “ is sorted” is
and a complete sorting postcondition additionally requires be a permutation of , expressed with count function , the occurrences of :
The second part says and are the same multiset. Having the same elements is insufficient: and its converse compare only value sets, and has the same values as at the same length. Real specification languages include this function or a multiset type (in Dafny, multiset(b[..]) == multiset(a[..])). Without it one must say “there exists a bijection of indices with ,” quantifying over functions and leaving first order.
Proof
Existence: sort with any correct algorithm. For uniqueness let and be sorted lists with the same occurrences of every value as . For each value , the number of positions with is , likewise for ; call it . Likewise positions with number the same in and ; call it . In a sorted list positions containing are exactly those with . Hence for every index , is the unique with , and so is : . And .
∎A postcondition determining output is functional: any satisfying program computes the same function. This is not always desired. Search in an array with repeated values may return any matching index; specifying “the first” would overspecify, rejecting correct implementations the user need not exclude. Conversely, if records are sorted by a key, on keys does not fix order among equal-key records, and stability is an extra clause to request explicitly.
Binary search
For binary search of in an array of length returning an index or :
Each part has a purpose. Without the complete first disjunct, return -1 satisfies the specification. Without range , in a language with negative indices like Python, a[r] == x can hold for a negative the rest of the program does not expect. The precondition is not decorative: if is unsorted, binary search can return even though occurs, and the caller is at fault. Preconditions are caller obligations; postconditions are callee guarantees.
The adversary’s lesson fits a table. “Sorted” accepts the empty list; with length, zeros; with “every value of is in ,” repeated minimum; with all four set clauses it still accepts “remove duplicates and fill with maximum,” turning into . Only the count clause closes the hole, making everything except “sorted” redundant: length follows by summing over values, and inclusions from iff . For search, “strictly first occurrence” rejects correct binary search, which on returns index 2 (midpoint), while unconditional rejects every correct program when is absent.
Implementation from scratch
The lab has two parts: a finite-structure model checker, Tarski’s definition as code, and evaluating specifications as executable predicates against mutated implementations. First formulas as trees, free variables, and satisfaction.
from dataclasses import dataclass
# ---- términos ----
@dataclass(frozen=True)
class Var:
name: str
@dataclass(frozen=True)
class App: # f(t1, ..., tn); una constante es App("c")
fn: str
args: tuple = ()
# ---- fórmulas ----
@dataclass(frozen=True)
class Rel: # R(t1, ..., tn)
name: str
args: tuple
@dataclass(frozen=True)
class Eq:
left: object
right: object
@dataclass(frozen=True)
class Not:
f: object
@dataclass(frozen=True)
class Bin: # op en {"and", "or", "imp"}
op: str
left: object
right: object
@dataclass(frozen=True)
class Quant: # q en {"forall", "exists"}
q: str
var: str
body: object
def And(a, b): return Bin("and", a, b)
def Or(a, b): return Bin("or", a, b)
def Imp(a, b): return Bin("imp", a, b)
def Forall(v, f): return Quant("forall", v, f)
def Exists(v, f): return Quant("exists", v, f)
x, y, z = Var("x"), Var("y"), Var("z")
def E(s, t): return Rel("E", (s, t))
@dataclass
class Structure:
domain: list
funcs: dict # nombre -> función de Python (o valor, si es una constante)
rels: dict # nombre -> conjunto de tuplas
def term_value(t, M, s):
if isinstance(t, Var):
return s[t.name]
f = M.funcs[t.fn]
return f(*(term_value(a, M, s) for a in t.args)) if t.args else f
EVALS = [0] # átomos evaluados, para medir el coste
def holds(phi, M, s):
"""M ⊨ phi[s], cláusula a cláusula como en la definición de Tarski."""
if isinstance(phi, Rel):
EVALS[0] += 1
return tuple(term_value(a, M, s) for a in phi.args) in M.rels[phi.name]
if isinstance(phi, Eq):
EVALS[0] += 1
return term_value(phi.left, M, s) == term_value(phi.right, M, s)
if isinstance(phi, Not):
return not holds(phi.f, M, s)
if isinstance(phi, Bin):
a = holds(phi.left, M, s)
if phi.op == "and":
return a and holds(phi.right, M, s)
if phi.op == "or":
return a or holds(phi.right, M, s)
return (not a) or holds(phi.right, M, s)
q = all if phi.q == "forall" else any
return q(holds(phi.body, M, {**s, phi.var: d}) for d in M.domain) # s[x -> d]
def term_vars(t):
if isinstance(t, Var):
return {t.name}
return set().union(*(term_vars(a) for a in t.args))
def free_vars(phi):
if isinstance(phi, Rel):
return set().union(*(term_vars(a) for a in phi.args))
if isinstance(phi, Eq):
return term_vars(phi.left) | term_vars(phi.right)
if isinstance(phi, Not):
return free_vars(phi.f)
if isinstance(phi, Bin):
return free_vars(phi.left) | free_vars(phi.right)
return free_vars(phi.body) - {phi.var}
SYM = {"and": "∧", "or": "∨", "imp": "→", "forall": "∀", "exists": "∃"}
def show(phi):
if isinstance(phi, Var):
return phi.name
if isinstance(phi, App):
return phi.fn + ("(" + ", ".join(map(show, phi.args)) + ")" if phi.args else "")
if isinstance(phi, Rel):
return f"{phi.name}({', '.join(map(show, phi.args))})"
if isinstance(phi, Eq):
return f"{show(phi.left)} = {show(phi.right)}"
if isinstance(phi, Not):
return "¬" + show(phi.f)
if isinstance(phi, Bin):
return f"({show(phi.left)} {SYM[phi.op]} {show(phi.right)})"
return f"{SYM[phi.q]}{phi.var} {show(phi.body)}"
ciclo = Structure(list("abcd"), {}, {"E": {("a", "b"), ("b", "c"), ("c", "d"), ("d", "a")}})
for phi in [Forall("x", Exists("y", E(x, y))), Exists("y", Forall("x", E(x, y))), Exists("y", E(y, x))]:
fv = free_vars(phi)
if fv:
print(f"{show(phi):16s} libres {sorted(fv)}:", {d: holds(phi, ciclo, {"x": d}) for d in ciclo.domain})
else:
print(f"{show(phi):16s} sentencia:", holds(phi, ciclo, {}))
# la misma sentencia en dos estructuras: Z_5 con la suma y {0..4} con el orden
Z5 = Structure(list(range(5)), {"+": lambda a, b: (a + b) % 5, "0": 0},
{"<": {(a, b) for a in range(5) for b in range(5) if a < b}})
opuesto = Forall("x", Exists("y", Eq(App("+", (x, y)), App("0"))))
sin_maximo = Forall("x", Exists("y", Rel("<", (x, y))))
print(show(opuesto), "en Z5:", holds(opuesto, Z5, {}))
print(show(sin_maximo), "en {0..4}:", holds(sin_maximo, Z5, {}))
# coste: una sentencia verdadera con tres cuantificadores examina del orden de n^3 ternas
sin_atajos = Forall("x", Forall("y", Forall("z", Imp(And(E(x, y), E(y, z)), Not(E(x, z))))))
for n in [4, 8, 16, 32]:
M = Structure(list(range(n)), {}, {"E": {(i, (i + 1) % n) for i in range(n)}})
EVALS[0] = 0
v = holds(sin_atajos, M, {})
print(f"ciclo de {n:2d}: {v}, átomos evaluados = {EVALS[0]:6d}, n^3 = {n**3:6d}")The evaluator is Tarski’s definition line by line: all and any over the domain are and clauses, and {**s, phi.var: d} is assignment . Short-circuiting and, or, all, and any are precisely evaluation-game moves: any stops at the first witness and all at the first counterexample. In the final block, the sentence says the cycle has no two-step shortcuts, is true, and evaluates in all triples, in the where holds, and in the where both hold: atoms (33824 for the 32-cycle).
The evaluator can check claims over all small structures. The 512 binary relations on a three-element domain confirm law (5) and measure the difference between and ; checking quantifier laws under all interpretations of two unary predicates finds counterexamples to failing laws.
from itertools import product
D3 = list(range(3))
pares = [(i, j) for i in D3 for j in D3]
AE = Forall("x", Exists("y", E(x, y)))
EA = Exists("y", Forall("x", E(x, y)))
n_ae = n_ea = n_ea_sin_ae = 0
for bits in product([0, 1], repeat=9):
M = Structure(D3, {}, {"E": {p for p, b in zip(pares, bits) if b}})
ae, ea = holds(AE, M, {}), holds(EA, M, {})
n_ae += ae
n_ea += ea
n_ea_sin_ae += ea and not ae
print(f"de 512 relaciones en {{0, 1, 2}}: ∀x∃y E en {n_ae}, ∃y∀x E en {n_ea}, "
f"∃∀ sin ∀∃ en {n_ea_sin_ae}, ∀∃ sin ∃∀ en {n_ae - n_ea}")
def P(t): return Rel("P", (t,))
def Q(t): return Rel("Q", (t,))
q = Rel("q", ()) # aridad 0: una proposición en la que x no aparece
leyes = {
"∀x(P∧Q) ≡ ∀xP ∧ ∀xQ": (Forall("x", And(P(x), Q(x))), And(Forall("x", P(x)), Forall("x", Q(x)))),
"∃x(P∨Q) ≡ ∃xP ∨ ∃xQ": (Exists("x", Or(P(x), Q(x))), Or(Exists("x", P(x)), Exists("x", Q(x)))),
"∀x(P∨Q) ≡ ∀xP ∨ ∀xQ": (Forall("x", Or(P(x), Q(x))), Or(Forall("x", P(x)), Forall("x", Q(x)))),
"∃x(P∧Q) ≡ ∃xP ∧ ∃xQ": (Exists("x", And(P(x), Q(x))), And(Exists("x", P(x)), Exists("x", Q(x)))),
"¬∀xP ≡ ∃x¬P": (Not(Forall("x", P(x))), Exists("x", Not(P(x)))),
"∀x(P → q) ≡ ∃xP → q": (Forall("x", Imp(P(x), q)), Imp(Exists("x", P(x)), q)),
"∀x(P → q) ≡ ∀xP → q": (Forall("x", Imp(P(x), q)), Imp(Forall("x", P(x)), q)),
"∃x(P → Q) ≡ ∀xP → ∃xQ": (Exists("x", Imp(P(x), Q(x))), Imp(Forall("x", P(x)), Exists("x", Q(x)))),
}
def estructuras(max_n=4):
for n in range(1, max_n + 1):
D = list(range(n))
for Pb, Qb, qb in product(product([0, 1], repeat=n), product([0, 1], repeat=n), [0, 1]):
yield Structure(D, {}, {"P": {(d,) for d in D if Pb[d]}, "Q": {(d,) for d in D if Qb[d]},
"q": {()} if qb else set()})
for nombre, (f, g) in leyes.items():
cx = next((M for M in estructuras() if holds(f, M, {}) != holds(g, M, {})), None)
if cx is None:
print(f"{nombre:24s} se cumple en las {sum(1 for _ in estructuras())} estructuras de tamaño ≤ 4")
else:
Ps = sorted(d for (d,) in cx.rels["P"])
Qs = sorted(d for (d,) in cx.rels["Q"])
print(f"{nombre:24s} FALLA con D = {cx.domain}, P = {Ps}, Q = {Qs}, q = {bool(cx.rels['q'])}")Of 512 relations, 343 satisfy (each of three adjacency-matrix rows must be nonzero: ), and 169 satisfy (some full column: ). None satisfy the second without the first, as law (5) requires, and 174 satisfy the first without the second. False equivalences appear with minimal counterexamples, and the last line shows a counterintuitive but correct law: is equivalent to , hence true whenever some element fails .
Now substitution. The naive version replaces free occurrences without checking. To measure damage the cell generates random formulas, terms, and structures and checks the substitution lemma, , in each case.
import random
def subst_term(t, v, u):
if isinstance(t, Var):
return u if t.name == v else t
return App(t.fn, tuple(subst_term(a, v, u) for a in t.args))
def subst_ingenua(phi, v, u):
"""Sustituye las apariciones libres de v por u sin mirar si u queda capturado."""
if isinstance(phi, Rel):
return Rel(phi.name, tuple(subst_term(a, v, u) for a in phi.args))
if isinstance(phi, Eq):
return Eq(subst_term(phi.left, v, u), subst_term(phi.right, v, u))
if isinstance(phi, Not):
return Not(subst_ingenua(phi.f, v, u))
if isinstance(phi, Bin):
return Bin(phi.op, subst_ingenua(phi.left, v, u), subst_ingenua(phi.right, v, u))
if phi.var == v: # v está ligada aquí: no se toca
return phi
return Quant(phi.q, phi.var, subst_ingenua(phi.body, v, u))
def hay_captura(phi, v, u, ligadas=frozenset()):
"""¿Alguna aparición libre de v está en el ámbito de un cuantificador sobre una variable de u?"""
if isinstance(phi, (Rel, Eq)):
return v in free_vars(phi) and bool(term_vars(u) & ligadas)
if isinstance(phi, Not):
return hay_captura(phi.f, v, u, ligadas)
if isinstance(phi, Bin):
return hay_captura(phi.left, v, u, ligadas) or hay_captura(phi.right, v, u, ligadas)
if phi.var == v:
return False
return hay_captura(phi.body, v, u, ligadas | {phi.var})
no_es_maximo = Exists("y", Rel("<", (x, y))) # φ(x): «x no es el máximo»
orden3 = Structure([0, 1, 2], {}, {"<": {(a, b) for a in range(3) for b in range(3) if a < b}})
print(show(no_es_maximo), " con x := y ->", show(subst_ingenua(no_es_maximo, "x", y)))
print("φ con x = s(y) = 0:", holds(no_es_maximo, orden3, {"x": 0}),
" sustitución ingenua con s(y) = 0:", holds(subst_ingenua(no_es_maximo, "x", y), orden3, {"y": 0}))
def rterm(r, d):
if d == 0 or r.random() < 0.6:
return Var(r.choice("xyz"))
return App("f", (rterm(r, d - 1),))
def rform(r, d):
if d == 0 or r.random() < 0.25:
return E(rterm(r, 1), rterm(r, 1))
k = r.choice(["not", "and", "or", "imp", "forall", "exists"])
if k == "not":
return Not(rform(r, d - 1))
if k in ("and", "or", "imp"):
return Bin(k, rform(r, d - 1), rform(r, d - 1))
return Quant(k, r.choice("xyz"), rform(r, d - 1))
r = random.Random(0)
N, fallos, capturas, fallos_sin_captura = 3000, 0, 0, 0
for _ in range(N):
phi, u, v = rform(r, 4), rterm(r, 2), r.choice("xyz")
D = [0, 1, 2]
tabla = {a: r.choice(D) for a in D}
M = Structure(D, {"f": lambda a, m=tabla: m[a]}, {"E": {(a, b) for a in D for b in D if r.random() < 0.45}})
s = {w: r.choice(D) for w in "xyz"}
falla = holds(subst_ingenua(phi, v, u), M, s) != holds(phi, M, {**s, v: term_value(u, M, s)})
cap = hay_captura(phi, v, u)
fallos += falla
capturas += cap
fallos_sin_captura += falla and not cap
print(f"\n{N} casos aleatorios: hay captura en {capturas}, el lema falla en {fallos}, "
f"fallos sin captura: {fallos_sin_captura}")The lemma fails only with capture, and not in all such cases: in this run, 40 of 380 capture cases (sometimes the captured variable happens to have the correct value, or the formula does not depend on it). This is the worst kind of bug: intermittent and dependent on variable names. Fixing subst_ingenua is the lesson’s coding exercise.
Executable specifications and mutants
With bounded quantifiers a specification is an executable predicate. To measure strength use mutation testing: generate incorrect program variants (mutants) and count detected ones. A specification that misses an incorrect mutant has a hole. This is m00’s property-based testing idea, with specification as the property.
import random
from itertools import permutations
def cuenta(v, b): # #(v, b)
return sum(1 for w in b if w == v)
# cláusulas de la postcondición de b = ordenar(a), con cuantificadores acotados
def ordenada(a, b): return all(b[i] <= b[i + 1] for i in range(len(b) - 1))
def longitud(a, b): return len(b) == len(a)
def en_a(a, b): return all(any(b[i] == a[j] for j in range(len(a))) for i in range(len(b)))
def en_b(a, b): return all(any(a[j] == b[i] for i in range(len(b))) for j in range(len(a)))
def apariciones(a, b): return all(cuenta(v, b) == cuenta(v, a) for v in set(a) | set(b))
specs = {
"ord": [ordenada],
"ord+long": [ordenada, longitud],
"ord+long+⊆+⊇": [ordenada, longitud, en_a, en_b],
"ord+apariciones": [ordenada, apariciones],
}
def relleno(a):
s = sorted(set(a))
return s + s[-1:] * (len(a) - len(s))
def burbuja_corta(a):
b = list(a)
for k in range(len(b) - 2): # falta la última pasada
for i in range(len(b) - 1 - k):
if b[i] > b[i + 1]:
b[i], b[i + 1] = b[i + 1], b[i]
return b
mutantes = {
"vacía": lambda a: [],
"ceros": lambda a: [0] * len(a),
"mínimo repetido": lambda a: [min(a)] * len(a) if a else [],
"sin duplicados": lambda a: sorted(set(a)),
"sin dup. + relleno": relleno,
"identidad": lambda a: list(a),
"burbuja corta": burbuja_corta,
"al revés": lambda a: sorted(a, reverse=True),
}
r = random.Random(1)
entradas = [[r.randint(0, 4) for _ in range(r.randint(0, 7))] for _ in range(3000)]
def cumple(spec, a, b): return all(c(a, b) for c in spec)
assert all(cumple(sp, a, sorted(a)) for sp in specs.values() for a in entradas) # la correcta las cumple
print(f"{'mutante':20s}" + "".join(f"{n:>17s}" for n in specs))
for nombre, prog in mutantes.items():
fila = ["detectado" if any(not cumple(sp, a, prog(a)) for a in entradas) else "PASA" for sp in specs.values()]
print(f"{nombre:20s}" + "".join(f"{c:>17s}" for c in fila))
# el teorema de unicidad, comprobado por fuerza bruta en entradas pequeñas
pequenas = [a for a in entradas if len(a) <= 6][:300]
assert all({p for p in permutations(a) if ordenada(a, p)} == {tuple(sorted(a))} for a in pequenas)
print(f"\nen {len(pequenas)} entradas, la única permutación ordenada de a es sorted(a)")The table reproduces the debugger: each added clause kills some mutants, “deduplicate and fill” survives all four set clauses, and only the occurrence clause kills all. Likewise binary search, comparing a weak postcondition, one forgetting range bounds, and the complete one:
def binaria(a, v):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == v:
return mid
if a[mid] < v:
lo = mid + 1
else:
hi = mid - 1
return -1
def post_debil(a, v, r): # «si devuelve un índice, ahí está v»
return r == -1 or (0 <= r < len(a) and a[r] == v)
def post_sin_rango(a, v, r): # completa, pero a[r] con la indexación de Python
if r == -1:
return all(a[i] != v for i in range(len(a)))
try:
return a[r] == v
except IndexError:
return False
def post_completa(a, v, r):
n = len(a)
if r == -1:
return all(a[i] != v for i in range(n))
return 0 <= r < n and a[r] == v
def binaria_lt(a, v): # while lo < hi: pierde el último candidato
lo, hi = 0, len(a) - 1
while lo < hi:
mid = (lo + hi) // 2
if a[mid] == v:
return mid
if a[mid] < v:
lo = mid + 1
else:
hi = mid - 1
return -1
def negativo(a, v): # devuelve el índice negativo equivalente: a[i - n] == a[i]
i = binaria(a, v)
return i - len(a) if 0 <= i < len(a) - 1 else i
mutantes_b = {
"rendirse (-1)": lambda a, v: -1,
"while lo < hi": binaria_lt,
"índice negativo": negativo,
"len(a) si no está": lambda a, v: (lambda i: len(a) if i == -1 else i)(binaria(a, v)),
}
r = random.Random(2)
casos = []
for _ in range(3000):
a = sorted(r.randint(0, 6) for _ in range(r.randint(0, 8)))
casos.append((a, r.randint(-1, 7)))
posts = {"débil": post_debil, "sin rango": post_sin_rango, "completa": post_completa}
assert all(p(a, v, binaria(a, v)) for p in posts.values() for a, v in casos)
print(f"{'mutante':20s}" + "".join(f"{n:>12s}" for n in posts))
for nombre, prog in mutantes_b.items():
fila = ["detectado" if any(not p(a, v, prog(a, v)) for a, v in casos) else "PASA" for p in posts.values()]
print(f"{nombre:20s}" + "".join(f"{c:>12s}" for c in fila))The weak postcondition misses a program giving up or losing candidates; the unbounded one accepts negative indices that point to the correct element in Python but mislead code expecting . Only the complete one detects them all. None sees Bloch’s bug, because Python integers have arbitrary precision: finding it requires modeling the language’s 32-bit integers, as the module project will (bounded model checking).
With professional tools
In Python the natural tool for checking specifications against many inputs is Hypothesis, which generates inputs and shrinks each counterexample to a minimum. The complete sorting postcondition is written just as in the previous cell (this code needs pip install hypothesis and runs with pytest in the local lab):
from collections import Counter
from hypothesis import given, strategies as st
@given(st.lists(st.integers()))
def test_ordenar_cumple_la_especificacion(a):
b = mi_ordenar(a)
assert all(b[i] <= b[i + 1] for i in range(len(b) - 1)) # Ord(b)
assert Counter(b) == Counter(a) # ∀v #(v, b) = #(v, a)
Counter(b) == Counter(a) is multiset equality. Tests, however, only explore inputs: they do not prove. Verification languages use the same formulas as annotations and prove them for all inputs. In Dafny, the sorting specification is literally this lesson’s:
method Ordenar(a: array<int>) returns (b: array<int>)
ensures b.Length == a.Length
ensures forall i, j :: 0 <= i < j < b.Length ==> b[i] <= b[j]
ensures multiset(b[..]) == multiset(a[..])
The verifier translates method and invariants into verification conditions and sends them to an SMT solver (Z3); if it cannot prove them, it identifies the clause it cannot guarantee. Here sorting uses two indices, , equivalent to consecutive indices by transitivity but more convenient for the prover. Equivalent tools are JML for Java, ACSL with Frama-C for C, and SPARK contracts for Ada. Proving a program satisfies a postcondition using loop invariants and weakest preconditions is the topic of lessons 8 and 9.
Common mistakes
Exercises
Step 1 of 4. How do you start proving the consequence?
('var', nombre) or ('fn', nombre, (args...)). Formulas: ('rel', nombre, (args...)), ('not', φ), ('and', φ, ψ), ('or', φ, ψ), ('imp', φ, ψ), ('forall', v, φ), and ('exists', v, φ). Implement free_vars(phi), returning the set of free-variable names, and subst(phi, x, t), returning without capture: if a quantifier over a variable of t has free occurrences of x in its scope, first rename that bound variable with a fresh name. Tests check capture cases and the substitution lemma on hundreds of random formulas, so the specific fresh name does not matter.def free_vars(phi):
"""Conjunto de nombres de las variables libres de phi."""
# tu código
return set()
def subst(phi, x, t):
"""phi[t/x] sin captura de variables."""
# tu código
return phiStep 1 of 4. How is defined?
Summary
- Syntax distinguishes terms (objects) from formulas (statements). Free and bound apply to individual occurrences; a sentence has no free variables and a truth value in every structure.
- Tarski semantics defines recursively, with and traversing a nonempty domain. In finite structures it is an algorithm costing ; Hintikka’s game explains decisions using witnesses and counterexamples.
- Under negation quantifiers change type and retain order; distributes over and over , not conversely; exiting an antecedent changes a quantifier; but not conversely, the distinction between continuity and uniform continuity.
- Substitution requires renaming bound variables that would capture the term (alpha renaming); naive substitution makes the substitution lemma fail when capture occurs.
- By completeness, logical consequence equals derivability, so validity is semidecidable; it is not decidable, and a finite counterexample refutes but finite checks do not prove.
- A complete sorting specification is “sorted and with the same occurrences of each value,” determining output; for search, absence and index range are essential. Measuring which mutants a specification detects is a practical way to find holes.