Module contents
Lesson 2 of 22Review 90 min

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 231−12^{31} - 1, possible for arrays with more than 2302^{30} 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 ∀\forall and ∃\exists, 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 {0,1,+,⋅,<}\{0, 1, +, \cdot, <\}, term x⋅x+1x \cdot x + 1 is a number and formula ∃y (x=y+y)\exists y\,(x = y + y) says “xx is even.” With the graph signature containing one binary relation symbol EE, formula ∀x ∃y E(x,y)\forall x\,\exists y\,E(x, y) 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: ¬\neg, ∀x\forall x, and ∃x\exists x bind more strongly than ∧\land, which binds more strongly than ∨\lor, then →\to, then ↔\leftrightarrow; →\to associates right. (Huth and Ryan give ∧\land and ∨\lor equal precedence; when in doubt, parenthesize.) Thus ∀x P(x)∧Q(x)\forall x\,P(x) \land Q(x) is (∀x P(x))∧Q(x)(\forall x\,P(x)) \land Q(x); to make the quantifier cover the conjunction write ∀x (P(x)∧Q(x))\forall x\,(P(x) \land Q(x)). Both graph interactives read formulas under these rules.

Free and bound variables

In ∀x φ\forall x\,\varphi, formula φ\varphi is the quantifier’s scope, and occurrences of xx inside are bound by it. An occurrence outside every quantifier over its variable is free. Free variables are computed recursively:

FV⁡(R(t1,…,tn))=var⁡(t1)∪⋯∪var⁡(tn),FV⁡(¬φ)=FV⁡(φ),FV⁡(φ∘ψ)=FV⁡(φ)∪FV⁡(ψ),FV⁡(∀x φ)=FV⁡(∃x φ)=FV⁡(φ)∖{x},\begin{aligned} \operatorname{FV}(R(t_1, \dots, t_n)) &= \operatorname{var}(t_1) \cup \cdots \cup \operatorname{var}(t_n), & \operatorname{FV}(\neg\varphi) &= \operatorname{FV}(\varphi), \\ \operatorname{FV}(\varphi \circ \psi) &= \operatorname{FV}(\varphi) \cup \operatorname{FV}(\psi), & \operatorname{FV}(\forall x\,\varphi) = \operatorname{FV}(\exists x\,\varphi) &= \operatorname{FV}(\varphi) \setminus \{x\}, \end{aligned}

where ∘\circ is any binary connective and var⁡(t)\operatorname{var}(t) are variables in term tt (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 ∃y E(x,y)\exists y\,E(x, y) is a property of xx whose value depends on which object xx is.

The same variable can have free and bound occurrences in one formula. In

∀x (E(x,y)∧∃y E(y,x))∨E(x,z)\forall x\,\big(E(x, y) \land \exists y\,E(y, x)\big) \lor E(x, z)

the yy in E(x,y)E(x, y) is free and that in E(y,x)E(y, x) is bound by ∃y\exists y; the xx in E(x,z)E(x, z) is outside the scope of ∀x\forall x and is free. Thus FV⁡={x,y,z}\operatorname{FV} = \{x, y, z\}, although xx and yy 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 ∀\forall clause (“for every d∈Dd \in D”) belong to mathematics used to discuss logic, the metalanguage, whereas ∀x\forall x is an object-language symbol. When DD is finite, “for every dd” 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 ss and s′s' agree on FV⁡(φ)\operatorname{FV}(\varphi), then M⊨φ[s]\mathcal{M} \models \varphi[s] iff M⊨φ[s′]\mathcal{M} \models \varphi[s']. Formula value depends only on free variables. In particular, a sentence has the same value under any assignment, written simply M⊨φ\mathcal{M} \models \varphi.
  • Nonempty domain. The condition D≠∅D \neq \emptyset matters: it guarantees ∀x φ→∃x φ\forall x\,\varphi \to \exists x\,\varphi is valid and the prenex laws below work. With empty domains, ∀x ⊥\forall x\,\bot would be true and ∃x ⊤\exists x\,\top false.

An example with two structures

