Module contents
Lesson 13 of 23Advanced 120 min

SMT: satisfiability modulo theories and the design of Z3

Study SMT, the DPLL(T) interface and theory explanations, congruence closure, difference logic, arithmetic, bit-blasting, theory combination and Z3.

After this lesson you can

  • Explain DPLL(T) and distinguish eager and lazy approaches.
  • Implement theory solvers for equality with uninterpreted functions and difference logic with explanations.
  • Describe SMT general simplex and bit-blasting and reason about their costs.
  • Combine theories using Nelson–Oppen and recognize the role of convexity.
  • Model problems in Z3, choosing the appropriate SMT-LIB logic.

Before you start

Motivation: when Booleans are not enough

Last lesson you built a CDCL solver, able to decide formulas with millions of clauses. Questions of practical interest rarely arrive as clauses. They look like this:

  • Can this allocation overflow? In C, malloc(n * 4) allocates less than requested if n * 4 wraps at 32 bits. The question is whether an n exists with n>0n > 0 and 4n mod 232<n4n \bmod 2^{32} < n. This is machine-integer arithmetic.
  • Does this schedule fit? Tasks with durations, precedence constraints and one machine must finish by a deadline. This is linear arithmetic over start times with disjunctions (“A before B, or B before A”).
  • Are these programs equivalent? A compiler eliminated a common subexpression. Translation validation need not know what multiplication does: it suffices that it is a function, so equal arguments yield equal results.
  • Can this neural network produce the wrong output in an input region? This is real linear arithmetic with ReLU constraints, solved by Reluplex (Katz et al., 2017), studied alongside certified robustness.

All of this can be translated to SAT: 32-bit integers are 32 Booleans, and start times can use the lesson 11 order encoding. But translation has a measurable cost: a schedule’s order encoding grows with time horizon, and a 32-bit multiplication exceeds eight thousand clauses. Structure is lost too: to a shortest-path algorithm, x<y<z<xx < y < z < x is a negative-weight cycle found in polynomial time, while SAT on the CNF must rediscover the impossibility clause by clause.

Satisfiability modulo theories (SMT) divides the work. CDCL handles Boolean structure; each theory (equality, arithmetic, bit-vectors, arrays) supplies a specialized decision procedure for conjunctions of atoms: union-find, Bellman–Ford, simplex. Their interface is the central topic: how theory explains conflicts so CDCL can learn. By the end you will understand Z3’s design, have programmed DPLL(T) for difference logic and congruence closure with explanations, and know how to choose the right theory.

Theories, logics and SMT-LIB

An SMT formula is a quantifier-free first-order formula whose symbols have predetermined meaning. In x+1≤y∧f(x)≠f(y)x + 1 \le y \land f(x) \neq f(y), ++ and ≤\le are not freely interpreted as in general first-order semantics: they mean integer addition and order. ff, however, is free.

Common theories and the cost of deciding a conjunction of literals (the theory solver’s job; CDCL supplies disjunction):

TheoryTypical atomsLiteral conjunctionsProcedure
Equality with uninterpreted functions (EUF)f(a)=bf(a) = b, g(x,y)≠zg(x, y) \neq zO(nlog⁡n)\bigO(n \log n)congruence closure
Difference logic (IDL, RDL)x−y≤cx - y \le cpolynomial, O(nm)\bigO(nm)Bellman–Ford
Linear real arithmetic (LRA)2x−3y+z≤72x - 3y + z \le 7polynomialsimplex (exponential worst case, fast in practice)
Linear integer arithmetic (LIA)same over Z\ZNP-completesimplex with branching and cuts
Bit-vectors (BV)bvadd x y = z, bvultNP-complete (counting each bit in size)bit-blasting to SAT
Arrays (AX)select(store(a, i, v), j)NP-completeread-over-write axioms

The third-column bounds are classical: Downey, Sethi and Tarjan’s (1980) congruence closure is O(nlog⁡n)\bigO(n \log n); linear programming has been polynomial since Khachiyan’s ellipsoid method (1979), though solvers use simplex; integer linear arithmetic contains 0–1 integer programming, which is NP-hard.

Uninterpreted functions seem useless but are extremely useful. They satisfy only equality axioms (reflexive, symmetric, transitive) and congruence: s1=t1∧⋯∧sk=tk⇒f(s1,…,sk)=f(t1,…,tk)s_1 = t_1 \land \dots \land s_k = t_k \Rightarrow f(s_1, \dots, s_k) = f(t_1, \dots, t_k). They abstract: to prove two programs equivalent when the proof does not depend on multiplication’s details, replace multiplication with arbitrary ff. Equivalence proved for every ff holds for multiplication, turning nonlinear integer arithmetic (undecidable) into nearly linear-time EUF.

SMT-LIB: a common format

SMT-LIB specifies a common solver language and logic catalog. Logic names are assembled from QF_ (quantifier-free), UF (uninterpreted functions), A or AX (arrays), BV (bit-vectors), IDL and RDL (integer and real differences), LIA, LRA, NIA (linear integer, linear real, nonlinear integer arithmetic). Thus QF_AUFLIA means quantifier-free arrays, uninterpreted functions and linear integer arithmetic, typical for array-program verification. Declaring logic tells the solver which procedures to load and which simplifications are sound. An SMT-LIB 2 problem looks like this (in lab 3, s.sexpr() prints this example’s declarations and assertions):

(set-logic QF_LIA)
(declare-fun p () Int)
(declare-fun q () Int)
(assert (>= (+ p (* 2 q)) 3))
(assert (<= (- p q) 1))
(assert (or (< p 0) (> q 5)))
(check-sat)
(get-model)

Arrays have a theory with two symbols, select (read) and store (write), and two read-over-write axioms: select(store(a,i,v),i)=v\mathrm{select}(\mathrm{store}(a, i, v), i) = v and i≠j⇒select(store(a,i,v),j)=select(a,j)i \neq j \Rightarrow \mathrm{select}(\mathrm{store}(a, i, v), j) = \mathrm{select}(a, j), plus extensionality (arrays agreeing at every index are equal). The second axiom forces case distinctions on whether indices agree, explaining NP-completeness of conjunctions.

Eager or lazy

There are two ways to use SAT to decide an SMT formula.

The eager approach translates the entire formula into equisatisfiable CNF once and calls SAT once. For bit-vectors this is natural: bit-blasting below. For EUF, Ackermann reduction (1954) replaces each application f(ti)f(t_i) with a fresh constant FiF_i and, for each pair of applications of the same symbol, adds functional consistency constraint ti=tj⇒Fi=Fjt_i = t_j \Rightarrow F_i = F_j. The resulting equality logic is encoded in SAT. Difference logic has encodings adding transitivity constraints between differences (Strichman, Seshia and Bryant, 2002). The appeal is using SAT unchanged with all its preprocessing. Size is the problem: Ackermann is quadratic in each symbol’s application count, transitivity can be cubic, and order encoding grows with constants.

The lazy approach does not translate everything. It replaces each theory atom with a fresh Boolean variable, yielding the formula’s Boolean abstraction (or propositional skeleton). For example,

(x−y≤−2)⏟p1∧((y−z≤−3)⏟p2∨(z−x≤4)⏟p3)  ⟼  p1∧(p2∨p3).\underbrace{(x - y \le -2)}_{p_1} \land \big(\underbrace{(y - z \le -3)}_{p_2} \lor \underbrace{(z - x \le 4)}_{p_3}\big) \;\longmapsto\; p_1 \land (p_2 \lor p_3).

Each abstraction model says which atoms are true and false: a conjunction of theory literals, exactly what the theory solver can decide. If TT-consistent, the original formula has a model. Otherwise theory returns an inconsistent subset EE, its explanation, and SAT learns clause ⋁ℓ∈E¬ℓ\bigvee_{\ell \in E} \neg\ell, which is TT-valid: no TT model makes all literals of EE true together.

The simplest offline lazy loop alternates until SAT runs out of models or theory accepts one. Explanation size determines efficiency. The figure uses a scheduling problem: three tasks on one machine, durations 2, 3 and 1, all within [0,H][0, H] with A before C. Each task pair gives two atoms, “X before Y” (sX−sY≤−dXs_X - s_Y \le -d_X) and its opposite; the abstraction requires at least one.

InteractiveSAT and theory dialogue
Durations: A = 2, B = 3, C = 1. Also, A finishes before C starts. “X < Y” means X finishes before Y starts.
Round 1
SAT: I propose this assignment of the Boolean abstraction
A < BB < AA < CC < AB < CC < B
plus unit constraints: start and end bounds and precedence
Theory: inconsistent; the explanation is
C < BB < C
Blocking clause (2 literals): ¬(C < B) ∨ ¬(B < C)
Learned clauses: 1
¬(C < B) ∨ ¬(B < C)
  • true atom
  • false atom
  • both orders at once (or explanation)
5
Theory explains using
round 1 of 8
Rounds with negative cycle8 (unsat)
Rounds with full assignment27 (unsat)
Mean clause length: cycle · assignment3.0 · 13.0
Total duration (one machine: H must be at least the sum)6
SAT proposes a complete Boolean-abstraction assignment; theory checks it with Bellman–Ford and, if inconsistent, returns an explanation whose negation is the blocking clause. With ‘negative cycle’ the explanation has two to four literals; with ‘whole assignment’ it blocks only the proposed assignment. Compare rounds for H = 5 (unsatisfiable: durations total 6) and H = 6, then switch to four tasks.

With H=5H = 5 the problem is unsatisfiable because durations total 6. Minimal explanations prove it in 8 rounds; returning the full assignment takes 27. With four tasks and H=7H = 7 the difference is 38 versus 729, not by chance: 729=36729 = 3^6. Each of 6 pairs permits three combinations (one order, the other, or both), giving 363^6 abstraction models, all inconsistent; a clause negating the full assignment excludes exactly one. By contrast a clause of kk literals over nn free atoms excludes the 2n−k2^{n-k} total assignments falsifying it. This is enumeration versus reasoning.

The counts do not depend on the widget: the next cell implements the same Python loop, same decision order (SAT returns the first lexicographic model, true before false), and same Bellman–Ford.

[ ]The simplest lazy loopBrowser
import itertools

def planificacion(tareas, H, prec=()):
    """Átomos x - y <= c (z es el origen de tiempos). Devuelve los átomos y los pares de órdenes alternativas."""
    atomos, pares = [], []
    dur = dict(tareas)
    for t, d in tareas:
        atomos.append(("z", t, 0, f"{t} ≥ 0", True))            # s_t >= 0
        atomos.append((t, "z", H - d, f"{t} ≤ {H - d}", True))   # s_t + d <= H
    for a, b in prec:
        atomos.append((a, b, -dur[a], f"{a} → {b}", True))       # a termina antes de que empiece b
    for (a, da), (b, db) in itertools.combinations(tareas, 2):
        atomos.append((a, b, -da, f"{a} < {b}", False))
        atomos.append((b, a, -db, f"{b} < {a}", False))
        pares.append((len(atomos) - 2, len(atomos) - 1))
    return atomos, pares

def arista(atomos, l):
    x, y, c = atomos[abs(l) - 1][:3]
    return (y, x, c) if l > 0 else (x, y, -c - 1)   # ¬(x - y <= c)  <=>  y - x <= -c - 1 en enteros

def teoria(atomos, lits):
    """Bellman-Ford desde una fuente virtual: (True, modelo) o (False, literales de un ciclo negativo)."""
    E = [(arista(atomos, l), l) for l in lits]
    nodos = sorted({v for (u, w, _), _ in E for v in (u, w)})
    dist = {v: 0 for v in nodos}; pred = {}
    for _ in range(len(nodos)):
        ultimo = None
        for (u, v, w), l in E:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w; pred[v] = (u, l); ultimo = v
        if ultimo is None:
            return True, {v: dist[v] - dist["z"] for v in nodos}
    v = ultimo
    for _ in range(len(nodos)):
        v = pred[v][0]
    ciclo, u = [], v
    while True:
        u, l = pred[u]; ciclo.append(l)
        if u == v:
            return False, ciclo