Sentence ∀x ∃y (x+y=0)\forall x\,\exists y\,(x + y = 0) says every element has an additive inverse. In structure Z5=({0,1,2,3,4},+ mod 5,0)\Z_5 = (\{0, 1, 2, 3, 4\}, +\bmod 5, 0) it is true: the inverse of xx is 5−x5 - x (and 0’s is 0). In (N,+,0)(\N, +, 0) it is false: for x=1x = 1, no y∈Ny \in \N satisfies 1+y=01 + y = 0. The sentence has not changed; the structure has. Sentence ∀x ∃y (x<y)\forall x\,\exists y\,(x < y), “there is no maximum,” is true in (N,<)(\N, <) and false in ({0,…,4},<)(\{0, \dots, 4\}, <), where x=4x = 4 has no larger yy.

Truth as a game

The ∀\forall clause requires checking all elements and ∃\exists requires finding one. Jaakko Hintikka turned this asymmetry into a game between the verifier, seeking to show φ\varphi true, and falsifier, seeking to show it false. Play traverses the formula from the root:

  • At ∃x φ\exists x\,\varphi the verifier chooses d∈Dd \in D and play continues with φ\varphi and x↦dx \mapsto d. At ∀x φ\forall x\,\varphi the falsifier chooses.
  • At φ∨ψ\varphi \lor \psi the verifier chooses the disjunct; at φ∧ψ\varphi \land \psi the falsifier chooses the conjunct. (φ→ψ\varphi \to \psi is treated as ¬φ∨ψ\neg\varphi \lor \psi.)
  • At ¬φ\neg\varphi players swap roles and continue with φ\varphi.
  • At an atom inspect the structure: if true the current verifier wins, otherwise the other player does.
Proof

Induct on φ\varphi, simultaneously proving the dual claim: M⊭φ[s]\mathcal{M} \not\models \varphi[s] 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 M⊨φ[s]\mathcal{M} \models \varphi[s] and the falsifier otherwise; both equivalences follow. At an atom there are no moves and the definition selects the winner. At ∃x ψ\exists x\,\psi: if M⊨∃x ψ[s]\mathcal{M} \models \exists x\,\psi[s], some dd has M⊨ψ[s[x↦d]]\mathcal{M} \models \psi[s[x \mapsto d]], and by induction the verifier wins from there; its strategy is “choose dd and follow the winning strategy for ψ\psi.” If false, every dd has M⊭ψ[s[x↦d]]\mathcal{M} \not\models \psi[s[x \mapsto d]], and by the dual hypothesis the falsifier wins after any verifier choice. The ∀\forall case is symmetric, and ∨\lor and ∧\land are identical with two options instead of ∣D∣\abs{D}. At ¬ψ\neg\psi roles swap, so the verifier wins ¬ψ\neg\psi iff the falsifier wins ψ\psi, i.e. by the dual iff M⊭ψ[s]\mathcal{M} \not\models \psi[s], the negation clause.

∎

The game exposes what recursion hides: in ∀x ∃y\forall x\,\exists y, witness yy is chosen after seeing xx and can depend on it. A verifier winning strategy for ∀x ∃y φ(x,y)\forall x\,\exists y\,\varphi(x, y) is a function g:D→Dg : D \to D with M⊨φ(d,g(d))\mathcal{M} \models \varphi(d, g(d)) for every dd. This is a Skolem function; replacing ∃y\exists y with a fresh function symbol is Skolemization used by automated provers. In ∃y ∀x φ(x,y)\exists y\,\forall x\,\varphi(x, y) instead, the verifier commits to one yy before seeing any xx.

InteractiveVerifier versus falsifier game
∀x ∃y E(x,y)\forall x\, \exists y\, E(x, y): every node has a successor.
Still to decide∀x ∃y E(x,y)\forall x\, \exists y\, E(x, y)
abcd
Quantifier-free formula for each pair: rows xx, columns yy
y=ay = \mathsf{a}
y=by = \mathsf{b}
y=cy = \mathsf{c}
y=dy = \mathsf{d}
x=ax = \mathsf{a}
✗
✓
✗
✗
x=bx = \mathsf{b}
✗
✗
✓
✗
x=cx = \mathsf{c}
✗
✗
✗
✓
x=dx = \mathsf{d}
✓
✗
✗
✗
    You play as
    Scoreyou 0 · machine 0
    The machine, as falsifier, is choosing xx...
    Play against an optimal machine on a four-node graph. Start as verifier with ∀x ∃y E(x,y)\forall x\,\exists y\,E(x, y) on the cycle: falsifier chooses xx and you respond with a successor. Then switch to ∃y ∀x E(x,y)\exists y\,\forall x\,E(x, y) on the same graph: can you ever win? The table shows the quantifier-free formula for each pair; enable Tarski calculation and compare the two formulas: ‘every row has a true cell’ versus ‘there is a whole true row.’ Switch sides and graphs: you win only when your side has a winning strategy.

    On cycle a→b→c→d→aa \to b \to c \to d \to a, the verifier’s winning strategy for ∀x ∃y E(x,y)\forall x\,\exists y\,E(x, y) is “next node,” and falsifier cannot defeat it. For ∃y ∀x E(x,y)\exists y\,\forall x\,E(x, y) 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 xx 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 dd for everyone: this illustrates ∃y ∀x\exists y\,\forall x entails ∀x ∃y\forall x\,\exists y, 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.

    InteractiveFormulas on a graph you draw
    Read as∀x ∃y E(x,y)\forall x\, \exists y\, E(x, y)
    abcd
    Certificate
    • True: for each value of xx.
    • x=ax = \mathsf{a}: y=b: E(a,b)y = \mathsf{b}:\ E(\mathsf{a}, \mathsf{b})
    • x=bx = \mathsf{b}: y=c: E(b,c)y = \mathsf{c}:\ E(\mathsf{b}, \mathsf{c})
    • x=cx = \mathsf{c}: y=d: E(c,d)y = \mathsf{d}:\ E(\mathsf{c}, \mathsf{d})
    • x=dx = \mathsf{d}: y=a: E(d,a)y = \mathsf{a}:\ E(\mathsf{d}, \mathsf{a})
    • edge supporting the verdict
    • edge whose absence determines it
    • label x, y, z...: node assigned to that variable (one color per variable)
    Nodes
    Verdicttrue
    Free variables∅ (a sentence)
    Quantifier depth2
    Atoms evaluated10
    Worst-case assignments, ∣D∣k\abs{D}^k42=164^{2} = 16
    Tap one node then another to add or remove their edge, and enter formulas over signature {E,=}\{E, =\}. The tool decides M⊨φ\mathcal{M} \models \varphi and highlights why using the winning side's strategy (verifier witnesses if true, falsifier counterexample if false): present edges supporting the verdict in aquamarine and absent deciding edges in dashed red. Try ‘every node has a successor’ and remove an edge until false; enter an open formula such as ∃y E(x,y)\exists y\,E(x, y) and observe dependence on the node assigned to xx; try the trap at the end of the list: why is it true in almost any graph?

    Try three things in the interactive.

    1. 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 gg, 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.
    2. Cost is exponential in depth. Evaluated-atom count grows as ∣D∣k\abs{D}^k, where kk is quantifier nesting depth: transitivity with three quantifiers examines up to ∣D∣3\abs{D}^3 triples. Recursively evaluating formula φ\varphi on a finite structure costs O(∣φ∣⋅∣D∣k)\bigO(\abs{\varphi} \cdot \abs{D}^k): polynomial for a fixed formula and exponential if the formula is input (the general problem is PSPACE-complete).
    3. What a finite graph cannot satisfy. Select “Irreflexive, transitive, and no end,” ∀x ¬E(x,x)∧∀x ∀y ∀z (E(x,y)∧E(y,z)→E(x,z))∧∀x ∃y E(x,y)\forall x\,\neg E(x, x) \land \forall x\,\forall y\,\forall z\,(E(x, y) \land E(y, z) \to E(x, z)) \land \forall x\,\exists y\,E(x, y), and draw any graph: it is always false. The next example explains why.

    Quantifier laws

    Formulas are logically equivalent, φ≡ψ\varphi \equiv \psi, if M⊨φ[s]\mathcal{M} \models \varphi[s] and M⊨ψ[s]\mathcal{M} \models \psi[s] 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) M⊨¬∀x φ[s]\mathcal{M} \models \neg\forall x\,\varphi[s] iff it is not true that φ\varphi holds under s[x↦d]s[x \mapsto d] for every dd, iff some dd makes it fail. (2) “For every dd, A(d)A(d) and B(d)B(d)” is equivalent to “for every dd, A(d)A(d)” and “for every dd, B(d)B(d).” (3) By coincidence, χ\chi‘s value under s[x↦d]s[x \mapsto d] does not depend on dd; hence ∀x χ≡χ\forall x\,\chi \equiv \chi, using D≠∅D \neq \emptyset. Others reduce to this and (1)–(2): for example ∀x (φ→χ)≡∀x (¬φ∨χ)≡∀x ¬φ∨χ≡¬∃x φ∨χ≡∃x φ→χ\forall x\,(\varphi \to \chi) \equiv \forall x\,(\neg\varphi \lor \chi) \equiv \forall x\,\neg\varphi \lor \chi \equiv \neg\exists x\,\varphi \lor \chi \equiv \exists x\,\varphi \to \chi. (4) Both express “for every pair (d,e)(d, e).” (5) is the first guided exercise.

    ∎

    The other two distributions in (2) are false; keep the smallest counterexample handy. With D={0,1}D = \{0, 1\}, P={0}P = \{0\}, and Q={1}Q = \{1\}, every element satisfies PP or QQ, so ∀x (P(x)∨Q(x))\forall x\,(P(x) \lor Q(x)) is true; but not all satisfy PP and not all satisfy QQ. In the same structure someone is in PP and someone in QQ, but nobody in both: ∃x P(x)∧∃x Q(x)\exists x\,P(x) \land \exists x\,Q(x) does not imply ∃x (P(x)∧Q(x))\exists x\,(P(x) \land Q(x)). One-way implications do hold: ∀x φ∨∀x ψ⊨∀x (φ∨ψ)\forall x\,\varphi \lor \forall x\,\psi \models \forall x\,(\varphi \lor \psi) and ∃x (φ∧ψ)⊨∃x φ∧∃x ψ\exists x\,(\varphi \land \psi) \models \exists x\,\varphi \land \exists x\,\psi.

    Continuity versus uniform continuity

    Quantifier order is not style. Continuity of f:R→Rf : \R \to \R at every point and uniform continuity differ only in where ∀a\forall a occurs:

    continuous:∀ε>0 ∀a ∃δ>0 ∀x (∣x−a∣<δ→∣f(x)−f(a)∣<ε),uniformly continuous:∀ε>0 ∃δ>0 ∀a ∀x (∣x−a∣<δ→∣f(x)−f(a)∣<ε).\begin{aligned} \text{continuous:}\quad &\forall \eps > 0\ \forall a\ \exists \delta > 0\ \forall x\,\big(\abs{x - a} < \delta \to \abs{f(x) - f(a)} < \eps\big), \\ \text{uniformly continuous:}\quad &\forall \eps > 0\ \exists \delta > 0\ \forall a\ \forall x\,\big(\abs{x - a} < \delta \to \abs{f(x) - f(a)} < \eps\big). \end{aligned}

    In the game, in the first the verifier chooses δ\delta after seeing ε\eps and aa: its strategy is a function δ(ε,a)\delta(\eps, a). In the second δ(ε)\delta(\eps) cannot depend on the point. For f(x)=x2f(x) = x^2, δ=min⁡(1,ε/(2∣a∣+1))\delta = \min(1, \eps/(2\abs{a} + 1)) suffices and tends to 0 as ∣a∣\abs{a} grows; no fixed δ\delta works for every aa: with ε=1\eps = 1, for any δ>0\delta > 0 the falsifier plays a=1/δa = 1/\delta and x=a+δ/2x = a + \delta/2, giving ∣x2−a2∣=δ2 (2a+δ2)=1+δ24>ε\abs{x^2 - a^2} = \tfrac{\delta}{2}\,(2a + \tfrac{\delta}{2}) = 1 + \tfrac{\delta^2}{4} > \eps. Definitions of PAC learnability have the same form, ∀ε ∀δ ∃m ∀D\forall \eps\,\forall \delta\,\exists m\,\forall \mathcal{D}, and order decides whether sample size may depend on distribution.

    Prenex form

    A formula is in prenex form if it is Q1x1⋯Qkxk μQ_1 x_1 \cdots Q_k x_k\,\mu with each Qi∈{∀,∃}Q_i \in \{\forall, \exists\} and μ\mu quantifier-free. Every formula is equivalent to a prenex one, and the proof is an algorithm like conversion to conjunctive normal form: eliminate ↔\leftrightarrow, rename bound variables to be distinct from one another and free ones, and move quantifiers outward with laws (1) and (3), changing ∀\forall to ∃\exists whenever a quantifier exits an antecedent or negation. Renaming is mandatory, as this example’s second step shows:

    ∀x E(x,y)→∃x ∀y E(y,x)\forall x\,E(x, y) \to \exists x\,\forall y\,E(y, x)
    The antecedent's y is free; the consequent's is bound. Separate them before moving anything.
    1/5

    If step 2 does not rename yy, pulling ∀y\forall y outward captures the free yy in E(x,y)E(x, y) and changes the formula’s meaning. Prenex form is not unique (independent quantifiers may be moved in either order), and prefix alternation, ∀∃\forall\exists, ∃∀∃\exists\forall\exists…, measures logical complexity and reappears in computability.

    Substitution and variable capture

    Quantifier inference rules need instantiation: from ∀x φ\forall x\,\varphi derive φ\varphi with xx replaced by any term tt, written φ[t/x]\varphi[t/x]. The naive definition “replace every free occurrence of xx with tt” has a flaw. Let φ(x)=∃y (x<y)\varphi(x) = \exists y\,(x < y), “xx is not the maximum.” Replacing xx with yy should mean “yy is not the maximum,” but literal replacement produces

    ∃y (y<y),\exists y\,(y < y),

    which is false in any strict order. The inserted yy was free and got captured by ∃y\exists y. Meaning cannot depend on names of bound variables: ∃y (x<y)\exists y\,(x < y) and ∃z (x<z)\exists z\,(x < z) say the same. Rename before substituting.

    With the correct definition, (∃y (x<y))[y/x]=∃z (y<z)(\exists y\,(x < y))[y/x] = \exists z\,(y < z), exactly what we wanted. The justification is the substitution lemma: for every term tt,

    M⊨φ[t/x] [s]  ⟺  M⊨φ [s[x↦tM[s]]].\mathcal{M} \models \varphi[t/x]\,[s] \iff \mathcal{M} \models \varphi\,\big[s[x \mapsto t^{\mathcal{M}}[s]]\big].

    Syntactically substituting tt for xx equals evaluating φ\varphi with xx assigned the value of tt. Prove by induction on φ\varphi; 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, φ\varphi is valid iff ¬φ\neg\varphi is unsatisfiable, and Γ⊨φ\Gamma \models \varphi iff Γ∪{¬φ}\Gamma \cup \{\neg\varphi\} 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 ⇒\Rightarrow is completeness proper, and ⇐\Leftarrow soundness, proven by induction on derivations (see soundness and completeness). Two immediate consequences: derivations are finite, so if Γ⊨φ\Gamma \models \varphi then φ\varphi follows from a finite subset of Γ\Gamma (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 φ∞\varphi_\infty 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: ∀i (0≤i<n→φ(i))\forall i\,(0 \le i < n \to \varphi(i)), Python all(phi(i) for i in range(n)), and ∃i (0≤i<n∧φ(i))\exists i\,(0 \le i < n \land \varphi(i)), any(...). Note connectives: bounded universal uses →\to and existential uses ∧\land. With arrays, “bb is sorted” is

    Ord(b)  ≡  ∀i (0≤i<∣b∣−1→b[i]≤b[i+1]),\mathrm{Ord}(b) \;\equiv\; \forall i\,\big(0 \le i < \abs{b} - 1 \to b[i] \le b[i + 1]\big),

    and a complete sorting postcondition additionally requires bb be a permutation of aa, expressed with count function #(v,b)=∣{i:0≤i<∣b∣, b[i]=v}∣\#(v, b) = \abs{\{i : 0 \le i < \abs{b},\ b[i] = v\}}, the occurrences of vv:

    Postord(a,b)  ≡  Ord(b)∧∀v (#(v,b)=#(v,a)).\mathrm{Post}_{\mathrm{ord}}(a, b) \;\equiv\; \mathrm{Ord}(b) \land \forall v\,\big(\#(v, b) = \#(v, a)\big).

    The second part says aa and bb are the same multiset. Having the same elements is insufficient: ∀i ∃j (b[i]=a[j])\forall i\,\exists j\,(b[i] = a[j]) and its converse compare only value sets, and [1,2,2][1, 2, 2] has the same values as [1,1,2][1, 1, 2] 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 π\pi of indices with b[i]=a[π(i)]b[i] = a[\pi(i)],” quantifying over functions and leaving first order.

    Proof

    Existence: sort aa with any correct algorithm. For uniqueness let bb and cc be sorted lists with the same occurrences of every value as aa. For each value vv, the number of positions with b[j]<vb[j] < v is ∑w<v#(w,b)=∑w<v#(w,a)\sum_{w < v} \#(w, b) = \sum_{w < v} \#(w, a), likewise for cc; call it L(v)L(v). Likewise positions with b[j]≤vb[j] \le v number the same in bb and cc; call it U(v)U(v). In a sorted list positions containing vv are exactly those ii with L(v)≤i<U(v)L(v) \le i < U(v). Hence for every index ii, b[i]b[i] is the unique vv with L(v)≤i<U(v)L(v) \le i < U(v), and so is c[i]c[i]: b[i]=c[i]b[i] = c[i]. And ∣b∣=∑v#(v,a)=∣c∣\abs{b} = \sum_v \#(v, a) = \abs{c}.

    ∎

    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, Postord\mathrm{Post}_{\mathrm{ord}} on keys does not fix order among equal-key records, and stability is an extra clause to request explicitly.

    For binary search of xx in an array aa of length nn returning an index or −1-1:

    Pre(a)≡Ord(a),Post(a,x,r)≡(r=−1∧∀i (0≤i<n→a[i]≠x))∨(0≤r<n∧a[r]=x).\begin{aligned} \mathrm{Pre}(a) &\equiv \mathrm{Ord}(a), \\ \mathrm{Post}(a, x, r) &\equiv \Big(r = -1 \land \forall i\,\big(0 \le i < n \to a[i] \neq x\big)\Big) \lor \Big(0 \le r < n \land a[r] = x\Big). \end{aligned}

    Each part has a purpose. Without the complete first disjunct, return -1 satisfies the specification. Without range 0≤r<n0 \le r < n, in a language with negative indices like Python, a[r] == x can hold for a negative rr the rest of the program does not expect. The precondition is not decorative: if aa is unsorted, binary search can return −1-1 even though xx occurs, and the caller is at fault. Preconditions are caller obligations; postconditions are callee guarantees.

    InteractiveSpecification debugger against an adversary
    Postcondition of b=ordenar⁡(a)b = \operatorname{ordenar}(a): conjunction of selected clauses. Indices start at 0; #(v,b)\#(v, b) counts occurrences of vv in bb.
    Adversary programs
    Correct sortcorrect · accepted
    return sorted(a)
    Satisfies the specification on every input.
    Empty listincorrect · ACCEPTED
    return []
    Satisfies the specification, but for a = [2] returns [] instead of [2].
    Zerosincorrect · ACCEPTED
    return [0] * len(a)
    Satisfies the specification, but for a = [2] returns [0] instead of [2].
    Repeat the minimumincorrect · ACCEPTED
    return [min(a)] * len(a) if a else []
    Satisfies the specification, but for a = [2, 1] returns [1, 1] instead of [1, 2].
    Remove duplicatesincorrect · ACCEPTED
    return sorted(set(a))
    Satisfies the specification, but for a = [1, 1] returns [1] instead of [1, 1].
    Remove duplicates and padincorrect · ACCEPTED
    s = sorted(set(a))
    return s + s[-1:] * (len(a) - len(s))
    Satisfies the specification, but for a = [2, 3, 2, 4] returns [2, 3, 4, 4] instead of [2, 2, 3, 4].
    Return inputincorrect · rejected
    return a
    For a = [2, 1] returns [2, 1]: fails “b is sorted».
    Bubble sort with one fewer passincorrect · rejected
    b = list(a)
    for k in range(len(b) - 2):
        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
    For a = [2, 1] returns [2, 1]: fails “b is sorted».
    Algorithm
    Active clauses1
    Inputs tested407
    Incorrect programs accepted5 of 7
    Correct programs rejected0
    The adversary wins: 5 of 7 incorrect programs satisfy your specification on all 407 inputs. Strengthen it.
    Select postcondition clauses. The adversary has a collection of correct, absurd, and subtly broken programs and tests them against your specification on about 400 random inputs. An incorrect program satisfying it on all means the specification is weak; a correct one failing it means it is too strong. Start with only ‘sorted’ and strengthen it. Are same length and same values in both directions enough? Then switch to search and try dashed-border clauses outside the intention.

    The adversary’s lesson fits a table. “Sorted” accepts the empty list; with length, zeros; with “every value of bb is in aa,” repeated minimum; with all four set clauses it still accepts “remove duplicates and fill with maximum,” turning [1,1,2][1, 1, 2] into [1,2,2][1, 2, 2]. Only the count clause closes the hole, making everything except “sorted” redundant: length follows by summing #(v,⋅)\#(v, \cdot) over values, and inclusions from #(v,b)>0\#(v, b) > 0 iff #(v,a)>0\#(v, a) > 0. For search, “strictly first occurrence” rejects correct binary search, which on [1,2,2,2,5][1, 2, 2, 2, 5] returns index 2 (midpoint), while unconditional a[r]=xa[r] = x rejects every correct program when xx 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.

    [ ]Formulas, free variables, and satisfactionBrowser
    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 ∀\forall and ∃\exists clauses, and {**s, phi.var: d} is assignment s[x↦d]s[x \mapsto d]. 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 E(x,y)E(x, y) in all n3n^3 triples, E(y,z)E(y, z) in the n2n^2 where E(x,y)E(x, y) holds, and E(x,z)E(x, z) in the nn where both hold: n3+n2+nn^3 + n^2 + n 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 ∀x ∃y\forall x\,\exists y and ∃y ∀x\exists y\,\forall x; checking quantifier laws under all interpretations of two unary predicates finds counterexamples to failing laws.

    [ ]Quantifier laws by brute forceBrowser
    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 ∀x ∃y E(x,y)\forall x\,\exists y\,E(x, y) (each of three adjacency-matrix rows must be nonzero: 737^3), and 169 satisfy ∃y ∀x E(x,y)\exists y\,\forall x\,E(x, y) (some full column: 512−73512 - 7^3). 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: ∃x (P(x)→Q(x))\exists x\,(P(x) \to Q(x)) is equivalent to ∀x P(x)→∃x Q(x)\forall x\,P(x) \to \exists x\,Q(x), hence true whenever some element fails PP.

    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, M⊨φ[t/x][s]  ⟺  M⊨φ[s[x↦tM[s]]]\mathcal{M} \models \varphi[t/x][s] \iff \mathcal{M} \models \varphi[s[x \mapsto t^{\mathcal{M}}[s]]], in each case.

    [ ]Naive substitution and captureBrowser
    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.

    [ ]Sorting specifications against mutantsBrowser
    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:

    [ ]Binary search specificationsBrowser
    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 0≤r<n0 \le r < n. 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, ∀i,j (0≤i<j<n→b[i]≤b[j])\forall i, j\,(0 \le i < j < n \to b[i] \le b[j]), 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

    QuizFree and bound
    What is the free-variable set of ∀x (E(x,y)∧∃y E(y,x))∨E(x,z)\forall x\,\big(E(x, y) \land \exists y\,E(y, x)\big) \lor E(x, z)?
    QuizNegating continuity
    Continuity of ff at aa is ∀ε>0 ∃δ>0 ∀x (∣x−a∣<δ→∣f(x)−f(a)∣<ε)\forall \eps > 0\ \exists \delta > 0\ \forall x\,\big(\abs{x - a} < \delta \to \abs{f(x) - f(a)} < \eps\big). What is its negation?
    QuizMove a quantifier from an antecedent
    If xx does not occur free in χ\chi, which formula is equivalent to ∀x (φ→χ)\forall x\,(\varphi \to \chi)?
    QuizFormalize an access policy
    With Admin(u)\mathrm{Admin}(u), Servidor(s)\mathrm{Servidor}(s), and Acceso(u,s)\mathrm{Acceso}(u, s), which formula says ‘some administrator has access to every server’?
    NumericCounting relations
    How many of the 29=5122^9 = 512 binary relations EE over {0,1,2}\{0, 1, 2\} satisfy ∀x ∃y E(x,y)\forall x\,\exists y\,E(x, y) but not ∃y ∀x E(x,y)\exists y\,\forall x\,E(x, y)?
    Proof∃∀ implies ∀∃, not conversely
    Prove: ∃y ∀x P(x,y)⊨∀x ∃y P(x,y)\exists y\,\forall x\,P(x, y) \models \forall x\,\exists y\,P(x, y), and there exists a finite structure where ∀x ∃y P(x,y)\forall x\,\exists y\,P(x, y) is true and ∃y ∀x P(x,y)\exists y\,\forall x\,P(x, y) false.
    0
    Recall Γ⊨φ\Gamma \models \varphi means every structure satisfying Γ\Gamma satisfies φ\varphi.

    Step 1 of 4. How do you start proving the consequence?

    CodeFree variables and capture-avoiding substitution
    Formulas are represented as tuples. Terms: ('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 φ[t/x]\varphi[t/x] 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 phi
    Shift+Enter to run
    QuizBinary search postcondition
    With precondition ‘aa sorted’ and n=∣a∣n = \abs{a}, search returns an index of xx or −1-1 if xx is absent. Which postcondition is correct?
    ProofThe complete specification excludes the empty list
    Prove: Let Post(a,b)≡Ord(b)∧∀v (#(v,b)=#(v,a))\mathrm{Post}(a, b) \equiv \mathrm{Ord}(b) \land \forall v\,\big(\#(v, b) = \#(v, a)\big) with Ord(b)≡∀i (0≤i<∣b∣−1→b[i]≤b[i+1])\mathrm{Ord}(b) \equiv \forall i\,(0 \le i < \abs{b} - 1 \to b[i] \le b[i + 1]). If aa is nonempty, b=[ ]b = [\,] does not satisfy Post(a,b)\mathrm{Post}(a, b); it does satisfy Ord(b)\mathrm{Ord}(b).
    0
    First formalize the count function, then reason about both parts of the postcondition.

    Step 1 of 4. How is #(v,b)\#(v, b) defined?

    Summary

    Key idea
    A first-order formula is true in a structure exactly when the verifier has a winning strategy in its evaluation game; specifying an algorithm means writing a formula whose only models are correct programs, checked by seeking the adversary: an absurd program satisfying it.
    • 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 M⊨φ[s]\mathcal{M} \models \varphi[s] recursively, with ∀\forall and ∃\exists traversing a nonempty domain. In finite structures it is an algorithm costing O(∣φ∣⋅∣D∣k)\bigO(\abs{\varphi} \cdot \abs{D}^k); Hintikka’s game explains decisions using witnesses and counterexamples.
    • Under negation quantifiers change type and retain order; ∀\forall distributes over ∧\land and ∃\exists over ∨\lor, not conversely; exiting an antecedent changes a quantifier; ∃∀⊨∀∃\exists\forall \models \forall\exists 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.