def bucle_perezoso(atomos, pares, modo):
    """El SAT devuelve el primer modelo (cierto antes que falso, en el orden de los átomos) de la abstracción
    booleana más lo aprendido; la teoría lo comprueba y explica con el ciclo ('min') o con todo ('full')."""
    unidades = [k + 1 for k, a in enumerate(atomos) if a[4]]
    libres = [k for k, a in enumerate(atomos) if not a[4]]
    n = len(libres); bit = {a: 1 << (n - 1 - i) for i, a in enumerate(libres)}
    aprendidas, vueltas, mask = [], 0, 0      # bit a 1: ese átomo libre es falso
    while True:
        while mask < (1 << n):
            if all(not (mask & bit[p] and mask & bit[q]) for p, q in pares) and \
               all((~mask & t) or (mask & f) for t, f in aprendidas):
                break
            mask += 1
        else:
            return "unsat", vueltas, None
        vueltas += 1
        lits = [-(a + 1) if mask & bit[a] else a + 1 for a in libres]
        ok, res = teoria(atomos, unidades + lits)
        if ok:
            return "sat", vueltas, res
        expl = res if modo == "min" else unidades + lits
        if any(l < 0 and atomos[-l - 1][4] for l in expl):
            continue                                    # la cláusula contiene una unidad: siempre cierta
        t = sum(bit[-l - 1] for l in expl if l < 0)     # cláusula: alguno de estos libres cierto...
        f = sum(bit[l - 1] for l in expl if l > 0 and not atomos[l - 1][4])  # ...o alguno de estos falso
        aprendidas.append((t, f))

tres = [("A", 2), ("B", 3), ("C", 1)]
cuatro = tres + [("D", 2)]
for nombre, tareas, prec, Hs in (("3 tareas, A antes que C", tres, [("A", "C")], (5, 6)),
                                 ("4 tareas", cuatro, [], (7, 8))):
    for H in Hs:
        atomos, pares = planificacion(tareas, H, prec)
        r1, v1, modelo = bucle_perezoso(atomos, pares, "min")
        r2, v2, _ = bucle_perezoso(atomos, pares, "full")
        print(f"{nombre}, H = {H}: {r1}; vueltas con el ciclo: {v1:3d}, con la asignación completa: {v2:3d}")
        if modelo:
            print("   modelo:", {t: modelo[t] for t, _ in tareas})

Notice minimal explanations: several of the 8 rounds end in conflicts such as “C<BC < B and B<CB < C”, stating the obvious (two tasks cannot each precede the other). SAT discovers them one by one because it knows no arithmetic. If, upon SAT setting “B<CB < C” true, theory immediately reported that “C<BC < B” must be false, those conflicts would not arise. This is theory propagation. Together with checking theory during search rather than only on complete assignments, it distinguishes offline looping from DPLL(T).

DPLL(T): SAT and theory inside the same loop

Nieuwenhuis, Oliveras and Tinelli formalize DPLL(T) as transitions over states M∥FM \parallel F (trail MM and formula FF), reproducing abstract CDCL rules (propagate, decide, fail, backjump, learn, forget, restart) and adding theory rules. Three defining DPLL(T):

  • T-Propagate: if M⊨TℓM \models_T \ell for unassigned literal ℓ\ell of FF, add ℓ\ell to the trail.
  • T-Learn: if ℓ1∨⋯∨ℓk\ell_1 \lor \dots \lor \ell_k is TT-valid (and its atoms lie in FF or MM), add it to FF.
  • T-Forget: remove a learned TT-valid clause.

The central correctness result: if SolverT\mathrm{Solver}_T decides TT-consistency of literal conjunctions, executions meeting fairness conditions (not restarting or forgetting indefinitely without progress) terminate, reaching failure only if FF is TT-unsatisfiable, or otherwise a TT-consistent trail satisfying FF.

Proof

For the offline loop a three-line proof contains the idea. Unsat soundness: each learned clause negates a TT-inconsistent conjunction, so is TT-valid and adding it does not change the formula’s TT-models. If the abstraction plus learned clauses has no Boolean model, the original has no TT-model, because a TT-model would evaluate atoms to a Boolean abstraction model satisfying every TT-valid clause. Sat soundness: if theory accepts an assignment, its model makes exactly those literals true and thus satisfies abstraction and formula. Termination: each learned clause is false under the proposed assignment, preventing its return; there are 2n2^n assignments. Full DPLL(T) terminates by the CDCL argument: each backjump yields a lexicographically greater trail in a well-founded order, and theory rules add only literals or TT-valid clauses.

∎

Requirements for a theory solver

Dutertre and de Moura (2006) describe the interface CDCL expects, implemented in the lab:

  • Assert(ℓ\ell) adds a literal. It must be sound but may be incomplete: it may accept a literal even when the set is already inconsistent if detection is expensive.
  • Check() decides current-state consistency and must be sound and complete. Multiple literals can therefore be asserted before one check.
  • Backtrack() returns to the last checkpoint, forgetting later asserted literals.
  • Optional Propagate() returns implied literals (possibly not all).
  • To communicate with CDCL, the solver must explain each conflict and propagated literal.

Explanations fit 1-UIP conflict analysis. A theory conflict with explanation EE is treated as if clause ⋁ℓ∈E¬ℓ\bigvee_{\ell \in E} \neg\ell existed and became false: resolve backward to the first UIP and use nonchronological backjumping. Theory propagation of ℓ\ell with explanation EE enters the implication graph with reason clause ℓ∨⋁e∈E¬e\ell \lor \bigvee_{e \in E} \neg e, like unit propagation. Serious solvers generate such reasons lazily, only when conflict analysis asks, since most propagations never participate in conflict.

Two practical consequences:

  • Explanations should be small. This accounts for 38 versus 729 rounds. Finding a minimal explanation can be expensive; solvers accept small explanations obtained cheaply from the algorithm (a cycle, simplex row, proof-forest path).
  • Theory must backtrack cheaply. CDCL backtracks thousands of times per second. A theory solver rebuilding state each time is unusable. Difference logic and simplex backtrack without recomputation; for congruence closure, solvers log merges and undo them in reverse (often giving up path compression, expensive to undo; this lesson’s non-backtracking solvers use it).

Equality and uninterpreted functions: congruence closure

A set of equalities si=tis_i = t_i and inequalities uj≠vju_j \neq v_j between EUF terms is satisfiable iff no inequality joins terms forced equal by the equalities. Compute the smallest equivalence relation over subterms containing the equalities and closed under congruence.

Proof

In a model, “have equal value” contains EE, is an equivalence and is congruence-closed (functions are functions), so contains the smallest such relation ∼\sim; if uj∼vju_j \sim v_j their values agree and the inequality is false. Conversely, if no inequality joins equivalent terms, construct a model with one element per class: universe T/ ⁣∼\mathcal{T}/\!\sim, each term interpreted as its class, and f([s1],…,[sk])=[f(t1,…,tk)]f([s_1], \dots, [s_k]) = [f(t_1, \dots, t_k)] if some f(t1,…,tk)∈Tf(t_1, \dots, t_k) \in \mathcal{T} has ti∼sit_i \sim s_i (any class otherwise). This is well-defined exactly because ∼\sim is congruence-closed: two T\mathcal{T} applications with equivalent arguments share a class. By induction each t∈Tt \in \mathcal{T} evaluates to its class [t][t], so the model satisfies EE and, since [uj]≠[vj][u_j] \neq [v_j], the inequalities.

∎

The algorithm is union-find with union by rank and path compression, plus two indices:

  1. Each class has a use list: applications with some argument in that class.
  2. A signature table: application f(t1,…,tk)f(t_1, \dots, t_k) has signature (f,find(t1),…,find(tk))(f, \mathrm{find}(t_1), \dots, \mathrm{find}(t_k)). Applications with the same signature are congruent.

To process s=ts = t, merge distinct classes; applications on the absorbed class’s use list change signature, and any matching an existing signature enqueue a new equality. Always merging the smaller class into the larger gives Downey, Sethi and Tarjan’s O(nlog⁡n)\bigO(n \log n) bound, since each term changes class at most log⁡2n\log_2 n times.

InteractiveCongruence closure
af(a)f²(a)f³(a)f⁴(a)f⁵(a)
  • same class, same color
  • proof: input equality
  • proof: congruence
  • disequality terms
Merges, in order
1. f³(a) = a (input e1)
2. f(a) = f⁴(a) (congruence: arguments of f(a) and f⁴(a) already equal)
3. f²(a) = f⁵(a) (congruence: arguments of f²(a) and f⁵(a) already equal)
Input equalities
Disequality: f(a) ≠ a
Equivalence classes3 (of 6 terms)
Merges: input · congruence1 · 2
Consistent: f(a) and a are in different classes. A model has one element per class.
Each application points to its arguments. Add input equalities in any order: union-find classes share a color and congruence merges rise through the graph. Dashed arcs are the proof forest, which yields an explanation when an inequality falls inside a class. In the first problem f³(a) = a alone does not cause conflict: why is f⁵(a) = a also needed? In the second, does e1 participate in the explanation? What explanation results if you reach conflict with e4 and e5 instead of e3?

The first problem is Nelson and Oppen’s classical congruence-closure example (1980). With f3(a)=af^3(a) = a, congruence gives f4(a)=f(a)f^4(a) = f(a) and f5(a)=f2(a)f^5(a) = f^2(a) but there remain three classes, {a,f3(a)}\{a, f^3(a)\}, {f(a),f4(a)}\{f(a), f^4(a)\} and {f2(a),f5(a)}\{f^2(a), f^5(a)\}: a three-element model cyclically permuted by ff satisfies f3(a)=af^3(a) = a and f(a)≠af(a) \neq a. Adding f5(a)=af^5(a) = a merges the class of f2(a)f^2(a) with aa‘s, and congruence pulls in f3(a)=f(a)f^3(a) = f(a): everything collapses into one class and inequality f(a)≠af(a) \neq a conflicts, explained by both equalities.

Explanations: the proof forest

A theory solver’s congruence closure must explain why terms share a class. Union-find cannot: path compression and union by rank erase history. Nieuwenhuis and Oliveras (2007) separately maintain a proof forest: an undirected term graph with one edge per merge labeled by its reason (an input equality or congruence between specific applications). Merging classes of ss and tt reverses the path from ss to its root so ss becomes its tree root, then adds edge s→ts \to t. Edges are never compressed, so terms in a class have a unique path. To explain s=ts = t:

  1. Find the common ancestor of ss and tt in the forest and traverse both paths.
  2. Each input edge contributes its equality.
  3. Each congruence edge between f(s1,…,sk)f(s_1, \dots, s_k) and f(t1,…,tk)f(t_1, \dots, t_k) generates subproblems si=tis_i = t_i, explained recursively.

The result is correct (input equalities implying s=ts = t) and usually small, but history-dependent. In the figure’s second problem, reaching conflict via e4 (a=ca = c) and e5 (b=cb = c) yields explanation {e2,e4,e5}\{e_2, e_4, e_5\}, even after adding e3 (a=ba = b), for which {e2,e3}\{e_2, e_3\} would suffice: e3 arrives when aa and bb already share a class, creates no merge and leaves no forest edge. Input equalities ignored by the explanation (e1 here) occur on no traversed path. The lab implements exactly this.

Lab 1: explaining congruence closure

The implementation follows that scheme: terms as strings (constants) or tuples (f, arg1, ..., argk), ranked and compressed union-find, use lists, signature table and proof forest. The first test is the figure example.

[ ]Congruence closure with a proof forestBrowser
class Congruencia:
    """Cierre por congruencia con union-find (rango + compresión de caminos), listas de uso y bosque de pruebas.
    Términos: cadenas (constantes) o tuplas (f, arg1, ..., argk)."""

    def __init__(self):
        self.id, self.term = {}, []
        self.padre, self.rango = [], []
        self.miembros, self.usos = [], []        # por representante: miembros de la clase y aplicaciones que la usan
        self.firma = {}                          # (f, rep(arg1), ..., rep(argk)) -> nodo
        self.prueba, self.razon = [], []         # bosque de pruebas: arista hacia el padre y su razón
        self.pendiente = []

    def nodo(self, t):
        if t in self.id:
            return self.id[t]
        args = [self.nodo(a) for a in t[1:]] if isinstance(t, tuple) else []
        i = len(self.term)
        self.id[t] = i; self.term.append(t)
        self.padre.append(i); self.rango.append(0); self.miembros.append([i]); self.usos.append([])
        self.prueba.append(None); self.razon.append(None)
        if args:
            for a in set(self.find(a) for a in args):
                self.usos[a].append(i)
            clave = (t[0],) + tuple(self.find(a) for a in args)
            if clave in self.firma:              # congruente con un nodo ya existente
                self.pendiente.append((i, self.firma[clave], ("cong", i, self.firma[clave])))
                self._procesa()
            else:
                self.firma[clave] = i
        return i

    def find(self, i):
        r = i
        while self.padre[r] != r:
            r = self.padre[r]
        while self.padre[i] != r:
            self.padre[i], i = r, self.padre[i]
        return r

    def _args(self, i):
        t = self.term[i]
        return [self.id[a] for a in t[1:]] if isinstance(t, tuple) else []

    def igual(self, s, t, etiqueta):
        a, b = self.nodo(s), self.nodo(t)
        self.pendiente.append((a, b, ("entrada", etiqueta)))
        self._procesa()

    def _procesa(self):
        while self.pendiente:
            a, b, razon = self.pendiente.pop()
            ra, rb = self.find(a), self.find(b)
            if ra == rb:
                continue
            self._enraiza(a); self.prueba[a], self.razon[a] = b, razon
            if self.rango[ra] > self.rango[rb]:
                ra, rb = rb, ra                  # ra (la de menor rango) se cuelga de rb
            self.padre[ra] = rb
            self.rango[rb] += self.rango[ra] == self.rango[rb]
            self.miembros[rb] += self.miembros[ra]
            for u in self.usos[ra]:              # las aplicaciones que usaban ra cambian de firma
                clave = (self.term[u][0],) + tuple(self.find(x) for x in self._args(u))
                if clave in self.firma and self.find(self.firma[clave]) != self.find(u):
                    v = self.firma[clave]
                    self.pendiente.append((u, v, ("cong", u, v)))
                else:
                    self.firma[clave] = u
                self.usos[rb].append(u)

    def _enraiza(self, x):
        """Invierte el camino de x a su raíz en el bosque de pruebas: x pasa a ser raíz."""
        previo, razon_previa = None, None
        while x is not None:
            sig, r = self.prueba[x], self.razon[x]
            self.prueba[x], self.razon[x] = previo, razon_previa
            previo, razon_previa, x = x, r, sig

    def explica(self, s, t):
        """Conjunto de etiquetas de igualdades de entrada que implican s = t (None si no se deduce)."""
        a, b = self.nodo(s), self.nodo(t)
        if self.find(a) != self.find(b):
            return None
        usadas, hecho, tareas = set(), set(), [(a, b)]
        while tareas:
            x, y = tareas.pop()
            anc = []
            z = x
            while z is not None:
                anc.append(z); z = self.prueba[z]
            z = y
            while z not in anc:
                z = self.prueba[z]
            comun = z
            for z in (x, y):
                while z != comun:
                    if z not in hecho:
                        hecho.add(z)
                        r = self.razon[z]
                        if r[0] == "entrada":
                            usadas.add(r[1])
                        else:
                            tareas += list(zip(self._args(r[1]), self._args(r[2])))
                    z = self.prueba[z]
        return usadas

# Comprobación: el ejemplo clásico f³(a) = a, f⁵(a) = a  ⊢  f(a) = a
def f(t, n=1):
    for _ in range(n): t = ("f", t)
    return t
cc = Congruencia()
for k in range(6): cc.nodo(f("a", k))
cc.igual(f("a", 3), "a", "e1")
print("tras e1: ¿f(a) = a?", cc.explica(f("a"), "a"), "  ¿f⁴(a) = f(a)?", sorted(cc.explica(f("a", 4), f("a"))))
cc.igual(f("a", 5), "a", "e2")
print("tras e2: ¿f(a) = a?", sorted(cc.explica(f("a"), "a")))

After e1, f(a)=af(a) = a is not deduced (returns None), and f4(a)=f(a)f^4(a) = f(a) is explained by e1 alone; after e2, f(a)=af(a) = a needs both.

A real application: translation validation (Pnueli, Siegel and Singerman, 1998; Necula, 2000). Rather than prove an optimizer correct for every program, check each translation: convert source and optimized programs in SSA form into equalities, leave operators uninterpreted, and ask whether outputs are equal. Rewrites below are common-subexpression elimination (CSE) applied once and twice, a buggy rewrite, and one using addition commutativity.

[ ]Validating toy compiler rewritesBrowser
# Validación de traducciones: dos cadenas de reescrituras de un compilador de juguete.
# Un programa es una lista de asignaciones en SSA (cada variable se asigna una vez); los operadores son
# funciones NO interpretadas: no sabemos nada de mul ni de add salvo que son funciones.
def ecuaciones(prog, sufijo):
    """Cada asignación v = op(a, b) da la igualdad v_sufijo = op(a', b'); las entradas son comunes."""
    nombre = lambda x: x if x in ENTRADAS else f"{x}{sufijo}"
    eqs = []
    for v, (op, *args) in prog:
        rhs = nombre(args[0]) if op == "copia" else (op, *[nombre(a) for a in args])
        eqs.append((nombre(v), rhs, f"{v}{sufijo}"))
    return eqs

ENTRADAS = {"a", "b", "c"}
fuente = [("t1", ("mul", "a", "b")), ("t2", ("mul", "a", "b")), ("t3", ("add", "t1", "c")),
          ("t4", ("add", "t2", "c")), ("r", ("sub", "t3", "t4"))]
# reescritura 1: eliminación de subexpresiones comunes (t2 := t1) y propagación de copias
cse = [("t1", ("mul", "a", "b")), ("t3", ("add", "t1", "c")), ("t4", ("add", "t1", "c")), ("r", ("sub", "t3", "t4"))]
# reescritura 2: otra vez CSE (t4 := t3)
cse2 = [("t1", ("mul", "a", "b")), ("t3", ("add", "t1", "c")), ("r", ("sub", "t3", "t3"))]
# una reescritura con un error: confunde b con c en la segunda multiplicación
mala = [("t1", ("mul", "a", "b")), ("t3", ("add", "t1", "c")), ("t4", ("add", ("mul", "a", "c"), "c")),
        ("r", ("sub", "t3", "t4"))]
# una correcta que EUF no puede justificar: usa que add es conmutativa
conm = [("t1", ("mul", "a", "b")), ("t3", ("add", "c", "t1")), ("r", ("sub", "t3", "t3"))]

def plano(prog):
    """Las subexpresiones anidadas se nombran con temporales nuevos (el programa queda en forma plana)."""
    out, n = [], 0
    def sube(e):
        nonlocal n
        if isinstance(e, tuple):
            n += 1; v = f"_k{n}"; out.append((v, (e[0], *[sube(a) for a in e[1:]]))); return v
        return e
    for v, (op, *args) in prog:
        out.append((v, (op, *[sube(a) for a in args])))
    return out

def equivalentes(p, q):
    cc = Congruencia()
    for x, y, et in ecuaciones(plano(p), "_p") + ecuaciones(plano(q), "_q"):
        cc.igual(x, y, et)
    return cc.explica("r_p", "r_q"), cc

OPS = {"mul": lambda x, y: x * y, "add": lambda x, y: x + y, "sub": lambda x, y: x - y}
def evalua(prog, entrada):
    env = dict(entrada)
    for v, (op, *args) in plano(prog):
        env[v] = OPS[op](*[env[a] for a in args])
    return env["r"]

punto = {"a": 3, "b": 5, "c": 7}
for nombre, q in (("CSE", cse), ("CSE dos veces", cse2), ("con error", mala), ("conmutatividad", conm)):
    expl, cc = equivalentes(fuente, q)
    if expl is None:
        print(f"{nombre:15s}: r_fuente = r_optimizado NO se deduce en EUF ({len(set(map(cc.find, range(len(cc.term))))):d} clases); "
              f"con la aritmética de verdad en {punto}: fuente {evalua(fuente, punto)}, optimizado {evalua(q, punto)}")
    else:
        print(f"{nombre:15s}: equivalentes; la prueba usa {len(expl)} de las {len(fuente) + len(plano(q))} definiciones: {sorted(expl)}")

The four cases show what abstraction gives and loses. Both CSE rewrites validate using all definitions. The buggy rewrite fails validation, and evaluation on actual numbers confirms it is wrong (source gives 0, optimized version −6). The rewrite commuting add also fails validation, but both versions give 0: a false alarm. EUF does not know addition is commutative; “not implied” means “not implied by operators being functions”, not “different”. To validate this rewrite give the solver more theory, e.g. integer arithmetic; lab 3 shows Z3 succeeds once operators are interpreted.

Difference logic: conflicts are negative cycles

Many scheduling, circuit-timing and timed-system verification problems use only constraints of the form “xx cannot exceed yy by more than cc”.

Edge direction is not arbitrary: using distances, the constraint says d(x)≤d(y)+cd(x) \le d(y) + c, the triangle inequality for edge y→xy \to x. Summing constraints around a cycle cancels variables pairwise and leaves 0≤0 \le cycle weight. Therefore:

The guided exercise proves this. Two consequences matter for DPLL(T):

  • Free minimal explanations. Edges of a simple negative cycle form a minimal inconsistent set: remove any and the rest is an acyclic path, with no negative cycle. Bellman–Ford finds one by following predecessors from the last relaxed vertex.
  • Models translate. If x↦v(x)x \mapsto v(x) is a model, so is x↦v(x)+kx \mapsto v(x) + k, since only differences occur. Thus origin z=0z = 0 can be fixed at the end.
InteractiveDifference constraints as a graph
3−204−141x₁d = −3x₂d = −1x₃d = −3x₄d = 0
  • selected constraint
  • negative cycle (explanation)
  • d(x): distance from virtual source
−2
x₃ − x₂ ≤ −2 is edge x₂ → x₃ with weight −2: “x₃ does not exceed x₂ by more than −2”.
Model (distances from the virtual source): x₁ = −3, x₂ = −1, x₃ = −3, x₄ = 0
The same shifted model (x₁ = 0): x₁ = 0, x₂ = 2, x₃ = 0, x₄ = 3
Simple-cycle weights: x₁→x₂→x₃→x₁: 1; x₁→x₂→x₃→x₄→x₁: 6; x₁→x₄→x₂→x₃→x₁: 1; x₁→x₄→x₁: 5; x₂→x₃→x₄→x₂: 1
Satisfiable: no cycle weighs less than 0, and x = d(x) satisfies all 7 constraints because d(x) ≤ d(y) + c on every edge.
Each constraint xᵢ − xⱼ ≤ c is an edge xⱼ → xᵢ of weight c. Initially all five simple cycles weigh at least 1 and virtual-source distances form a model. Lower r2's constant: at what value does conflict appear, and why does it affect three cycles at once? Also lower r3, which lies in only two.

Initially the five simple cycles weigh 1, 1, 1, 5 and 6; virtual-source distances are (x1,x2,x3,x4)=(−3,−1,−3,0)(x_1, x_2, x_3, x_4) = (-3, -1, -3, 0), translated so x1=0x_1 = 0 to yield (0,2,0,3)(0, 2, 0, 3): check each constraint. Edge r2 (x2→x3x_2 \to x_3, weight −2-2) lies in four of five cycles, three of weight 1, so lowering it to −4-4 makes three cycles weigh −1-1; Bellman–Ford returns one.

An incremental solver

DPLL(T) cannot run Bellman–Ford from scratch at every query. The lab solver maintains a potential π\pi, a model of active constraints, and upon adding edge u→vu \to v of weight ww:

  1. If π(u)+w≥π(v)\pi(u) + w \ge \pi(v), the edge already holds and nothing is needed.
  2. Otherwise lower π(v)\pi(v) to π(u)+w\pi(u) + w and propagate the decrease to successors, as Bellman–Ford but only in the affected region.
  3. If propagation lowers π(u)\pi(u), the repair path from vv to uu closed by the new edge is a negative cycle: undo π\pi changes and return the cycle as explanation.

Backtracking is trivial: remove edges and leave π\pi unchanged, because a model of constraints also models any subset. This makes simplex backtracking cheap too. For theory propagation, adding u→vu \to v triggers Dijkstra distances to uu and from vv (using reduced costs π(a)+w−π(b)≥0\pi(a) + w - \pi(b) \ge 0, nonnegative because π\pi is a model): a free atom x−y≤cx - y \le c follows if δ(y,u)+w+δ(v,x)≤c\delta(y, u) + w + \delta(v, x) \le c, explained by that path. This simplifies Cotton and Maler’s propagation (2006).

Lab 2: DPLL(T) for difference logic

First the engine: compact CDCL (watches, 1-UIP, backjumping, activity and saved phase as before) with a theory hook, plus the incremental difference solver with explanations and propagation. Finally the dialogue figure’s tasks.

[ ]CDCL with a difference-logic theory solverBrowser
import time, heapq

class CDCL:
    """CDCL compacto: vigilados, 1-UIP, backjumping, actividad tipo VSIDS y fase guardada.
    Opcionalmente dialoga con un solver de teoría (DPLL(T)): ver el método _teoria."""

    def __init__(self, nvars, clauses, theory=None):
        self.n = nvars
        self.val = [0] * (nvars + 1)          # 1, -1 o 0
        self.level = [0] * (nvars + 1)
        self.reason = [None] * (nvars + 1)    # índice de cláusula o None (decisión)
        self.act = [0.0] * (nvars + 1)
        self.phase = [-1] * (nvars + 1)
        self.inc = 1.0
        self.trail, self.lim = [], []
        self.clauses, self.watch = [], {}
        self.qhead = 0
        self.th, self.thead = theory, 0       # el solver de teoría ve el trail a partir de thead
        self.stats = dict(conflicts=0, decisions=0, props=0, t_conflicts=0, t_props=0)
        self.ok = True
        for c in clauses:
            if not self.add_clause(list(c)):
                self.ok = False

    def value(self, l):
        v = self.val[abs(l)]
        return v if l > 0 else -v

    def add_clause(self, c, learnt=False):
        c = list(dict.fromkeys(c))
        if not learnt and any(-l in c for l in c):
            return True                         # tautología
        if len(c) == 0:
            return False
        if len(c) == 1:
            if self.value(c[0]) == -1:
                return False
            if self.value(c[0]) == 0:
                self.enqueue(c[0], None)
            return True
        i = len(self.clauses)
        self.clauses.append(c)
        self.watch.setdefault(c[0], []).append(i)
        self.watch.setdefault(c[1], []).append(i)
        return True

    def enqueue(self, l, reason):
        v = abs(l)
        self.val[v] = 1 if l > 0 else -1
        self.level[v] = len(self.lim)
        self.reason[v] = reason
        self.trail.append(l)

    def propagate(self):
        while self.qhead < len(self.trail):
            l = self.trail[self.qhead]; self.qhead += 1
            fl = -l                              # literal que acaba de hacerse falso
            ws = self.watch.get(fl, [])
            keep = []
            i = 0
            while i < len(ws):
                ci = ws[i]; i += 1
                c = self.clauses[ci]
                if c[0] == fl:
                    c[0], c[1] = c[1], c[0]
                if self.value(c[0]) == 1:
                    keep.append(ci); continue
                for k in range(2, len(c)):
                    if self.value(c[k]) != -1:
                        c[1], c[k] = c[k], c[1]
                        self.watch.setdefault(c[1], []).append(ci)
                        break
                else:
                    keep.append(ci)
                    if self.value(c[0]) == -1:   # conflicto
                        keep.extend(ws[i:])
                        self.watch[fl] = keep
                        return ci
                    self.enqueue(c[0], ci); self.stats['props'] += 1
            self.watch[fl] = keep
        return None

    def analyze(self, confl):
        seen = set(); learnt = [None]; cnt = 0
        lits = self.clauses[confl]
        idx = len(self.trail) - 1
        cur = len(self.lim)
        p = None
        while True:
            for q in (lits if p is None else lits[1:]):
                v = abs(q)
                if v not in seen and self.level[v] > 0:
                    seen.add(v)
                    self.act[v] += self.inc
                    if self.level[v] == cur:
                        cnt += 1
                    else:
                        learnt.append(q)
            while abs(self.trail[idx]) not in seen:
                idx -= 1
            p = self.trail[idx]; idx -= 1
            seen.discard(abs(p)); cnt -= 1
            if cnt == 0:
                break
            lits = self.clauses[self.reason[abs(p)]]
            # la razón tiene el literal propagado en la posición 0
            if lits[0] != p:
                j = lits.index(p); lits[0], lits[j] = lits[j], lits[0]
        learnt[0] = -p
        self.inc *= 1.05
        bt = 0
        if len(learnt) > 1:
            j = max(range(1, len(learnt)), key=lambda k: self.level[abs(learnt[k])])
            learnt[1], learnt[j] = learnt[j], learnt[1]
            bt = self.level[abs(learnt[1])]
        return learnt, bt

    def backjump(self, lvl):
        if len(self.lim) <= lvl:
            return
        start = self.lim[lvl]
        for l in self.trail[start:]:
            v = abs(l); self.phase[v] = self.val[v]; self.val[v] = 0; self.reason[v] = None
        del self.trail[start:]; del self.lim[lvl:]
        self.qhead = min(self.qhead, start)
        if self.th is not None and self.thead > start:
            self.th.backtrack(start)            # la teoría olvida lo que vio más allá de start
            self.thead = start

    def _teoria(self):
        """Pasa a la teoría los literales nuevos del trail. Devuelve el índice de una cláusula
        de conflicto (explicación), o None. Las propagaciones de teoría entran como cláusulas razón."""
        while self.thead < len(self.trail):
            l = self.trail[self.thead]; self.thead += 1
            expl = self.th.assert_lit(l, self.thead)
            if expl is not None:                 # conflicto: los literales de expl son todos ciertos
                self.stats['t_conflicts'] += 1
                c = [-e for e in expl]
                c.sort(key=lambda q: -self.level[abs(q)])
                return self._add_reason(c)
        for l, expl in self.th.implied(self.value):
            if self.value(l) == 0:
                self.stats['t_props'] += 1
                ci = self._add_reason([l] + [-e for e in expl])
                self.enqueue(l, ci)
        return None

    def _add_reason(self, c):
        i = len(self.clauses); self.clauses.append(c)
        if len(c) >= 2:
            self.watch.setdefault(c[0], []).append(i); self.watch.setdefault(c[1], []).append(i)
        return i

    def solve(self, budget=200000):
        if not self.ok:
            return False
        while True:
            confl = self.propagate()
            if confl is None and self.th is not None:
                confl = self._teoria()
                if confl is None and self.qhead < len(self.trail):
                    continue                     # la teoría ha propagado: vuelve a BCP
            if confl is not None:
                self.stats['conflicts'] += 1
                if not self.lim:
                    return False
                learnt, bt = self.analyze(confl)
                self.backjump(bt)
                if len(learnt) == 1:
                    self.enqueue(learnt[0], None)
                else:
                    ci = self._add_reason(learnt)
                    self.enqueue(learnt[0], ci)
                if self.stats['conflicts'] > budget:
                    return None
                continue
            free = [v for v in range(1, self.n + 1) if self.val[v] == 0]
            if not free:
                return True
            v = max(free, key=lambda u: self.act[u])
            self.stats['decisions'] += 1
            self.lim.append(len(self.trail))
            self.enqueue(v if self.phase[v] > 0 else -v, None)


class DiffLogic:
    """Solver de teoría incremental para lógica de diferencias entera.
    Átomo k: x - y <= c, arista y -> x de peso c. Su negación: y - x <= -c - 1.
    Mantiene un potencial pi factible (un modelo) y lo repara al añadir cada arista."""

    def __init__(self, atoms, propagate=True):
        self.atoms = atoms                       # atoms[k] = (x, y, c); variable booleana k + 1
        self.nodes = list(dict.fromkeys([a[0] for a in atoms] + [a[1] for a in atoms]))
        self.pi = {v: 0 for v in self.nodes}
        self.out = {v: [] for v in self.nodes}   # aristas activas: (destino, peso, literal)
        self.inn = {v: [] for v in self.nodes}
        self.stack = []                          # (posición en el trail, origen, destino)
        self.do_prop = propagate
        self.pending = []

    def edge(self, l):
        x, y, c = self.atoms[abs(l) - 1]
        return (y, x, c) if l > 0 else (x, y, -c - 1)

    def assert_lit(self, l, pos):
        u, v, w = self.edge(l)
        self.out[u].append((v, w, l)); self.inn[v].append((u, w, l)); self.stack.append((pos, u, v))
        if self.pi[u] + w < self.pi[v]:
            old = {v: self.pi[v]}; pred = {v: (u, l)}
            self.pi[v] = self.pi[u] + w
            queue = [v]
            while queue:
                a = queue.pop()
                for b, wb, lb in self.out[a]:
                    if self.pi[a] + wb < self.pi[b]:
                        if b == u:               # la reparación vuelve al origen: ciclo negativo
                            cyc = [l, lb]; z = a
                            while z != v:
                                z, lz = pred[z]; cyc.append(lz)
                            for k, val in old.items():
                                self.pi[k] = val # deshace la reparación a medias
                            return cyc
                        old.setdefault(b, self.pi[b])
                        self.pi[b] = self.pi[a] + wb; pred[b] = (a, lb)
                        queue.append(b)
        if self.do_prop:
            self._propagar(u, v, w, l)
        return None

    def _dijkstra(self, s, forward):
        # caminos mínimos con costes reducidos pi(a) + w - pi(b) >= 0 (no negativos)
        pi = self.pi; dist = {s: 0}; pred = {}; heap = [(0, 0, s)]; done = set(); n = 0
        adj = self.out if forward else self.inn
        while heap:
            d, _, a = heapq.heappop(heap)
            if a in done:
                continue
            done.add(a)
            for b, w, l in adj[a]:
                rc = (pi[a] + w - pi[b]) if forward else (pi[b] + w - pi[a])
                if b not in dist or d + rc < dist[b]:
                    dist[b] = d + rc; pred[b] = (a, l); n += 1; heapq.heappush(heap, (dist[b], n, b))
        # deshace la reducción: distancia real entre s y b
        real = {b: (d - pi[s] + pi[b]) if forward else (d - pi[b] + pi[s]) for b, d in dist.items()}
        return real, pred

    def _camino(self, pred, s, t):
        path = []
        while t != s:
            t, l = pred[t]; path.append(l)
        return path

    def _propagar(self, u, v, w, l):
        """Átomos implicados por un camino que usa la arista nueva u -> v."""
        hacia_u, pu = self._dijkstra(u, False)   # dist(a, u) para cada a
        desde_v, pv = self._dijkstra(v, True)    # dist(v, b) para cada b
        for k, (x, y, c) in enumerate(self.atoms):
            # x - y <= c es consecuencia si dist(y, x) <= c; su negación, si dist(x, y) <= -c - 1
            for lit, a, b, bound in ((k + 1, y, x, c), (-(k + 1), x, y, -c - 1)):
                if a in hacia_u and b in desde_v and hacia_u[a] + w + desde_v[b] <= bound:
                    expl = self._camino(pu, u, a) + [l] + self._camino(pv, v, b)
                    self.pending.append((lit, expl)); break

    def implied(self, value):
        res = [(lit, e) for lit, e in self.pending if value(lit) == 0]
        self.pending = []
        return res

    def backtrack(self, pos):
        self.pending = []
        while self.stack and self.stack[-1][0] > pos:
            _, u, v = self.stack.pop(); self.out[u].pop(); self.inn[v].pop()
        # pi sigue siendo un modelo de las aristas que quedan: no hay nada más que deshacer

    def model(self):
        return dict(self.pi)
# Prueba: las tareas de la figura del diálogo, ahora con CDCL + teoría incremental
for H in (5, 6):
    atomos, pares = planificacion(tres, H, [("A", "C")])
    clausulas = [[k + 1] for k, a in enumerate(atomos) if a[4]] + [[p + 1, q + 1] for p, q in pares]
    for prop in (False, True):
        th = DiffLogic([a[:3] for a in atomos], propagate=prop)
        s = CDCL(len(atomos), clausulas, theory=th)
        r = s.solve()
        modelo = {t: th.pi[t] - th.pi["z"] for t, _ in tres} if r else None
        print(f"H = {H}, propagación de teoría {'sí' if prop else 'no'}: {'sat' if r else 'unsat'}; "
              f"conflictos {s.stats['conflicts']} (de teoría {s.stats['t_conflicts']}), "
              f"propagaciones de teoría {s.stats['t_props']}, decisiones {s.stats['decisions']}; modelo {modelo}")

With theory propagation, case H=5H = 5 solves without a single decision: unit clauses (deadlines and A-before-C) let theory deduce 4 orders and reach level-0 conflict. Without propagation it takes 4 decisions and 5 theory conflicts. With H=6H = 6, the potential’s schedule (BB at 0, AA at 3, CC at 5) meets precedence and deadline.

Now a real problem: a random job shop of 5 jobs and 5 machines, durations 1 to 9. Each job visits machines in order and operations on a machine cannot overlap. Can everything finish before MM? Within-job precedences are units; each pair of operations on one machine gives a disjunction of two difference atoms: 150 atoms total. Independently, the same CDCL solves the order encoding of the same problem from lesson 11, using variables [s≤t][s \le t] for each time tt.

[ ]A job shop: optimal makespan with DPLL(T) and order encodingBrowser
import itertools, random, time
def jobshop(n_jobs, n_mach, seed, dmax=9):
    rnd = random.Random(seed)
    jobs = []
    for j in range(n_jobs):
        orden = list(range(n_mach)); rnd.shuffle(orden)
        jobs.append([(m, rnd.randint(1, dmax)) for m in orden])
    return jobs

def escalar(jobs, k):
    return [[(m, d * k) for m, d in job] for job in jobs]

def codifica_dl(jobs, M):
    """Átomos x - y <= c sobre los inicios s_jk y el origen z. Devuelve (átomos, cláusulas)."""
    atoms, clauses = [], []
    def atom(x, y, c):
        atoms.append((x, y, c)); return len(atoms)
    ops = {}
    for j, job in enumerate(jobs):
        for k, (m, d) in enumerate(job):
            ops[(j, k)] = (m, d)
            clauses.append([atom('z', (j, k), 0)])                  # s >= 0
            if k + 1 < len(job):
                clauses.append([atom((j, k), (j, k + 1), -d)])      # precedencia en el trabajo
        k = len(job) - 1
        clauses.append([atom((j, k), 'z', M - job[k][1])])          # termina antes de M
    por_maquina = {}
    for o, (m, d) in ops.items():
        por_maquina.setdefault(m, []).append(o)
    for m, lst in por_maquina.items():
        for a, b in itertools.combinations(lst, 2):
            da, db = ops[a][1], ops[b][1]
            clauses.append([atom(a, b, -da), atom(b, a, -db)])      # a antes que b, o b antes que a
    return atoms, clauses

def resuelve_dl(jobs, M, propagar=True):
    atoms, clauses = codifica_dl(jobs, M)
    th = DiffLogic(atoms, propagate=propagar)
    s = CDCL(len(atoms), clauses, theory=th)
    t0 = time.perf_counter(); r = s.solve(); t = time.perf_counter() - t0
    modelo = None
    if r:
        pi = th.model(); modelo = {o: pi[o] - pi['z'] for o in th.nodes if o != 'z'}
    return r, s, t, modelo, len(atoms), len(s.clauses)

def codifica_orden(jobs, M):
    """Codificación de orden: q[o][t] <=> s_o <= t, t = 0..H-1 con H = M - d_o (s_o <= H siempre)."""
    nv = 0; clauses = []
    def var():
        nonlocal nv; nv += 1; return nv
    ops = {}; q = {}
    for j, job in enumerate(jobs):
        for k, (m, d) in enumerate(job):
            ops[(j, k)] = (m, d)
    for o, (m, d) in ops.items():
        H = M - d
        if H < 0:
            return nv, [[]]
        q[o] = [var() for _ in range(H)]            # q[o][t] para t < H; s_o <= H se cumple siempre
        for t in range(H - 1):
            clauses.append([-q[o][t], q[o][t + 1]])  # s <= t  ->  s <= t + 1
    def le(o, t):    # literal de s_o <= t (True/False si es constante)
        H = M - ops[o][1]
        if t < 0: return False
        if t >= H: return True
        return q[o][t]
    def precede(a, b, sel=None):
        # s_b >= s_a + d_a   <=>  para todo t: s_b <= t  ->  s_a <= t - d_a
        da = ops[a][1]; Hb = M - ops[b][1]
        for t in range(-1, Hb + 1):
            lb, la = le(b, t), le(a, t - da)
            if lb is False or la is True:
                continue
            c = [] if sel is None else [-sel]
            if lb is not True: c.append(-lb)
            if la is not False: c.append(la)
            clauses.append(c)
    for j, job in enumerate(jobs):
        for k in range(len(job) - 1):
            precede((j, k), (j, k + 1))
    por_maquina = {}
    for o, (m, d) in ops.items():
        por_maquina.setdefault(m, []).append(o)
    for m, lst in por_maquina.items():
        for a, b in itertools.combinations(lst, 2):
            sel = var()
            precede(a, b, sel); precede(b, a, -sel)
    return nv, clauses

def resuelve_orden(jobs, M):
    nv, clauses = codifica_orden(jobs, M)
    s = CDCL(nv, clauses)
    t0 = time.perf_counter(); r = s.solve(); t = time.perf_counter() - t0
    return r, s, t, nv, len(clauses)

def valida(jobs, M, inicio):
    ok = all(v >= 0 for v in inicio.values())
    for j, job in enumerate(jobs):
        for k, (m, d) in enumerate(job):
            if k + 1 < len(job): ok &= inicio[(j, k + 1)] >= inicio[(j, k)] + d
        ok &= inicio[(j, len(job) - 1)] + job[-1][1] <= M
    ops = [(j, k) for j, job in enumerate(jobs) for k in range(len(job))]
    for a, b in itertools.combinations(ops, 2):
        (ma, da), (mb, db) = jobs[a[0]][a[1]], jobs[b[0]][b[1]]
        if ma == mb: ok &= inicio[b] >= inicio[a] + da or inicio[a] >= inicio[b] + db
    return ok

jobs = jobshop(5, 5, seed=2)
print("trabajos (máquina, duración):")
for j, job in enumerate(jobs): print(f"  J{j}: {job}")
cota = max(max(sum(d for _, d in job) for job in jobs),
           max(sum(d for job in jobs for m, d in job if m == mm) for mm in range(5)))
# búsqueda del makespan óptimo: subir desde la cota inferior hasta el primer M satisfacible
M = cota
while not resuelve_dl(jobs, M)[0]:
    M += 1
print(f"cota inferior trivial {cota}; makespan óptimo {M}")
for MM in (M - 1, M):
    for prop in (False, True):
        r, s, t, ini, na, nc = resuelve_dl(jobs, MM, prop)
        print(f"M = {MM}  DPLL(T) {'con' if prop else 'sin'} propagación de teoría: {'sat' if r else 'unsat'}"
              f"{' (calendario válido: ' + str(valida(jobs, MM, ini)) + ')' if r else ''}; "
              f"{na} átomos, conflictos {s.stats['conflicts']}, propagaciones de teoría {s.stats['t_props']}")
    r, s, t, nv, nc = resuelve_orden(jobs, MM)
    print(f"M = {MM}  codificación de orden, mismo CDCL: {'sat' if r else 'unsat'}; {nv} variables, {nc} cláusulas, "
          f"conflictos {s.stats['conflicts']}")

The encodings agree: 53 is unsatisfiable and 54 satisfiable, and the DPLL(T) schedule passes independent validation. Theory propagation reduces conflicts more than tenfold (55 to 5 at M=53M = 53 and 47 to 4 at M=54M = 54). Order encoding needs about 1200 variables and 7000 clauses versus 150 atoms because it has a variable per operation and time. With single-digit durations this is no penalty: it propagates as well as theory (5 conflicts at M=53M = 53) and in the next cell with k=1k = 1 is even faster than our Python DPLL(T). What if durations use units ten times finer?

[ ]Scaling durations: encoding sizesBrowser
import matplotlib.pyplot as plt
filas = []
for k in (1, 2, 4, 8):
    J = escalar(jobs, k)
    t0 = time.perf_counter(); r1, s1, _, _, na, _ = resuelve_dl(J, (M - 1) * k); t1 = time.perf_counter() - t0
    t0 = time.perf_counter(); r2, s2, _, nv, nc = resuelve_orden(J, (M - 1) * k); t2 = time.perf_counter() - t0
    filas.append((k, na, len(s1.clauses), t1, nv, nc, t2))
    print(f"duraciones x{k}: M = {(M - 1) * k} ({'sat' if r1 else 'unsat'}/{'sat' if r2 else 'unsat'})  "
          f"DPLL(T): {na} átomos, {s1.stats['conflicts']} conflictos, {t1:.3f} s  |  "
          f"orden: {nv} variables, {nc} cláusulas, {s2.stats['conflicts']} conflictos, {t2:.3f} s")
fig, ax = plt.subplots(1, 2, figsize=(9, 3.2))
ks = [f[0] for f in filas]
ax[0].plot(ks, [f[1] for f in filas], "o-", label="DPLL(T): átomos")
ax[0].plot(ks, [f[5] for f in filas], "s-", label="orden: cláusulas")
ax[0].set_xscale("log", base=2); ax[0].set_yscale("log"); ax[0].set_xlabel("factor de escala de las duraciones")
ax[0].set_title("Tamaño de la codificación"); ax[0].legend()
ax[1].plot(ks, [f[3] for f in filas], "o-", label="DPLL(T)")
ax[1].plot(ks, [f[6] for f in filas], "s-", label="orden (codificar y resolver)")
ax[1].set_xscale("log", base=2); ax[1].set_yscale("log"); ax[1].set_xlabel("factor de escala de las duraciones")
ax[1].set_title("Tiempo hasta probar M − 1 insatisfacible (s)"); ax[1].legend()
plt.tight_layout(); plt.show()

Multiplying every duration by kk (and deadline by kk) leaves the problem unchanged: DPLL(T) atoms and conflicts do not change and runtime barely moves. Order encoding grows linearly with kk in variables and clauses (at k=8k = 8 already about 55,000) and runtime grows at least as fast even with unchanged conflicts: size is the cost. This illustrates the lazy approach: theory treats constants as numbers, while Boolean encoding must represent them.

Linear arithmetic: general simplex

For general linear constraints ∑jajxj⋈c\sum_j a_j x_j \bowtie c, the decision procedure is linear-programming simplex adapted to DPLL(T): no objective (feasibility only), atoms arrive and leave thousands of times per second, and every conflict needs an explanation. Yices, Z3 and other modern solvers use Dutertre and de Moura’s (2006) version.

Since A\mat{A} is fixed, rows are never added or removed: asserting an atom changes a bound; backtracking restores previous bounds (saved on a stack) and the last assignment passing Check, which satisfies all earlier checkpoint bounds. No pivots. The paper contrasts this with classical incremental simplex, which added and removed rows and might need to pivot on backtracking.

Check repeats until no basic variable violates its bounds:

  1. Take the smallest basic xix_i (in a fixed total order) with β(xi)<ℓi\beta(x_i) < \ell_i or β(xi)>ui\beta(x_i) > u_i.
  2. If below, find the smallest nonbasic xjx_j in its row that can raise it: aij>0a_{ij} > 0 and β(xj)<uj\beta(x_j) < u_j, or aij<0a_{ij} < 0 and β(xj)>ℓj\beta(x_j) > \ell_j. If above, reverse directions.
  3. If none, conflict. Otherwise pivot xix_i with xjx_j and set xix_i to the violated bound.

Always choosing the smallest variable is Bland’s rule, guaranteeing no cycling and termination of Check.

The row supplies the explanation. If xix_i is below ℓi\ell_i and no nonbasic can raise it, each xjx_j with aij>0a_{ij} > 0 is at its upper bound and each with aij<0a_{ij} < 0 at its lower bound. Thus for any x\vb{x} with Ax=0\mat{A}\vb{x} = \vb{0} satisfying those bounds,

xi=∑aij>0aijxj+∑aij<0aijxj  ≤  ∑aij>0aijuj+∑aij<0aijℓj  =  β(xi)  <  ℓi,x_i = \sum_{a_{ij} > 0} a_{ij} x_j + \sum_{a_{ij} < 0} a_{ij} x_j \;\le\; \sum_{a_{ij} > 0} a_{ij} u_j + \sum_{a_{ij} < 0} a_{ij} \ell_j \;=\; \beta(x_i) \;<\; \ell_i,

so {xi≥ℓi}∪{xj≤uj:aij>0}∪{xj≥ℓj:aij<0}\{x_i \ge \ell_i\} \cup \{x_j \le u_j : a_{ij} > 0\} \cup \{x_j \ge \ell_j : a_{ij} < 0\} is inconsistent: a Farkas certificate read directly from the tableau.

InteractiveSimplex with bounds
  • b1
  • b2
  • b3
  • b4
  • asserted-bound region
  • assignment and its path
Tableau (nonbasic: x, y)
s₁ = x + y
s₂ = x − y
variablevaluelower boundupper bound
x0−∞+∞nonbasic
y0−∞+∞nonbasic
s₁0−∞6 (b1)basic
s₂01 (b2)+∞basic, violates
6
1
2
4
Asserted boundsb1, b2
Assignment (x, y)(0, 0)
Total pivots0
Just asserted b2: s₂ = 0 violates s₂ ≥ 1. Press “Check step”.
The fixed tableau is s₁ = x + y, s₂ = x − y. Initially b1 is asserted and checked and b2 has just been asserted: s₂ = 0 violates s₂ ≥ 1. Pivot and watch assignment (x, y) move. Assert b3 (a nonbasic bound: no pivot needed) and b4. Then backtrack: the tableau does not change. Finally backtrack to b1, lower it to 4 before reasserting, and repeat: which bounds form the explanation?

In the figure, pivoting from the initial state removes s2s_2 and introduces xx: tableau becomes x=s2+yx = s_2 + y, s1=s2+2ys_1 = s_2 + 2y, and assignment jumps to (1,0)(1, 0). Bound b3 (y≥2y \ge 2) moves nonbasic yy to 2 without pivoting, giving (3,2)(3, 2). With x+y≤4x + y \le 4 instead of 6, row s1=s2+2ys_1 = s_2 + 2y can no longer decrease: s2s_2 is at lower bound 1 and yy at its own, 2, so s1≥1+2⋅2=5>4s_1 \ge 1 + 2 \cdot 2 = 5 > 4; explanation {b1,b2,b3}\{b_1, b_2, b_3\}. Bound b4 does not participate despite being asserted.

What a real solver adds

  • Strict inequalities. Dutertre and de Moura leave the algorithm unchanged: replace x<cx < c by x≤c−δx \le c - \delta with symbolic infinitesimal δ>0\delta > 0. Bounds and values become lexicographically ordered pairs (c,k)(c, k) representing c+kδc + k\delta, and their Lemma 1 guarantees strict constraints are satisfiable iff the nonstrict ones are satisfiable for some sufficiently small rational δ\delta, computed at the end.
  • Theory propagation by bound refinement. A row and its nonbasic bounds imply bounds for its basic variable, propagating atoms such as s≤c′s \le c'. The authors credit cheap backtracking, preprocessing and propagation for improvements in their evaluation, where their solver was even faster on difference logic than specialized solvers of the time.
  • Integers. If variables are integer, the simplex solution may not be. The paper uses branch and cut: branch on fractional variable vv with atoms x≤⌊v⌋x \le \lfloor v \rfloor or x≥⌈v⌉x \ge \lceil v \rceil, treated by CDCL like any others, and add Gomory cuts, which the authors report drastically accelerating convergence in several cases.

Cost. One pivot costs about tableau size (rows times columns for dense; far less for typical sparse rows). Check may take exponentially many pivots in the worst case, even with Bland’s rule (Avis and Chvátal, 1978), but in SMT each Check usually repairs few bounds from a nearly valid assignment using very few pivots. Call count dominates, making pivot-free backtracking and propagation important.

[ ]General simplex with exact rationals, validated against HiGHSBrowser
from fractions import Fraction as F
import random

class SimplexSMT:
    """Símplex general de Dutertre y de Moura (2006): tableau fijo, cotas que van y vienen, Check con la regla de Bland.
    Variables 0..n-1 originales; cada forma lineal sum a_j x_j recibe una holgura básica s_i = sum a_j x_j."""

    def __init__(self, n, formas):
        self.N = n + len(formas)
        self.fila = {n + i: {j: F(a) for j, a in enumerate(f) if a} for i, f in enumerate(formas)}  # básica -> fila
        self.val = [F(0)] * self.N
        self.lo, self.hi = [None] * self.N, [None] * self.N   # (valor, etiqueta del átomo)
        self.pivotes = 0

    def _actualiza(self, j, v):
        d = v - self.val[j]
        for b, r in self.fila.items():
            if j in r:
                self.val[b] += r[j] * d
        self.val[j] = v

    def aserta(self, x, tipo, k, etiqueta):
        """tipo '<=' o '>='. Devuelve una explicación si choca con la otra cota de x; si no, None."""
        k = F(k)
        if tipo == "<=":
            if self.lo[x] and k < self.lo[x][0]: return {self.lo[x][1], etiqueta}
            if self.hi[x] is None or k < self.hi[x][0]:
                self.hi[x] = (k, etiqueta)
                if x not in self.fila and self.val[x] > k: self._actualiza(x, k)
        else:
            if self.hi[x] and k > self.hi[x][0]: return {self.hi[x][1], etiqueta}
            if self.lo[x] is None or k > self.lo[x][0]:
                self.lo[x] = (k, etiqueta)
                if x not in self.fila and self.val[x] < k: self._actualiza(x, k)
        return None

    def _pivota(self, xi, xj):
        r = self.fila.pop(xi); a = r.pop(xj)
        nueva = {k: -c / a for k, c in r.items()}; nueva[xi] = 1 / a      # xj en función de xi y del resto
        for b, rb in self.fila.items():
            if xj in rb:
                c = rb.pop(xj)
                for k, ck in nueva.items():
                    v = rb.get(k, 0) + c * ck
                    if v: rb[k] = v
                    else: rb.pop(k, None)
        self.fila[xj] = nueva
        self.pivotes += 1

    def check(self):
        """Devuelve None si las cotas son compatibles; si no, la explicación (etiquetas de las cotas de una fila)."""
        while True:
            malas = [b for b in sorted(self.fila) if (self.lo[b] and self.val[b] < self.lo[b][0]) or
                                                     (self.hi[b] and self.val[b] > self.hi[b][0])]
            if not malas:
                return None
            xi = malas[0]; r = self.fila[xi]
            baja = bool(self.lo[xi]) and self.val[xi] < self.lo[xi][0]
            def puede(j):            # ¿puede xj mover xi en la dirección necesaria?
                sube_j = (r[j] > 0) == baja
                return (self.hi[j] is None or self.val[j] < self.hi[j][0]) if sube_j else \
                       (self.lo[j] is None or self.val[j] > self.lo[j][0])
            cand = [j for j in sorted(r) if puede(j)]
            if not cand:
                expl = {self.lo[xi][1] if baja else self.hi[xi][1]}
                for j, c in r.items():
                    b = self.hi[j] if (c > 0) == baja else self.lo[j]
                    expl.add(b[1])
                return expl
            xj = cand[0]
            objetivo = self.lo[xi][0] if baja else self.hi[xi][0]
            theta = (objetivo - self.val[xi]) / r[xj]
            self.val[xi] = objetivo; self.val[xj] += theta
            for b, rb in self.fila.items():
                if b != xi and xj in rb: self.val[b] += rb[xj] * theta
            self._pivota(xi, xj)

def resuelve(n, formas, atomos):
    """atomos: lista de (índice de forma o -1-j para la variable j, tipo, k). Devuelve (sat, explicación, pivotes)."""
    s = SimplexSMT(n, formas)
    for e, (f, tipo, k) in enumerate(atomos):
        x = n + f if f >= 0 else -1 - f
        ex = s.aserta(x, tipo, k, e)
        if ex: return False, ex, s.pivotes, s
        ex = s.check()
        if ex: return False, ex, s.pivotes, s
    return True, None, s.pivotes, s

# El ejemplo de la figura: s1 = x + y <= 4, s2 = x - y >= 1, y >= 2, x <= 4
sat, ex, piv, s = resuelve(2, [[1, 1], [1, -1]], [(0, "<=", 4), (1, ">=", 1), (-2, ">=", 2), (-1, "<=", 4)])
print("figura con b1: x + y <= 4 ->", "sat" if sat else f"unsat, explicación {sorted(f'b{e + 1}' for e in ex)}", f"tras {piv} pivote(s)")
sat, ex, piv, s = resuelve(2, [[1, 1], [1, -1]], [(0, "<=", 6), (1, ">=", 1), (-2, ">=", 2), (-1, "<=", 4)])
print("figura con b1: x + y <= 6 ->", "sat" if sat else "unsat", f"tras {piv} pivote(s); modelo x = {s.val[0]}, y = {s.val[1]}")

# Validación aleatoria contra HiGHS y tamaño de las explicaciones
from scipy.optimize import linprog
import numpy as np
rnd = random.Random(3)
acuerdos = minimas = conflictos = 0; tam = []
for prueba in range(150):
    n, m = 3, 4
    formas = [[rnd.randint(-3, 3) for _ in range(n)] for _ in range(m)]
    atomos = [(rnd.randrange(-n, m), rnd.choice(["<=", ">="]), rnd.randint(-4, 4)) for _ in range(6)]
    sat, ex, piv, _ = resuelve(n, formas, atomos)
    # el mismo problema para HiGHS: A_ub x <= b_ub con cada forma (o variable) y su cota
    filas, b = [], []
    for f, tipo, k in atomos:
        a = formas[f] if f >= 0 else [1 if j == -1 - f else 0 for j in range(n)]
        sg = 1 if tipo == "<=" else -1
        filas.append([sg * v for v in a]); b.append(sg * k)
    ref = linprog(np.zeros(n), A_ub=filas, b_ub=b, bounds=[(None, None)] * n, method="highs").status == 0
    acuerdos += sat == ref
    if not sat:
        conflictos += 1; tam.append(len(ex))
        sub = [atomos[e] for e in sorted(ex)]
        assert not resuelve(n, formas, sub)[0], "la explicación debe ser insatisfacible por sí sola"
        minimas += all(resuelve(n, formas, sub[:i] + sub[i + 1:])[0] for i in range(len(sub)))
print(f"coincide con HiGHS en {acuerdos} de 150 problemas; {conflictos} insatisfacibles")
print(f"explicaciones: tamaño medio {sum(tam) / len(tam):.2f} de 6 átomos; {minimas} de {conflictos} son mínimas "
      f"(quitar cualquier átomo las hace satisfacibles)")

The implementation agrees with HiGHS on all 150 random problems, 67 unsatisfiable. Explanations average 2.37 of 6 atoms and all 67 are minimal in this sample: removing any explanation atom makes it satisfiable. Not a general theorem (a row can carry unnecessary bounds), but typical for small problems.

Reluplex. General simplex can be extended with nonlinear constraints. Reluplex (Katz et al., 2017) adds ReLU constraint y=max⁡(0,x)y = \max(0, x): let simplex temporarily violate the relationship between xx and yy, repair it using specialized pivots and, only if a ReLU resists, branch on its two phases (active or inactive) as DPLL(T) would. They verified properties of prototype ACAS Xu drone-collision-avoidance networks, reportedly an order of magnitude larger than earlier methods reached.

Bit-vectors: bit-blasting

Bit-vector theory models machine integers: ww-bit vectors with arithmetic modulo 2w2^w (bvadd, bvmul, bvudiv), bitwise operations, shifts, and unsigned (bvult) and two’s-complement signed (bvslt) comparisons. It is the theory of low-level software verification and symbolic execution in lesson 15, exactly reproducing overflow.

Bit-blasting reduces it to SAT: each ww-bit vector becomes ww Boolean variables, each operator its hardware circuit, and each gate a few clauses via the Tseitin transformation: fresh variable gg per gate and clauses for g↔(a∧b)g \leftrightarrow (a \land b) (three), g↔(a∨b)g \leftrightarrow (a \lor b) (three) or g↔(a⊕b)g \leftrightarrow (a \oplus b) (four). An ww-bit adder chains full adders each with si=ai⊕bi⊕cis_i = a_i \oplus b_i \oplus c_i and ci+1=(ai∧bi)∨(ci∧(ai⊕bi))c_{i+1} = (a_i \land b_i) \lor (c_i \land (a_i \oplus b_i)): linear size. A full shift-add multiplier has w2w^2 AND gates for partial products and w−1w - 1 adders (the cell’s low-ww-bit-only version saves half the AND gates): quadratic size. Unsigned division is encoded using multiplication and addition, a=q⋅b+r∧r<ba = q \cdot b + r \land r < b for b≠0b \neq 0 (ensuring q⋅b+rq \cdot b + r does not overflow), inheriting that size.

[ ]Bit-blasting: adder and multiplier with TseitinBrowser
import random

class Circuito:
    """Bit-blasting con la transformación de Tseitin: cada puerta es una variable nueva y unas pocas cláusulas."""
    def __init__(self):
        self.n, self.cls = 0, []
    def var(self):
        self.n += 1
        return self.n
    def AND(self, a, b):
        x = self.var(); self.cls += [[-x, a], [-x, b], [x, -a, -b]]; return x
    def OR(self, a, b):
        x = self.var(); self.cls += [[x, -a], [x, -b], [-x, a, b]]; return x
    def XOR(self, a, b):
        x = self.var(); self.cls += [[-x, a, b], [-x, -a, -b], [x, -a, b], [x, a, -b]]; return x
    def entrada(self, w):
        return [self.var() for _ in range(w)]
    def suma(self, A, B, c=None):
        """Sumador de acarreo en cascada, módulo 2^w. Con c = None el bit 0 es un semisumador."""
        S = []
        for i, (a, b) in enumerate(zip(A, B)):
            t = self.XOR(a, b)
            if c is None:
                S.append(t); c = self.AND(a, b)
            else:
                S.append(self.XOR(t, c))
                if i + 1 < len(A):               # el acarreo del último bit se descarta (módulo 2^w)
                    c = self.OR(self.AND(a, b), self.AND(t, c))
        return S
    def producto(self, A, B):
        """Multiplicador de sumas desplazadas, módulo 2^w: w² puertas AND y w − 1 sumadores."""
        w = len(A)
        acc = [self.AND(A[i], B[0]) for i in range(w)]
        for j in range(1, w):
            fila = [self.AND(A[i - j], B[j]) for i in range(j, w)]
            acc = acc[:j] + self.suma(acc[j:], fila)
        return acc
    def distintos(self, X, Y):
        """Cláusula «algún bit difiere» (el inglete, miter, de dos circuitos)."""
        d = [self.XOR(x, y) for x, y in zip(X, Y)]
        self.cls.append(d)

def cuenta(op, w):
    c = Circuito(); A, B = c.entrada(w), c.entrada(w)
    (c.suma if op == "suma" else c.producto)(A, B)
    return c.n - 2 * w, len(c.cls)

print("variables auxiliares y cláusulas de Tseitin, módulo 2^w:")
for w in (8, 16, 32, 64):
    va, ca = cuenta("suma", w); vm, cm = cuenta("producto", w)
    print(f"  w = {w:2d}   suma: {va:5d} aux, {ca:6d} cláusulas   producto: {vm:6d} aux, {cm:7d} cláusulas")

def comprueba(op, w, pruebas, rnd):
    """Fija las entradas con cláusulas unitarias y lee la salida del modelo (con el CDCL del laboratorio 2)."""
    for _ in range(pruebas):
        c = Circuito(); A, B = c.entrada(w), c.entrada(w)
        S = (c.suma if op == "suma" else c.producto)(A, B)
        x, y = rnd.randrange(2 ** w), rnd.randrange(2 ** w)
        unit = [[v if (x >> i) & 1 else -v] for i, v in enumerate(A)] + [[v if (y >> i) & 1 else -v] for i, v in enumerate(B)]
        s = CDCL(c.n, c.cls + unit); assert s.solve()
        z = sum(1 << i for i, v in enumerate(S) if s.val[v] == 1)
        esperado = (x + y if op == "suma" else x * y) % 2 ** w
        assert z == esperado, (op, x, y, z, esperado)
        assert s.stats["decisions"] == 0, "con las entradas fijadas, la propagación unitaria basta"
    return True
rnd = random.Random(0)
print("suma de 16 bits correcta en 20 pruebas:", comprueba("suma", 16, 20, rnd))
print("producto de 8 bits correcto en 20 pruebas:", comprueba("producto", 8, 20, rnd))

At 32 bits addition uses 525 clauses and multiplication 9436, eighteen times more; at 64 bits the ratio is 37 (1069 versus 39,324). Both checks fix inputs with unit clauses, determining outputs by unit propagation alone (zero decisions): Tseitin circuit encoding propagates well forward.

But size is not multiplication’s real problem. Forward with fixed inputs is all propagation. Backward (which inputs give this output?) or between two multipliers, SAT must search, and multipliers are among its hardest inputs. The next cell proves addition and multiplication commutative for every pair of ww-bit inputs: construct the miter of f(x,y)f(x, y) and f(y,x)f(y, x), CNF saying “some output differs”, unsatisfiable iff they match, and count CaDiCaL conflicts.

[ ]Multiplier commutativity by logical brute forceBrowser
from pysat.solvers import Solver

def inglete(op, w):
    """CNF de «existen x, y de w bits con op(x, y) != op(y, x)»: insatisfacible si op es conmutativa."""
    c = Circuito(); A, B = c.entrada(w), c.entrada(w)
    f = c.suma if op == "suma" else c.producto
    c.distintos(f(A, B), f(B, A))
    return c

print("conmutatividad por bit-blasting: conflictos de CaDiCaL hasta probar que el inglete es insatisfacible")
previo = None
for w in (4, 5, 6, 7):                     # añade 8 y 9 en local: el producto sigue multiplicándose
    fila = []
    for op in ("suma", "producto"):
        c = inglete(op, w)
        with Solver(name="cadical153", bootstrap_with=c.cls) as s:
            r = s.solve(); conf = s.accum_stats()["conflicts"]
        assert r is False
        fila.append((conf, len(c.cls)))
    (cs, ns), (cp, np_) = fila
    crece = f"   (x{cp / previo:.1f} respecto a w - 1)" if previo else ""
    print(f"  w = {w}: suma {cs:5d} conflictos ({ns:4d} cláusulas)   producto {cp:6d} conflictos ({np_:5d} cláusulas){crece}")
    previo = cp

Addition conflicts grow slowly, roughly proportional to ww. For multiplication they multiply by 3 to 5 per added bit, as the last column shows (the cell stops at w=7w = 7 to keep browser runtime to seconds; add 8 and 9 locally to see it continue): exponential growth for a property a human proves in one line. SAT multiplier verification is a known hard problem motivating specialized techniques, such as combining SAT with computational algebra on circuit polynomials (Kaufmann, Biere and Kauers, 2019). Thus bit-vector solvers do not blindly bit-blast: first simplify at word level (rewrites such as x⋅y=y⋅xx \cdot y = y \cdot x, constant propagation, bit extraction), and some lazily bit-blast only what is needed (Hadarean et al., 2014, compare both in CVC4).

Combining theories: Nelson–Oppen

Real formulas mix theories: f(x+1)=y∧x≥0f(x + 1) = y \land x \ge 0 uses EUF and arithmetic together. Nelson and Oppen (1979) gave the standard method for combining decision procedures.

Purification. Introduce fresh variables to separate each theory’s terms until each literal is pure, from one theory. f(x+1)=yf(x + 1) = y becomes f(v)=yf(v) = y (EUF) and v=x+1v = x + 1 (arithmetic). Variables appearing in literals of both theories are shared, here vv.

Equality exchange. Each solver decides its part. If one theory implies equality between shared variables, it communicates it to the other. Repeat until a part is inconsistent (unsatisfiable) or nothing new propagates (satisfiable).

Stable infiniteness enters the soundness proof: both parts’ models must be glued into one, requiring universes of equal cardinality (modern proof by Tinelli and Harandi, 1996). Convexity determines cost. Linear real arithmetic and EUF are convex; integer arithmetic is not:

1≤x∧x≤2  ⊨LIA  x=1∨x=2,pero no implica x=1 ni x=2.1 \le x \land x \le 2 \;\models_{\mathrm{LIA}}\; x = 1 \lor x = 2, \quad\text{pero no implica } x = 1 \text{ ni } x = 2.

With f(x)≠f(1)∧f(x)≠f(2)f(x) \neq f(1) \land f(x) \neq f(2) added (and purified using c1=1c_1 = 1, c2=2c_2 = 2), the formula is unsatisfiable in LIA plus EUF, yet neither part alone deduces a shared-variable equality. Split cases: if x=c1x = c_1, EUF gives f(x)=f(c1)f(x) = f(c_1) and conflict; if x=c2x = c_2, likewise. Over reals the same formula is satisfiable with x=3/2x = 3/2, checked by Z3 in lab 3. Oppen (1980) studied cost: convex theories with polynomial procedures retain polynomial combination, while without convexity case splits can make it NP-hard.

Real solvers integrate combination into DPLL(T): shared-variable equalities are additional atoms CDCL can decide. Z3 uses model-based combination (de Moura and Bjørner, 2008): rather than derive every implied equality, expensive in arithmetic, each theory constructs a candidate model and reconciles only the equalities it assumes. If xx and yy have equal values in the arithmetic model, x=yx = y is proposed as a decision to other theories and, if incompatible, CDCL backtracks normally. Its authors describe this as Z3’s central design idea, recurring in arrays and quantifiers (Bjørner and de Moura, 2019).

The same pattern in constraint programming

DPLL(T)‘s architecture is not exclusive to SMT. In lesson 10 you used CP-SAT and its global constraints. A constraint-programming propagator does what a theory solver does: receives domain changes and infers others. Lazy clause generation (Ohrimenko, Stuckey and Codish, 2009) completes the analogy:

  • Domains use Boolean literals of order and direct encodings, [x≤v][x \le v] and [x=v][x = v], created on demand.
  • Each time a propagator prunes a value, it explains this with a clause over those literals. For example, x+y≤10x + y \le 10‘s propagator inferring y≤6y \le 6 from x≥4x \ge 4 records reason [x≤3]∨[y≤6][x \le 3] \lor [y \le 6].
  • SAT treats reasons normally: analyzes conflicts, learns nogoods and backjumps.

This is exactly T-Propagate with explanations, one propagator per constraint rather than one solver per theory. OR-Tools CP-SAT follows this pattern: its authors describe a constraint solver built on SAT with lazy clause generation plus simplex (Perron, Didier and Gay, 2023). A global constraint such as NoOverlap or Cumulative is judged by its explanation quality like a theory solver.

Z3’s design

Z3 (de Moura and Bjørner, 2008) combines everything above:

  • A DPLL(T) core with modern CDCL.
  • An E-graph: congruence closure shared across theories, maintaining term classes as a common blackboard. Theory solvers attach to its nodes.
  • Theory solvers: arithmetic (general simplex with branching and cuts for integers), bit-vectors (bit-blasting after word-level simplification), arrays, data types and others.
  • Model-based combination.
  • For quantifiers, E-matching (instantiate using E-graph terms) and MBQI (instantiate guided by a candidate model), studied in lesson 14.
  • Tactics: composable formula transformations (simplify, solve-eqs, bit-blast, tseitin-cnf…) selecting a problem-specific strategy. Declaring logic with SolverFor("QF_BV") selects a prepared strategy.

Lab 3: first steps with Z3

The first cell solves familiar problems with Z3: machine integers, reals versus integers, lab 2’s job shop in QF_IDL, and bit-blasting three 32-bit operations, counting clauses with Z3 tactics.

[ ]Z3: machine integers, theories and bit-blastingLocal GPU
import itertools, random, time
from z3 import *

print("z3", get_version_string())

# 1. Enteros matemáticos frente a enteros de máquina
x = Int("x")
print("Int:        ", end=" "); prove(x + 1 > x)
b = BitVec("b", 32)
print("BitVec 32:  ", end=" "); prove(b + 1 > b)          # > es la comparación con signo
n = BitVec("n", 32)
s = Solver()
s.add(UGT(n, 0), ULT(n * 4, n))                           # n * 4 da la vuelta: tamaño de reserva que se queda corto
print("¿n * 4 < n sin signo?", s.check(), "con n =", s.model()[n], "y n * 4 =", s.model().eval(n * 4))

# 2. Reales frente a enteros: la misma fórmula, dos teorías
for Srt, nombre in ((Real, "Real"), (Int, "Int")):
    y = Srt("y")
    s = Solver(); s.add(2 * y == 1)
    print(f"2y = 1 sobre {nombre}: {s.check()}", s.model() if s.check() == sat else "")
r = Real("r"); s = Solver(); s.add(r > 0, r < 1); s.check(); print("0 < r < 1:", s.model())

# 3. El job shop del laboratorio 2 en QF_IDL
def jobshop(n_jobs, n_mach, seed, dmax=9):
    rnd = random.Random(seed); jobs = []
    for j in range(n_jobs):
        orden = list(range(n_mach)); rnd.shuffle(orden)
        jobs.append([(m, rnd.randint(1, dmax)) for m in orden])
    return jobs
jobs = jobshop(5, 5, seed=2)
def modelo_js(s, M):
    S = {(j, k): Int(f"s_{j}_{k}") for j, job in enumerate(jobs) for k in range(len(job))}
    for (j, k), v in S.items():
        s.add(v >= 0)
        if k + 1 < len(jobs[j]): s.add(S[(j, k + 1)] - v >= jobs[j][k][1])
        else: s.add(v + jobs[j][k][1] <= M)
    for a, c in itertools.combinations(S, 2):
        (ma, da), (mc, dc) = jobs[a[0]][a[1]], jobs[c[0]][c[1]]
        if ma == mc: s.add(Or(S[c] - S[a] >= da, S[a] - S[c] >= dc))
    return S
for M in (53, 54):
    s = SolverFor("QF_IDL"); modelo_js(s, M)
    t0 = time.perf_counter(); r = s.check(); t = time.perf_counter() - t0
    st = s.statistics()
    print(f"job shop 5x5, M = {M}: {r}; conflictos {st.get_key_value('conflicts') if 'conflicts' in st.keys() else '-'}, "
          f"decisiones {st.get_key_value('decisions') if 'decisions' in st.keys() else '-'}")
o = Optimize(); Mk = Int("M"); S = modelo_js(o, Mk); o.minimize(Mk); o.check()
print("Optimize: makespan mínimo", o.model()[Mk])

# 4. Bit-blasting dentro de Z3: cuántas cláusulas cuesta cada operación de 32 bits
p, q, c = BitVecs("p q c", 32)
for nombre, f in (("p + q == c", p + q == c), ("p * q == c", p * q == c), ("p / q == c (udiv)", UDiv(p, q) == c)):
    g = Goal(); g.add(f)
    cnf = Then("simplify", "bit-blast", "tseitin-cnf")(g)[0]
    print(f"{nombre:20s} -> {len(cnf):6d} cláusulas")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

What to inspect:

  • x + 1 > x is valid over Int and false on 32-bit vectors: counterexample b=231−1b = 2^{31} - 1 is the largest signed integer, whose successor wraps negative. The malloc(n * 4) overflow question is answered: with n=1431655764n = 1431655764, n * 4 equals 1431655760 in 32 bits, less than n. This defensive use finds a value breaking a size check before someone else does.
  • 2y=12y = 1 is satisfiable over reals (y=1/2y = 1/2) and unsatisfiable over integers: theory changes the answer.
  • The job shop matches your DPLL(T): 53 unsatisfiable, 54 satisfiable, and Optimize confirms 54 as minimum. Its conflicts (28 for M=53M = 53) lie between your solver with theory propagation (5) and without (55); exact figures depend on Z3 version and heuristics.
  • Z3 tactics count 445 clauses for 32-bit addition, 8213 for multiplication and 19,174 for unsigned division: the same scale as your bit-blasting (525 and 9436), with some simplification.

The second cell moves to EUF, theory combination, nonlinear arithmetic and SMT-LIB.

[ ]Z3: uninterpreted functions, Nelson–Oppen, unknown and SMT-LIBLocal GPU
from z3 import *

# 5. Funciones no interpretadas: la validación de traducciones del laboratorio 1
V = DeclareSort("V")
mul, add, sub = (Function(f, V, V, V) for f in ("mul", "add", "sub"))
a, b, c = Consts("a b c", V)
t1, t2, t3, t4 = mul(a, b), mul(a, b), add(mul(a, b), c), add(mul(a, b), c)
r_fuente = sub(t3, t4)
print("CSE en EUF:          ", end=" "); prove(r_fuente == sub(add(mul(a, b), c), add(mul(a, b), c)))
print("add conmutada (EUF): ", end=" "); prove(add(mul(a, b), c) == add(c, mul(a, b)))
ai, bi, ci = Ints("a b c")
print("add conmutada (Int): ", end=" "); prove(ai * bi + ci == ci + ai * bi)

# 6. Convexidad: la misma fórmula sobre enteros y sobre reales
for nombre, Srt, dom in (("Int", Int, IntSort()), ("Real", Real, RealSort())):
    f = Function("f", dom, IntSort())
    x = Srt("x")
    s = Solver(); s.add(1 <= x, x <= 2, f(x) != f(1), f(x) != f(2))
    r = s.check()
    print(f"1 <= x <= 2, f(x) != f(1), f(x) != f(2) sobre {nombre}: {r}", s.model()[x] if r == sat else "")

# 6 bis. Nelson-Oppen en acción: aritmética lineal real y funciones no interpretadas
x1, x2, x3 = Reals("x1 x2 x3")
g = Function("g", RealSort(), RealSort())
s = Solver()
s.add(x2 >= x1, x1 - x3 >= x2, x3 >= 0, g(g(x1) - g(x2)) != g(x3))
print("x2 >= x1, x1 - x3 >= x2, x3 >= 0, g(g(x1) - g(x2)) != g(x3):", s.check())

# 7. Aritmética no lineal entera: indecidible en general; Z3 puede rendirse
x, y, z = Ints("x y z")
s = Solver(); s.set("timeout", 2000)
s.add(x**3 + y**3 + z**3 == 33)
r = s.check()
print("x³ + y³ + z³ = 33 con 2 s:", r, "| motivo:", s.reason_unknown() if r == unknown else "")

# 8. Lógicas SMT-LIB y el texto que ve el solver
s = SolverFor("QF_LIA")
p, q = Ints("p q")
s.add(p + 2 * q >= 3, p - q <= 1, Or(p < 0, q > 5))
print(s.sexpr())
print(s.check(), s.model())
st = s.statistics()
print({k: st.get_key_value(k) for k in st.keys() if k in ("conflicts", "decisions", "arith-pivots", "arith-make-feasible", "propagations")})
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
  • With DeclareSort and Function, Z3 matches your congruence closure: validates CSE but not commuting add, with a counterexample where add is an arbitrary table. Over Int, commutativity is proved.
  • The nonconvex formula (1≤x≤21 \le x \le 2, f(x)≠f(1)f(x) \neq f(1), f(x)≠f(2)f(x) \neq f(2)) is unsatisfiable over Int and satisfiable over Real with x=3/2x = 3/2. The back-and-forth equality example is unsatisfiable as derived by hand.
  • x3+y3+z3=33x^3 + y^3 + z^3 = 33 over integers returns unknown with a 2-second limit: nonlinear integer arithmetic is undecidable (Hilbert’s tenth problem) and Z3 can only apply heuristics. This particular equation has a solution using 16-digit numbers, found by Booker in 2019 with a dedicated search.
  • s.sexpr() prints the problem in SMT-LIB, the same text seen at the start, and statistics show simplex calls (arith-make-feasible).

Common mistakes

Exercises

ProofNegative cycles and models
Prove: A finite set of constraints x−y≤cx - y \le c is satisfiable iff its graph (edge y→xy \to x of weight cc) has no negative-weight cycles; then shortest distances from a new vertex ss joined to all vertices with weight 0 form a model, integer if constants are integer.
0
Write δ(s,x)\delta(s, x) for shortest distance from ss to xx in the augmented graph.

Step 1 of 4. For the forward direction, assume model vv and cycle x0→x1→⋯→xk=x0x_0 \to x_1 \to \dots \to x_k = x_0 with weights c1,…,ckc_1, \dots, c_k. What do you do?

CodeDecide EUF with congruence closure
Implement congruence_closure(igualdades, desigualdades, terminos), returning True if the conjunction of equalities and inequalities is EUF-satisfiable and False otherwise. Terms are strings (constants) or tuples (f, arg1, ..., argk); igualdades and desigualdades list term pairs, and terminos lists extra terms (which do not change the answer but must be accepted). Remember to register every subterm: congruence acts on them. Tests compare with brute force over all subterm partitions.
def congruence_closure(igualdades, desigualdades, terminos):
  """True si la conjunción es satisfacible en EUF."""
  # 1. reúne todos los subtérminos de terminos, igualdades y desigualdades
  # 2. union-find: une los dos lados de cada igualdad
  # 3. repite hasta el punto fijo: dos aplicaciones con el mismo símbolo y argumentos en la misma clase se unen
  # 4. comprueba las desigualdades
  return True
Shift+Enter to run
QuizIs integer arithmetic convex?
A theory is convex if whenever a literal conjunction implies a disjunction of variable equalities, it implies one of them. Is linear integer arithmetic (LIA) convex, and what does that mean for Nelson–Oppen combined with EUF?
NumericClauses in a 32-bit adder
A 32-bit ripple-carry adder uses 32 identical full adders (input carry c0c_0 is another variable and final carry c32c_{32} is also computed). Each full adder uses five gates: t=a⊕bt = a \oplus b, s=t⊕cs = t \oplus c, g=a∧bg = a \land b, h=t∧ch = t \land c and c′=g∨hc' = g \lor h. Using Tseitin (one variable per gate; 4 clauses per XOR and 3 per AND or OR), how many CNF clauses?
QuizChoose the SMT-LIB logic
Four problems: (1) verify a C function computing len * sizeof(T) with uint32_t cannot overflow; (2) a schedule with integer times and constraints such as 2sA+3sB≤402s_A + 3s_B \le 40; (3) verify a loop over an integer array with arithmetic indices that calls an auxiliary function to abstract; (4) decide feasibility of rational-coefficient linear inequalities over real variables. Which logic assignment is appropriate?
NumericAckermann's cost
A formula contains unary symbol ff applied to 6 distinct terms and binary symbol gg applied to 4 distinct argument pairs. How many functional-consistency constraints does Ackermann reduction add?
NumericHow much does an explanation prune?
A problem's Boolean abstraction has 12 free atoms. Theory finds a conflict explained by 3 literals, all on free atoms. How many of the 2122^{12} total assignments are eliminated by the learned clause?
NumericThe critical constant
Over integers: x−y≤2x - y \le 2, y−z≤−5y - z \le -5, z−x≤cz - x \le c, z−w≤1z - w \le 1 and w−x≤3w - x \le 3. What is the smallest cc making the system satisfiable?
QuizA row's explanation
In general simplex, basic ss has row s=2x−ys = 2x - y, with nonbasic xx and yy. Asserted bounds are b1: s≥5s \ge 5, b2: x≤2x \le 2, b3: y≥0y \ge 0, b4: y≤4y \le 4 and b5: x≥−10x \ge -10, with assignment x=2x = 2, y=0y = 0, s=4s = 4. What does Check return?
QuizA theory propagation's reason
Theory propagates literal ℓ\ell because it follows from asserted literals e1e_1 and e2e_2. For conflict analysis, which reason clause brings ℓ\ell into the implication graph?

Summary

Key idea
SMT divides work: CDCL decides Boolean structure while each theory decides atom conjunctions using its natural algorithm (union-find, Bellman–Ford, simplex). Explanations make this work: each theory conflict returns to CDCL as a short clause pruning an entire search-space region.
  • A theory fixes meaning of some symbols; SMT-LIB organizes useful fragments into logics (QF_UF, QF_IDL, QF_LIA, QF_LRA, QF_BV, QF_AUFLIA…). Choosing the right logic chooses the decision procedure.
  • Eager translation sends everything to SAT (bit-blasting, Ackermann); lazy abstraction makes atoms Boolean and consults theory. DPLL(T) integrates theory with CDCL: incremental assertions, explained conflicts and propagations entering 1-UIP analysis, and cheap backtracking.
  • EUF is decided by congruence closure in O(nlog⁡n)\bigO(n \log n) with proof-forest explanations. Difference logic is a shortest-path problem: inconsistent iff a negative cycle exists, a minimal explanation; virtual-source distances form a model.
  • Linear arithmetic uses Dutertre–de Moura general simplex: fixed tableau, changing bounds, Bland’s rule, row explanations, δ\delta for strict inequalities and branch-and-cut for integers. Backtracking does not pivot.
  • Bit-vectors are bit-blasted: addition has linear size, multiplication quadratic and especially difficult for SAT.
  • Nelson–Oppen combines disjoint-signature stably infinite theories by equality propagation; nonconvexity needs case splits. Z3 uses model guidance.
  • Lazy clause generation is the same pattern in constraint programming, at CP-SAT’s core.