Module contents
Lesson 14 of 23Advanced 105 min

Z3 in depth: incremental solving, cores, optimization, quantifiers and synthesis

Use Z3 incrementally with assumptions and unsatisfiable cores, MaxSAT, optimization, quantifiers and counterexample-guided synthesis.

After this lesson you can

  • Use Z3 incrementally with push/pop and assumptions, and extract minimal unsatisfiable cores.
  • Implement Fu–Malik MaxSAT and solve optimization problems with Z3's optimizer.
  • Diagnose quantified queries returning unknown or timing out by choosing E-matching patterns or MBQI.
  • Synthesize branch-free programs with CEGIS and recognize the ∃∀ structure.
  • Speed up a slow SMT model using statistics, tactics and reformulated constraints.

Before you start

Motivation: the same solver, hours or milliseconds

The previous lesson opened an SMT solver: DPLL(T) coordinates Boolean CDCL with decision procedures for each theory. This lesson covers the other side: using Z3 on real problems. The difference between naive and professional use is not 10%. Labs show queries changing from a 20-second timeout to one conflict, quantified queries changing from timeout to sat in milliseconds with one instance, and query batches running over ten times faster without changing a constraint.

Each section is motivated by practical problems:

  • Many questions on one model. A configuration validator checks hundreds of policy variants; a planner repeatedly asks “what if I fix this shift?” Rebuilding the solver discards everything learned.
  • Explaining “no”. When firewall or package-dependency rules conflict, “unsat” is insufficient: identify conflicting rules and the smallest number to remove. These are an unsatisfiable core and its dual, a correction set.
  • Optimization. A shift roster rarely satisfies every preference; minimize violations. This is MaxSAT, whose best algorithms use cores as their engine.
  • Quantifiers. Verifying programs requires axiomatizing structures (lists, heaps, arrays) with ∀\forall, the commonest cause of unknown and unexplained timeouts.
  • Synthesis. Finding a program satisfying a specification for every input is an ∃∀\exists\forall problem. CEGIS reduces it to quantifier-free queries and underlies code superoptimizers.

The common thread is incremental solving: nearly everything below repeatedly calls Z3 on formulas changing little. Build each part from scratch in the browser (DPLL returning cores, minimization, Fu–Malik, exhaustive 8-bit CEGIS), then the Z3 version locally. Local cells need pip install z3-solver; quoted results use version 5.3.1.

Professional Z3 workflow

A Python Z3 model has three parts: symbols (z3.Int, z3.Bool, z3.BitVec(nombre, 32), uninterpreted functions using z3.Function), assertions added to Solver with add, and queries (check) returning sat, unsat or unknown; after sat, model() provides a satisfying interpretation. First choose the theory matching the problem: mathematical integers (Int) for actual arithmetic, bit-vectors for machine code where 231−1+12^{31} - 1 + 1 is −231-2^{31} (shown in synthesis) and Z3 uses bit-blasting.

Professional workflows keep the solver alive across many queries. Two mechanisms support this.

Scopes: push and pop. push() opens a scope; corresponding pop() removes later additions. Useful for nested “what if also…?” questions in search.

Assumptions. check(l1, l2, ...) checks assertions’ satisfiability assuming literals lil_i without adding them. If the answer is unsat, unsat_core() returns a subset already sufficient for contradiction. To assume an arbitrary constraint CC rather than a literal, use a selector: fresh Boolean pp, permanent assertion p→Cp \rightarrow C and assumption pp. This is exactly what assert_and_track(C, p) does; Programming Z3 (Bjørner, de Moura, Nachmanson and Wintersteiger, 2019) says it has the effect of adding Implies(p, q) and implicitly assuming p.

Every minimum-cardinality MUS is a MUS, not conversely: this section’s explorer has 3-rule and 6-rule MUSes, with the 6-rule ones equally inclusion-minimal.

What survives between queries

Assumptions work well because of how CDCL handles them. Eén and Sörensson introduced them in MiniSat (An Extensible SAT-solver, 2003) simply: before deciding anything else, the solver treats a1,…,ama_1, \dots, a_m as decisions at the first trail levels.

Proof

Induct on learned clauses. Conflict analysis constructs the learned clause by resolution from the conflict clause and implied-literal reasons, all in the database of permanent and earlier learned clauses, which follow from permanent ones by induction. Resolution is sound, so the new clause follows too. Assumptions never enter the database: they are decisions, and decisions are no literal’s reason or resolution premise.

∎

With push/pop it differs. An assertion added inside a scope is a database clause, and learning from it ceases to be valid when it is removed: on pop the solver must discard what may depend on that scope. Selectors avoid this: p→Cp \rightarrow C is permanent and always true (pp false suffices), so learned clauses based on it, containing literal ¬p\neg p, remain valid afterward. Assumptions are therefore usually the default for nonnested queries.

A Z3 detail matters. Solver() combines two engines: Programming Z3 explains that the first check uses a one-shot solver and subsequent calls normally switch to an incremental solver. One-shot solving applies aggressive preprocessing that cannot be undone; incremental solving gives up some to allow assertion removal. Thus a new solver’s first query may follow a different path from later ones, and rebuilding per query repeatedly pays preprocessing and relearns from scratch.

The next cell measures this with 196 questions on 14 queens (“is there a solution with the row-0 queen in column jj and row-1 queen in column kk?”): a new solver per question, one solver with assumptions, and one with push/pop. Times vary by machine; the ratio matters.

[ ]A new solver per query versus assumptions and push/popLocal GPU
import z3, time

def reinas(n):
    q = [[z3.Bool(f'q_{i}_{j}') for j in range(n)] for i in range(n)]
    F = [z3.PbEq([(q[i][j], 1) for j in range(n)], 1) for i in range(n)]
    F += [z3.PbEq([(q[i][j], 1) for i in range(n)], 1) for j in range(n)]
    for d in range(-n + 1, n):
        diag = [q[i][i - d] for i in range(n) if 0 <= i - d < n]
        anti = [q[i][d + n - 1 - i] for i in range(n) if 0 <= d + n - 1 - i < n]
        F += [z3.AtMost(*l, 1) for l in (diag, anti) if len(l) > 1]
    return q, F

n = 14
q, F = reinas(n)
pares = [(j, k) for j in range(n) for k in range(n)]   # ¿hay solución con las dos primeras reinas en (0, j) y (1, k)?

t = time.perf_counter(); nuevo = []
for j, k in pares:                                      # 1) un solver nuevo por consulta
    s = z3.Solver(); s.add(F); s.add(q[0][j], q[1][k]); nuevo.append(s.check() == z3.sat)
t_nuevo = time.perf_counter() - t

s = z3.Solver(); s.add(F)                               # 2) un solver, consultas con suposiciones
t = time.perf_counter(); sup = [s.check(q[0][j], q[1][k]) == z3.sat for j, k in pares]
t_sup = time.perf_counter() - t

s = z3.Solver(); s.add(F)                               # 3) un solver, consultas con push/pop
t = time.perf_counter(); pp = []
for j, k in pares:
    s.push(); s.add(q[0][j], q[1][k]); pp.append(s.check() == z3.sat); s.pop()
t_pp = time.perf_counter() - t

assert nuevo == sup == pp
print(f'{len(pares)} consultas, {sum(nuevo)} satisfacibles')
print(f'tiempo con solver nuevo / con suposiciones = {t_nuevo / t_sup:.1f}')
print(f'tiempo con solver nuevo / con push-pop     = {t_nuevo / t_pp:.1f}')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

All three give the same 156 satisfiable answers out of 196, but the reused solver is over an order of magnitude faster (16 to 23 times in our runs, depending on variant and machine load). The 196 queries share nearly everything: row, column and diagonal constraints and CDCL learning. A new solver preprocesses 2⋅142 \cdot 14 cardinality constraints and rediscovers the same conflicts 196 times.

Unsatisfiable cores

Where cores come from

A solver does not search for a core: it emerges from the refutation. In CDCL with assumptions, when conflict forces an assumption to be undone, final analysis traverses the implication graph backward and collects assumptions it depends on (MiniSat calls this analyzeFinal). Build a transparent DPLL version: each assigned literal carries its assumption dependencies. An assumption depends on itself; a decision on none; a literal implied by a clause on the union of dependencies of that clause’s false literals. A conflict depends on the union of its literals’ dependencies, and when both branches of a decision fail, the decision refutation depends on both unions. Induction on the search tree shows each refuted node with dependencies DD has F∪D∪{decisiones del camino}F \cup D \cup \{\text{decisiones del camino}\} unsatisfiable; the root has no decisions, so DD is a core.

[ ]A solver with assumptions and coresBrowser
class Solver:
    """DPLL con suposiciones. Si check() responde unsat, core() da las suposiciones que usó la refutación."""
    def __init__(self):
        self.clausulas, self.nvars, self.llamadas = [], 0, 0
        self._nucleo, self._modelo = set(), None

    def nueva_var(self):
        self.nvars += 1
        return self.nvars

    def add(self, clausula):
        self.clausulas.append(list(clausula))
        self.nvars = max([self.nvars] + [abs(l) for l in clausula])

    def _propaga(self, val, dep):
        """Propagación unitaria. dep[v]: suposiciones de las que depende el valor de v. Devuelve las del conflicto."""
        cambio = True
        while cambio:
            cambio = False
            for c in self.clausulas:
                libres, d = [], set()
                for l in c:
                    v = val.get(abs(l))
                    if v is None:
                        libres.append(l)
                    elif v == (l > 0):
                        break                                  # cláusula satisfecha
                    else:
                        d |= dep[abs(l)]                       # literal falso: hereda sus dependencias
                else:                                          # ningún literal verdadero
                    if not libres:
                        return d                               # conflicto
                    if len(libres) == 1:
                        l = libres[0]
                        val[abs(l)], dep[abs(l)] = l > 0, d    # implicado por la cláusula
                        cambio = True
        return None

    def _dpll(self, val, dep):
        conflicto = self._propaga(val, dep)
        if conflicto is not None:
            return conflicto
        v = next((v for v in range(1, self.nvars + 1) if v not in val), None)
        if v is None:
            self._modelo = dict(val)
            return None
        usadas = set()
        for b in (True, False):                                # una decisión no depende de ninguna suposición
            r = self._dpll({**val, v: b}, {**dep, v: set()})
            if r is None:
                return None
            usadas |= r                                        # la refutación de v y la de ¬v se combinan
        return usadas

    def check(self, suposiciones=()):
        self.llamadas += 1
        val, dep = {}, {}
        for a in suposiciones:
            if abs(a) in val and val[abs(a)] != (a > 0):
                self._nucleo = dep[abs(a)] | {a}
                return 'unsat'
            val[abs(a)], dep[abs(a)] = a > 0, {a}
        r = self._dpll(val, dep)
        if r is None:
            return 'sat'
        self._nucleo = r
        return 'unsat'

    def core(self):
        return set(self._nucleo)

    def model(self):
        return self._modelo

def minimiza(s, nucleo):
    """Minimización por eliminación: una llamada por elemento del núcleo."""
    nucleo, i = list(nucleo), 0
    while i < len(nucleo):
        if s.check(nucleo[:i] + nucleo[i + 1:]) == 'unsat':
            nucleo.pop(i)                                      # sobraba
        else:
            i += 1                                             # imprescindible
    return nucleo

# x = 1, p = 2, y = 3, w = 4. Cada cláusula lleva un selector: (C ∨ ¬s) y se supone s.
clausulas = {'A': [-1, 2], 'B': [-1, -2],                      # x → p, x → ¬p: x tiene que ser falsa
             'E': [3, 4], 'F': [3, -4], 'G': [-3, 4], 'H': [-3, -4]}   # las cuatro combinaciones de y, w
s = Solver()
s.nvars = 4                                                    # las variables 1 a 4 ya están en uso
sel = {}
for nombre, c in clausulas.items():
    sel[nombre] = s.nueva_var()
    s.add(c + [-sel[nombre]])
nombre_de = {v: k for k, v in sel.items()}
print(s.check(list(sel.values())))
crudo = sorted(nombre_de[a] for a in s.core())
print('núcleo devuelto:', crudo)
mus = sorted(nombre_de[a] for a in minimiza(s, sorted(s.core())))
print('tras minimizar:', mus, '| llamadas en total:', s.llamadas)

The example exposes this. Clauses E,F,G,HE, F, G, H alone are unsatisfiable (all four sign combinations over y,wy, w), but DPLL first decides xx. In branch x=1x = 1, AA and BB immediately conflict; in branch x=0x = 0, AA and BB are satisfied and the refutation uses E,F,G,HE, F, G, H. Their union {A,B,E,F,G,H}\{A, B, E, F, G, H\} is a valid but nonminimal core: AA and BB were included only because of decision order. Six minimization calls reduce it to {E,F,G,H}\{E, F, G, H\}, seven including the first.

This is not a DPLL defect: any solver’s core reflects its refutation path. Programming Z3 says solvers do not return minimal cores by default. Z3 can minimize them (set('core.minimize', True) in its SMT core); the lab compares manual minimization.

Minimizing by deletion

Proof

MM is always unsatisfiable: initially so, and cic_i is removed only if the rest remains unsatisfiable. Let c∈Mc \in M be final and McM_c the value of MM when testing cc. Since cc remained, Mc∖{c}M_c \setminus \{c\} is satisfiable. Only elements are later removed, so M∖{c}⊆Mc∖{c}M \setminus \{c\} \subseteq M_c \setminus \{c\}, and a subset of a satisfiable set is satisfiable (any model of the larger satisfies the smaller). Removing any element of MM thus makes it satisfiable: a MUS. Each element of KK is tested once: nn calls.

∎

The proof’s monotonicity (subsets of satisfiable sets are satisfiable) also avoids checking 2n2^n subsets for minimality: nn single deletions suffice. Two improvements are common. Core refinement: when M∖{ci}M \setminus \{c_i\} is unsatisfiable, replace MM by that call’s possibly much smaller core, avoiding tests of dropped elements. QuickXplain (Junker, 2004) recursively halves the core and needs about klog⁡(n/k)k \log(n/k) calls when the MUS has kk elements, much less than nn for small kk. A minimum-cardinality core is harder: deciding whether a set is a MUS is already DPD^P-complete (Papadimitriou and Wolfe, 1988); generally many must be explored.

Explaining and repairing a conflict

A core explains one cause of conflict. Repair requires the dual question: which rules to remove.

Proof

If CC is a correction set and some MUS MM does not intersect CC, then M⊆F∖CM \subseteq F \setminus C, and F∖CF \setminus C containing an unsatisfiable set would be unsatisfiable: contradiction. Conversely, if CC hits every MUS and F∖CF \setminus C were unsatisfiable, it would contain a MUS (remove elements while unsatisfiable; FF is finite), which would not intersect CC. The second sentence applies the first to minimality and cardinality.

∎

This appears in Reiter’s (1987) model-based diagnosis and underlies enumeration algorithms by Liffiton and Sakallah (2008). Practically, removing one rule from the solver’s core does not repair other cores. Hit them all, either knowing them or solving the corresponding optimization problem (MaxSAT next).

InteractiveUnsatisfiable-core explorer
Unsatisfiable. Start with the trivial core: all 10 active rules. Replay deletion-based minimization: each step removes a rule and asks whether the rest remains unsatisfiable.
All minimal cores (6)
{R1, R2, R3}
{R1, R4, R5}
{R6, R7, R9}
{R1, R3, R5, R10}
{R1, R4, R6, R7, R8}
{R1, R3, R6, R7, R8, R10}
Minimal repairs
remove {R1, R6}
remove {R1, R7}
remove {R1, R9}
Every repair hits every minimal core: removing one rule from the found core is not enough if others exist.
  • in current core
  • rule being tested for removal
  • minimal repair
0 / 10
Deletion order
Solver calls0 of 10
Core size10
Distinct minimal cores6
Minimal repairremove 2 rules
Ten application dependency rules over five decisions (web 1 or 2, orm 1 or 2, Python 3.8 or 3.12, ssl 1 or 3, with or without payments). Everything is computed in your browser over 32 combinations. All ten rules are unsatisfiable: play deletion minimization and see its core in R1-to-R10 order, then change order. Right: six minimal cores and three minimal repairs. Remove R2, in the R10-to-R1 core: does it fix anything? Find a two-rule repair without looking at the list and identify which rule occurs in five of six cores.

The cell reproduces the explorer with the previous solver: first returned core, deletion in both orders, all MUSes by brute force over subsets, and minimal repairs.

[ ]Package rules: cores, MUSes and repairsBrowser
from itertools import combinations

# 1 web 2 · 2 orm 2 · 3 Python 3.12 · 4 ssl 3 · 5 módulo de pagos (falsa: web 1, orm 1, Python 3.8, ssl 1, sin pagos)
reglas = {
    'R1': [[1]],        # la aplicación necesita web 2
    'R2': [[-2]],       # requirements.txt fija orm 1
    'R3': [[-1, 2]],    # web 2 depende de orm 2
    'R4': [[-1, 3]],    # web 2 exige Python 3.12
    'R5': [[-3]],       # el servidor solo tiene Python 3.8
    'R6': [[5]],        # hay que instalar el módulo de pagos
    'R7': [[-5, -4]],   # el módulo de pagos solo funciona con ssl 1
    'R8': [[-3, 4]],    # Python 3.12 se compila con ssl 3
    'R9': [[4]],        # seguridad exige ssl 3
    'R10': [[-2, 3]],   # orm 2 exige Python 3.12
}
s = Solver(); s.nvars = 5
sel = {}
for r, cs in reglas.items():
    sel[r] = s.nueva_var()
    for c in cs:
        s.add(c + [-sel[r]])
regla_de = {v: k for k, v in sel.items()}
nombres = lambda sels: [regla_de[a] for a in sels]

print('todas:', s.check(list(sel.values())), '| núcleo del solver:', sorted(nombres(s.core()), key=lambda r: int(r[1:])))
for orden, lista in [('R1 a R10', list(sel.values())), ('R10 a R1', list(sel.values())[::-1])]:
    s.llamadas = 0
    print(f'eliminación de {orden} sobre las diez:', nombres(minimiza(s, lista)), f'({s.llamadas} llamadas)')

def satisfacible(rs):
    return s.check([sel[r] for r in rs]) == 'sat'
todas = list(reglas)
muses = []
for k in range(1, len(todas) + 1):
    for sub in combinations(todas, k):
        if not any(set(m) <= set(sub) for m in muses) and not satisfacible(sub):
            muses.append(sub)
print(len(muses), 'MUS:', [' '.join(m) for m in muses])
for k in range(1, len(todas) + 1):
    reparaciones = [q for q in combinations(todas, k) if satisfacible([r for r in todas if r not in q])]
    if reparaciones:
        print('reparaciones mínimas:', reparaciones)
        break
print('¿cada reparación toca todos los MUS?', all(set(q) & set(m) for q in reparaciones for m in muses))

With all ten rules the solver directly returns {R1,R2,R3}\{R1, R2, R3\}, already a MUS. Deleting from all ten depends on order: R1 to R10 ends at {R6,R7,R9}\{R6, R7, R9\} (ssl conflict), R10 to R1 at {R1,R2,R3}\{R1, R2, R3\} (orm), each taking 10 calls. Neither is “the” conflict: six MUSes have sizes 3 to 6, with R1 in five. Minimal repairs remove two rules: {R1,R6}\{R1, R6\}, {R1,R7}\{R1, R7\} or {R1,R9}\{R1, R9\}, giving up web 2 plus payments, its ssl constraint, or required ssl 3. All hit the six MUSes as the theorem says.

Lab: firewall cores and repair with Z3

The lab uses Z3 for a firewall policy with thirteen requirements on SSH and HTTP ports (16-bit vectors), administrator IP (32 bits), and access-list prefix (integer), each with a selector. Besides deletion, enumerate all MUSes and MCSes with MARCO (Liffiton, Previti, Malik and Marques-Silva, 2016): a second “map” solver proposes subsets containing no known MUS and hitting every known MCS; unsatisfiable subsets minimize to new MUSes, satisfiable ones expand to MSSes whose complements are new MCSes. Each answer adds a map clause excluding the corresponding region, so the process ends when the map is unsatisfiable.

[ ]Firewall: Z3 core, MARCO and minimum repairLocal GPU
import z3, time, itertools

ssh, http = z3.BitVecs('ssh_port http_port', 16)
admin = z3.BitVec('admin_ip', 32)
prefijo = z3.Int('prefijo')

def en_red(ip, base, bits):
    mascara = (0xFFFFFFFF << (32 - bits)) & 0xFFFFFFFF
    return ip & mascara == base & mascara

reglas = {
    'F1':  ('SSH fuera del puerto 22',                  ssh != 22),
    'F2':  ('SSH en un puerto privilegiado (< 1024)',   z3.ULT(ssh, 1024)),
    'F3':  ('el balanceador solo reenvía 22 y 2222',    z3.Or(ssh == 22, ssh == 2222)),
    'F4':  ('administración desde 10.0.0.0/8',          en_red(admin, 0x0A000000, 8)),
    'F5':  ('administración desde 192.168.0.0/16',      en_red(admin, 0xC0A80000, 16)),
    'F6':  ('prefijo de la ACL de /24 o más fino',      prefijo >= 24),
    'F7':  ('la ACL cubre la VPN entera (/16 o más)',   prefijo <= 16),
    'F8':  ('la aplicación antigua escucha en 2222',    http == 2222),
    'F9':  ('SSH y HTTP en puertos distintos',          ssh != http),
    'F10': ('HTTP fuera de los puertos privilegiados',  z3.UGE(http, 1024)),
    'F11': ('HTTP por encima de 8000',                  z3.UGT(http, 8000)),
    'F12': ('SSH y HTTP en el mismo bloque de 1000',    z3.UDiv(ssh, 1000) == z3.UDiv(http, 1000)),
    'F13': ('SSH por debajo de HTTP',                   z3.ULT(ssh, http)),
}
sel = {nombre: z3.Bool(nombre) for nombre in reglas}
s = z3.Solver()
for nombre, (_, f) in reglas.items():
    s.add(z3.Implies(sel[nombre], f))     # equivale a s.assert_and_track(f, sel[nombre])
todas = list(sel.values())
print('todas las reglas:', s.check(todas))
crudo = s.unsat_core()
print('núcleo de Z3:', sorted(map(str, crudo), key=lambda t: int(t[1:])))

def minimiza(s, nucleo):
    nucleo, i = list(nucleo), 0
    while i < len(nucleo):
        if s.check(nucleo[:i] + nucleo[i + 1:]) == z3.unsat:
            nucleo.pop(i)
        else:
            i += 1
    return nucleo

def crece(s, semilla, todas):                     # amplía un conjunto satisfacible hasta uno maximal (MSS)
    mss = list(semilla)
    for p in todas:
        if p not in mss and s.check(mss + [p]) == z3.sat:
            mss.append(p)
    return mss

def marco(s, todas):
    """Enumera todos los MUS y todas las MCS (Liffiton et al., 2016) con un solver «mapa» sobre los selectores."""
    mapa, muses, mcses = z3.Solver(), [], []
    while mapa.check() == z3.sat:
        m = mapa.model()
        semilla = [p for p in todas if not z3.is_false(m.eval(p, model_completion=True))]
        if s.check(semilla) == z3.sat:
            mcs = [p for p in todas if p not in crece(s, semilla, todas)]
            mcses.append(mcs)
            mapa.add(z3.Or(mcs))                       # todo conjunto futuro debe recuperar algo de esta MCS
        else:
            mus = minimiza(s, s.unsat_core())
            muses.append(mus)
            mapa.add(z3.Or([z3.Not(p) for p in mus]))  # y ninguno puede contener entero este MUS
    return muses, mcses

orden = lambda L: sorted(map(str, L), key=lambda t: int(t[1:]))
muses, mcses = marco(s, todas)
print(f'{len(muses)} MUS:')
for m in sorted(muses, key=len):
    print('  ', orden(m), '·', '; '.join(reglas[n][0] for n in orden(m)))
minimo = min(map(len, mcses))
print(f'{len(mcses)} MCS; la más pequeña tiene {minimo} reglas ({sum(len(c) == minimo for c in mcses)} de ese tamaño)')

o = z3.Optimize()                                  # reparación óptima: MaxSAT sobre los selectores
for nombre, (_, f) in reglas.items():
    o.add(z3.Implies(sel[nombre], f))
    o.add_soft(sel[nombre], 1)
o.check(); m = o.model()
print('Optimize quita:', [n for n in sel if z3.is_false(m.eval(sel[n], model_completion=True))])

activas, quitadas = list(todas), []                # reparación voraz: quitar una regla de cada núcleo
while s.check(activas) == z3.unsat:
    mus = minimiza(s, s.unsat_core())
    activas.remove(mus[0]); quitadas.append(str(mus[0]))
print('la reparación voraz quita:', quitadas)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The first query returns core {F6,F7}\{F6, F7\} (a prefix cannot be both ≥24\geq 24 and ≤16\leq 16), just one of the policy’s 12 MUSes. There are obvious pairs ({F4,F5}\{F4, F5\}, {F8,F11}\{F8, F11\}), triples ({F1,F2,F3}\{F1, F2, F3\}: not 22, below 1024, and 22 or 2222), and four-requirement conflicts hard to spot such as {F1,F3,F8,F9}\{F1, F3, F8, F9\}: if SSH cannot use 22 and the balancer accepts only 22 and 2222, SSH uses 2222, where the legacy app listens. MARCO also finds 44 MCSes, smallest of 5 requirements, with 36 of that size; Optimize returns one. Greedily removing one requirement per encountered core removes one extra in our run (6): it looks at one core at a time, whereas duality requires hitting all at once.

Optimization: MaxSAT and optimization modulo theories

Unit-weight MaxSAT is NP-hard (it contains SAT: optimum 0 iff all clauses are satisfiable). Since cardinality encodings express “at most kk false soft clauses”, a direct solution searches linearly over kk. Add relaxation variable rCr_C to each soft clause (becoming C∨rCC \vee r_C), and ask for a model with ∑rC≤k\sum r_C \leq k. Decreasing kk from above (SAT–UNSAT) improves each model; increasing from 0 (UNSAT–SAT) makes the first sat optimal. Core-guided algorithms use unsatisfiable calls more intelligently: they say not only “kk is insufficient” but which soft clauses conflict, relaxing only those. Fu–Malik was first.

Fu–Malik algorithm

Fu and Malik (2006) proposed the following unit-weight partial MaxSAT loop over a solver with assumptions:

  1. Each soft clause CC has selector aCa_C: add C∨¬aCC \vee \neg a_C and assume aCa_C.
  2. If check({aC})\mathrm{check}(\{a_C\}) is sat, return the model and accumulated cost.
  3. If unsat, core KK (restricted to selectors) identifies soft clauses incompatible with hard ones. If K=∅K = \emptyset, hard clauses are unsatisfiable. Otherwise for each C∈KC \in K add a fresh relaxation variable bCb_C (the soft clause becomes C∨bCC \vee b_C with fresh selector), add a hard exactly-one constraint on this core’s bCb_C variables, increase cost by one, and return to step 2.

“Exactly one” means one incompatible soft clause in this group may be violated, no more. A soft clause can occur in several cores and accumulate relaxation variables. In the analyzed version, each relaxed clause is a new soft clause of the transformed problem.

Proof

(≤\leq) Let II be optimal for (H,S)(H, S). Since I⊨HI \models H and H∪KH \cup K is unsatisfiable, II falsifies at least one C∗∈KC^\ast \in K. Extend II with bC∗=1b_{C^\ast} = 1 and all other bC=0b_C = 0: it satisfies HH and the new constraint, hence H′H'. Soft clauses outside KK are unchanged; those in KK except C∗C^\ast retain their value (their bb is 0); C∗∨bC∗C^\ast \vee b_{C^\ast} becomes satisfied. Cost falls exactly one, and opt(H′,S′)≤opt(H,S)−1\mathrm{opt}(H', S') \leq \mathrm{opt}(H, S) - 1.

(≥\geq) Let I′I' satisfy H′H'. Restricted to old variables it satisfies HH. Exactly one bC∗b_{C^\ast} is 1. Soft clauses outside KK and C∈KC \in K with bC=0b_C = 0 have the same value in both instances; the only clause that can hold in S′S' but fail in SS is C∗C^\ast. Thus costeS(I′)≤costeS′(I′)+1\mathrm{coste}_S(I') \leq \mathrm{coste}_{S'}(I') + 1 and, taking optimal I′I', opt(H,S)≤opt(H′,S′)+1\mathrm{opt}(H, S) \leq \mathrm{opt}(H', S') + 1.

For the algorithm: a satisfiable call satisfies all current soft and hard clauses together, so current optimum is 0. An unsatisfiable call with HH satisfiable has a soft clause in its core, and by the above the optimum drops by one. Starting at opt(H,S)\mathrm{opt}(H, S) and never negative, there are exactly opt(H,S)\mathrm{opt}(H, S) unsatisfiable calls before the first satisfiable one. The final model violates exactly that many original soft clauses: each violation needs its own true bb, each bb belongs to one group, and each group has one true bb, so violations are at most group count and at least opt\mathrm{opt}.

∎

The core need not be minimal. A large core gives weaker relaxation (one of many can be violated) and adds variables, but the proof only needs H∪KH \cup K unsatisfiable. Minimization costs calls and often saves constraint size, not iterations, which always equal the optimum.

InteractiveFu–Malik step by step
Each active preference has a selector, and all selectors are checked as assumptions. Lower bound: 0. The brute-force optimum is 3.
Soft clauses (weight 1) with their relaxation variables
Added hard constraints
none yet
Schedule (when finished)
Monday morning
?
Monday afternoon
?
Tuesday morning
?
Tuesday afternoon
?
0 / 4
Lower bound (cores)0
Brute-force optimum3
Solver calls0 (4 total)
Relaxation variables0
Three people (Ana, Bea, Ciro) and four shifts (Monday and Tuesday, morning and afternoon). Hard: exactly one covers each shift, no one works both shifts of a day, everyone works some shift. Soft: eight unit-weight preferences. Fu–Malik runs in your browser on the earlier core-producing DPLL; the reference optimum enumerates 4096 assignments. Play calls: each core is highlighted, each preference in it gains a relaxation variable and an exactly-one constraint appears. Which preference ends with two relaxation variables, and why? Enable minimization: do cores, cost or call count change? Remove preferences by clicking and check the final lower bound always matches brute force.
[ ]Fu–Malik from scratch, checked against brute forceBrowser
import itertools, random, time

def fu_malik(duras, blandas, minimizar=False):
    """MaxSAT parcial con pesos 1. Devuelve (coste, modelo, núcleos, llamadas); coste None si las duras son insatisfacibles."""
    s = Solver()
    for c in duras:
        s.add(c)
    s.nvars = max([abs(l) for c in duras + blandas for l in c] + [0])
    blandas = [list(c) for c in blandas]
    sel = []
    for c in blandas:                                  # blanda i activa  <=>  se supone sel[i]
        sel.append(s.nueva_var())
        s.add(c + [-sel[-1]])
    nucleos = []
    while True:
        if s.check(sel) == 'sat':
            return len(nucleos), s.model(), nucleos, s.llamadas
        nucleo = minimiza(s, sorted(s.core())) if minimizar else s.core()
        K = [i for i, a in enumerate(sel) if a in nucleo]
        if not K:
            return None, None, nucleos, s.llamadas     # el núcleo solo tiene duras
        nucleos.append(K)
        bs = []
        for i in K:
            s.add([-sel[i]])                           # retira la versión anterior de la blanda i
            b = s.nueva_var()
            blandas[i] = blandas[i] + [b]              # ... y la relaja con una variable nueva
            sel[i] = s.nueva_var()
            s.add(blandas[i] + [-sel[i]])
            bs.append(b)
        s.add(bs)                                      # exactamente una de las b nuevas:
        for p, q in itertools.combinations(bs, 2):     # al menos una y, por pares, como mucho una
            s.add([-p, -q])

def fuerza_bruta(duras, blandas, n):
    mejor = None
    for bits in itertools.product([False, True], repeat=n):
        cumple = lambda c: any(bits[abs(l) - 1] == (l > 0) for l in c)
        if all(map(cumple, duras)):
            k = sum(not cumple(c) for c in blandas)
            mejor = k if mejor is None else min(mejor, k)
    return mejor

# Turnos: Ana, Bea, Ciro × lunes mañana, lunes tarde, martes mañana, martes tarde
P, T = ['Ana', 'Bea', 'Ciro'], ['LM', 'LT', 'MM', 'MT']
X = {(p, t): 1 + i * 4 + j for i, p in enumerate(P) for j, t in enumerate(T)}
duras = []
for t in T:
    duras.append([X[p, t] for p in P])                                      # alguien cubre el turno
    duras += [[-X[p, t], -X[q, t]] for p, q in itertools.combinations(P, 2)]  # y solo una persona
for p in P:
    duras += [[-X[p, 'LM'], -X[p, 'LT']], [-X[p, 'MM'], -X[p, 'MT']]]      # nadie dobla en un día
    duras.append([X[p, t] for t in T])                                      # todos trabajan algún turno
prefs = [('Ana', 'MM', True), ('Ana', 'MT', True), ('Bea', 'MM', True), ('Bea', 'LT', True),
         ('Bea', 'MT', False), ('Ciro', 'MM', True), ('Ciro', 'LT', True), ('Ciro', 'LM', False)]
blandas = [[X[p, t] if quiere else -X[p, t]] for p, t, quiere in prefs]

for minimizar in (False, True):
    coste, modelo, nucleos, llamadas = fu_malik(duras, blandas, minimizar)
    print(f'minimizar={minimizar}: coste {coste}, núcleos {[[f"s{i + 1}" for i in K] for K in nucleos]}, {llamadas} llamadas')
print('óptimo por fuerza bruta:', fuerza_bruta(duras, blandas, 12))
print('cuadrante:', {t: p for (p, t), v in X.items() if modelo[v]})
print('preferencias violadas:', [f's{i + 1}' for i, c in enumerate(blandas) if modelo[abs(c[0])] != (c[0] > 0)])

# Comprobación en instancias aleatorias: el coste de Fu-Malik coincide con la fuerza bruta
rnd = random.Random(1); t0 = time.perf_counter(); casos = 0
for _ in range(300):
    n = rnd.randint(3, 8)
    lit = lambda: rnd.choice([1, -1]) * rnd.randint(1, n)
    d = [[lit() for _ in range(rnd.randint(1, 3))] for _ in range(rnd.randint(0, 4))]
    b = [[lit() for _ in range(rnd.randint(1, 2))] for _ in range(rnd.randint(1, 8))]
    assert fu_malik(d, b)[0] == fuerza_bruta(d, b, n)
    casos += 1
print(f'{casos} instancias aleatorias: Fu-Malik = fuerza bruta en todas ({time.perf_counter() - t0:.2f} s)')

The three cores are {s4,s7}\{s4, s7\} (Bea and Ciro both want Monday afternoon), {s1,s3}\{s1, s3\} (Ana and Bea, Tuesday morning), and {s1,s3,s6}\{s1, s3, s6\}: after the second, one of s1s1 or s3s3 may be violated, but Ciro also wants Tuesday morning and only one of three can hold. Thus s1s1 and s3s3 each end with two relaxation variables. Cost is 3, matching brute force after exactly three unsatisfiable calls and one satisfiable call (4 total). With minimization cores were already minimal and unchanged but calls rise to 11: each deletion costs one per element. The final roster (Ana Monday morning and Tuesday afternoon, Bea Monday afternoon, Ciro Tuesday morning) violates s1s1, s3s3 and s7s7: three preferences, as many as cores. All 300 random instances, including unsatisfiable hard clauses, match brute force.

Weights, MaxRes and Z3

Fu–Malik does not directly handle weights: a core with soft weights 5 and 1 should not always raise cost by 1. Standard generalization WPM1 (Ansótegui, Bonet and Levy, 2009) takes the core’s minimum weight wmin⁡w_{\min}, duplicates each soft clause CC of weight wC>wmin⁡w_C > w_{\min} into a copy of weight wmin⁡w_{\min} (relaxed) and one of weight wC−wmin⁡w_C - w_{\min} (unchanged), then raises cost by wmin⁡w_{\min}. Programming Z3 describes reducing weighted assertions to unweighted MaxSAT by splitting core weights.

Z3 does not use Fu–Malik. Its default MaxSAT engine opt.maxsat_engine = maxres is MaxRes (Narodytska and Bacchus, 2014), also core-guided but with another transformation: rather than add one relaxation variable per soft clause and core plus exactly-one constraints, increase cost by one and replace the core’s kk soft clauses with k−1k - 1 new ones, Ci+1∨(C1∧⋯∧Ci)C_{i+1} \vee (C_1 \wedge \dots \wedge C_i) in basic form, via MaxSAT resolution: the first violated soft clause is paid for, each additional violation costs again. No exactly-one constraints, no accumulating relaxation variables, and much slower formula growth.

The lab compares Fu–Malik on incremental Z3 (PbEq for exactly-one) against Optimize with add_soft, first on the previous roster then eight people, fourteen two-shift days and 120 random preferences.

[ ]Fu–Malik with Z3 versus OptimizeLocal GPU
import itertools, random

def fu_malik_z3(duras, blandas):
    """Fu-Malik con un solo solver incremental de Z3. duras y blandas: fórmulas booleanas."""
    s = z3.Solver()
    s.add(duras)
    blandas = list(blandas)
    sel = [z3.Bool(f'a_{i}_0') for i in range(len(blandas))]
    for a, c in zip(sel, blandas):
        s.add(z3.Implies(a, c))
    nucleos, nuevo = [], itertools.count(1)
    while True:
        if s.check(sel) == z3.sat:
            return len(nucleos), s.model(), nucleos
        en_nucleo = set(map(str, s.unsat_core()))
        K = [i for i, a in enumerate(sel) if str(a) in en_nucleo]
        if not K:
            return None, None, nucleos
        nucleos.append(K)
        bs = []
        for i in K:
            k = next(nuevo)
            b = z3.Bool(f'b_{i}_{k}')
            blandas[i] = z3.Or(blandas[i], b)
            sel[i] = z3.Bool(f'a_{i}_{k}')         # selector nuevo; el anterior deja de suponerse
            s.add(z3.Implies(sel[i], blandas[i]))
            bs.append(b)
        s.add(z3.PbEq([(b, 1) for b in bs], 1))      # exactamente una

def turnos(personas, franjas, dias, prefs):
    x = {(p, t): z3.Bool(f'x_{p}_{t}') for p in personas for t in franjas}
    duras = [z3.PbEq([(x[p, t], 1) for p in personas], 1) for t in franjas]
    for p in personas:
        duras += [z3.AtMost(*[x[p, t] for t in franjas if t.startswith(d)], 1) for d in dias]
        duras.append(z3.Or([x[p, t] for t in franjas]))
    blandas = [x[p, t] if quiere else z3.Not(x[p, t]) for p, t, quiere in prefs]
    return x, duras, blandas

def coste(modelo, blandas, pesos=None):
    pesos = pesos or [1] * len(blandas)
    return sum(w for c, w in zip(blandas, pesos) if not z3.is_true(modelo.eval(c, model_completion=True)))

P, T = ['Ana', 'Bea', 'Ciro'], ['LM', 'LT', 'MM', 'MT']
prefs = [('Ana', 'MM', True), ('Ana', 'MT', True), ('Bea', 'MM', True), ('Bea', 'LT', True),
         ('Bea', 'MT', False), ('Ciro', 'MM', True), ('Ciro', 'LT', True), ('Ciro', 'LM', False)]
x, duras, blandas = turnos(P, T, ['L', 'M'], prefs)
c_fm, m, nuc = fu_malik_z3(duras, blandas)
print('Fu-Malik con Z3: coste', c_fm, '· núcleos', [[f's{i + 1}' for i in K] for K in nuc])
o = z3.Optimize(); o.add(duras)
for c in blandas:
    o.add_soft(c, 1)
o.check(); print('Optimize: coste', coste(o.model(), blandas))

# Más grande: 8 personas, 14 días con turno de mañana y de tarde, 120 preferencias al azar
rnd = random.Random(0)
P2 = [f'p{i}' for i in range(8)]; D2 = [f'd{j:02d}' for j in range(14)]
T2 = [d + s for d in D2 for s in 'MT']
prefs2 = [(rnd.choice(P2), rnd.choice(T2), rnd.random() < 0.5) for _ in range(120)]
x2, duras2, blandas2 = turnos(P2, T2, D2, prefs2)
t0 = time.perf_counter(); c_fm2, _, nuc2 = fu_malik_z3(duras2, blandas2); t_fm = time.perf_counter() - t0
o = z3.Optimize(); o.add(duras2)
for c in blandas2:
    o.add_soft(c, 1)
t0 = time.perf_counter(); o.check(); t_opt = time.perf_counter() - t0
print(f'grande: Fu-Malik coste {c_fm2} ({len(nuc2)} núcleos), Optimize coste {coste(o.model(), blandas2)}')
print(f'tiempo de Fu-Malik / tiempo de Optimize = {t_fm / t_opt:.1f}')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

On shifts, Z3 finds different cores from DPLL ({s1,s2}\{s1, s2\}: Ana cannot work both Tuesday shifts; {s3,s6}\{s3, s6\}; {s4,s7}\{s4, s7\}), but cost remains 3 as the theorem predicts: iteration count is core-independent. On the larger case both reach cost 29 and Fu–Malik needs exactly 29 cores; it is still over ten times slower than Optimize (about 18 times in our runs, machine-dependent). Python-loop overhead explains part; algorithm explains the rest: with 120 soft clauses and 29 overlapping cores, Fu–Malik accumulates relaxation variables and exactly-one constraints that MaxRes does not.

Multiple objectives: νZ

Z3’s optimizer was described as νZ (Bjørner, Phan and Fleckenstein, 2015). It supports weighted soft clauses and minimize/maximize objectives over linear-arithmetic or bit-vector terms. Programming Z3 describes three ways to combine objectives: lexicographic (lex, default: optimize and fix each in turn), independent (box: each alone), and Pareto (pareto: each check returns a different nondominated point). The cell uses weighted Bea preferences and six tasks on two machines, one fast and expensive, one twice as slow and less energy-hungry, with objectives “finish early” and “use little energy”.

[ ]Weights and multiple objectives with OptimizeLocal GPU
pesos = [3 if p == 'Bea' else 1 for p, _, _ in prefs]
o = z3.Optimize(); o.add(duras)
for c, w in zip(blandas, pesos):
    o.add_soft(c, w)
o.check(); m = o.model()
print('con peso 3 en las preferencias de Bea: coste', coste(m, blandas, pesos), '· violadas',
      [f's{i + 1}' for i, c in enumerate(blandas) if not z3.is_true(m.eval(c, model_completion=True))])

# OMT con dos objetivos: seis tareas en dos máquinas; A es rápida y gasta 3 por unidad de trabajo,
# B tarda el doble y gasta 2 por unidad de trabajo
d = [4, 3, 3, 2, 2, 1]
en_A = [z3.Bool(f'A{i}') for i in range(len(d))]
carga_A = z3.Sum([z3.If(a, di, 0) for a, di in zip(en_A, d)])
carga_B = z3.Sum([z3.If(a, 0, 2 * di) for a, di in zip(en_A, d)])
energia = z3.Sum([z3.If(a, 3 * di, 2 * di) for a, di in zip(en_A, d)])
fin = z3.Int('fin')                                   # instante en que acaba la última tarea
def optimiza(prioridad, objetivos):
    o = z3.Optimize(); o.set(priority=prioridad)
    o.add(fin >= carga_A, fin >= carga_B)
    hs = [o.minimize(fin if k == 'fin' else energia) for k in objetivos]
    if prioridad == 'pareto':
        frente = []
        while o.check() == z3.sat:
            frente.append(tuple(h.value().as_long() for h in hs))
        return sorted(frente)
    o.check()
    return tuple(h.value().as_long() for h in hs)
print('lex (fin, energía):', optimiza('lex', ['fin', 'energia']))
print('lex (energía, fin):', optimiza('lex', ['energia', 'fin']))
print('box (fin, energía):', optimiza('box', ['fin', 'energia']))
print('pareto (fin, energía):', optimiza('pareto', ['fin', 'energia']))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Weight 3 on Bea’s three preferences changes the optimum: cost 4, violating four unit-weight preferences (s1s1, s6s6, s7s7 and s8s8) rather than any of Bea’s, because violating one costs 3. For the tasks, 15 units of work give a clean tradeoff: all on the slow machine finishes at 30 using 30 energy; distributing to finish at 10 uses 40. Lexicographic order matters: (finish, energy) gives (10,40)(10, 40) and (energy, finish) (30,30)(30, 30). Mode box returns (10,30)(10, 30), individual optima that do not correspond to one solution: they are two different solutions. The Pareto front has 11 points, (10,40)(10, 40) to (30,30)(30, 30), with each 2 units of accepted extra time saving 1 energy. This can be integer programming, and its linear relaxation returns in performance diagnosis.

Quantifiers: why Z3 says unknown

So far everything was decidable: SAT, bit-vectors, quantifier-free linear arithmetic. With ∀\forall that ends. Validity in first-order logic with uninterpreted symbols is undecidable (Church and Turing, 1936). It is semidecidable: by Herbrand’s theorem, if universal formulas are unsatisfiable, some finite set of ground instances is already unsatisfiable, and a procedure generating instances eventually finds it. If satisfiable, generally no procedure can certify this (first-order satisfiability is not even semidecidable), and only infinite models may exist. With arithmetic and uninterpreted functions even that fails: Presburger arithmetic with one unary predicate is Π11\Pi^1_1-complete (Halpern, 1991). An SMT solver with quantifiers is therefore a heuristic instance searcher, and unknown is a legitimate answer.

E-matching and patterns

E-matching comes from the Simplify prover (Detlefs, Nelson and Saxe, 2005). Each quantifier has one or more patterns (triggers): terms containing every bound variable, not a variable alone. When a term matching a pattern modulo known equalities appears in the solver’s E-graph (congruence closure), instantiate with the resulting substitution. A multipattern {p1,p2}\{p_1, p_2\} requires both matches with the same variables. Efficiency depends on finding matches quickly in constantly changing E-graphs; de Moura and Bjørner (2007) compile patterns into code trees and index which patterns can match each new term.

The example is linked-list length, a recursive function axiomatized using uninterpreted functions next\mathrm{next} and len\mathrm{len}:

∀x.  x≠nil  →  len(x)=1+len(next(x)),len(nil)=0.\forall x.\; x \neq \mathrm{nil} \;\rightarrow\; \mathrm{len}(x) = 1 + \mathrm{len}(\mathrm{next}(x)), \qquad \mathrm{len}(\mathrm{nil}) = 0.

Candidate patterns are len(x)\mathrm{len}(x), next(x)\mathrm{next}(x), len(next(x))\mathrm{len}(\mathrm{next}(x)) and multipattern {len(x),next(x)}\{\mathrm{len}(x), \mathrm{next}(x)\}. {len(x)}\{\mathrm{len}(x)\} has a problem: each instance on term len(t)\mathrm{len}(t) creates len(next(t))\mathrm{len}(\mathrm{next}(t)), matching the pattern again indefinitely. This is a matching loop. Z3 limits it using cost: each term created by an instance inherits a generation one above its creator, default instance cost is weight + generation, and instances above qi.eager_threshold (10) are deferred; lab statistics show those above qi.lazy_threshold (20) are not instantiated and counted as missed. With omitted instances Z3 cannot answer sat and returns unknown.

InteractiveThe instantiation loop
∀x.  x≠nil  →  len(x)=1+len(next(x)){len(x)}\forall x.\; x \neq \mathrm{nil} \;\rightarrow\; \mathrm{len}(x) = 1 + \mathrm{len}(\mathrm{next}(x))\qquad \{\mathrm{len}(x)\}
Query terms: b, nil, len(b) and len(nil). No next(·) term exists. Press ▶ for the first round.
lenbnot instantiated
lennilfalse guard
  • query term
  • term created by an instance (color by round)
  • already instantiated class
Each box is a class of equal terms (for example, next(next(a)) and nil are the same); the arrow is next. Instance x := c adds terms len(c), next(c) and len(next(c)).
round 0
Query
Instantiation
Pattern
Instances0
len(·) terms2
Resultin progress
An explicit browser simulation of the list-length axiom. Each box is an equality class (next(next(a)) and nil are identical in the two-cell list), arrows are next, and len appears when that class's len term exists, colored by creating round. E-matching instantiates all pattern matches each round. Start with the open list and {len(x)}, already three rounds: each instance created another matching term; play to the end. Switch to {len(x), next(x)}: how many instances and what does Z3 say? Switch to the two-cell list and test all four patterns, including {len(next(x))}, matching len(nil) because nil is next(next(a)). Enable MBQI for both: the candidate model assigns defaults to free values and instantiates only where the axiom fails.

For the two-cell list (a≠nila \neq \mathrm{nil}, next(a)≠nil\mathrm{next}(a) \neq \mathrm{nil}, next(next(a))=nil\mathrm{next}(\mathrm{next}(a)) = \mathrm{nil}), every pattern yields the two required instances x:=ax := a and x:=next(a)x := \mathrm{next}(a), immediately contradicting len(a)≠2\mathrm{len}(a) \neq 2. Match x:=nilx := \mathrm{nil} of {len(x)}\{\mathrm{len}(x)\} contributes nothing: guard nil≠nil\mathrm{nil} \neq \mathrm{nil} is false. Pattern {len(next(x))}\{\mathrm{len}(\mathrm{next}(x))\} is curious: initially no term written len(next(⋅))\mathrm{len}(\mathrm{next}(\cdot)) exists, but len(nil)\mathrm{len}(\mathrm{nil}) matches modulo equality nil=next(next(a))\mathrm{nil} = \mathrm{next}(\mathrm{next}(a)) with x:=next(a)x := \mathrm{next}(a). That is “modulo E”.

For the open list (only len(b)>5\mathrm{len}(b) > 5 is known), tight patterns find no matching term because no next(⋅)\mathrm{next}(\cdot) exists, and E-matching stops with no instances. Stopping differs from answering: E-matching cannot conclude sat because it cannot know whether the axiom holds for infinitely many unexamined xx. MBQI addresses that.

MBQI: instantiate where the model fails

Ge and de Moura (2009) propose: solve the quantifier-free part with accumulated instances to obtain candidate model MM, with finite universe and function tables. For each ∀x. φ(x)\forall \vb{x}.\, \varphi(\vb{x}) construct φM\varphi^M, replacing uninterpreted symbols by their tables in MM, and ask whether ¬φM(x)\neg\varphi^M(\vb{x}) is satisfiable, a quantifier-free query. If not, MM satisfies the quantifier. Otherwise the witness identifies where MM violates the axiom; translate it into ground terms t\vb{t} and add instance φ(t)\varphi(\vb{t}) to exclude the model. If a model passes all checks, answer sat with it. The authors identify complete fragments, notably essentially uninterpreted formulas whose bound variables appear only as arguments of uninterpreted symbols. Programming Z3 describes MBQI as powerful when the space of instantiation terms is finite.

MBQI searches for finite models, setting its limit. With query b≠nil∧len(b)<0b \neq \mathrm{nil} \wedge \mathrm{len}(b) < 0:

  • In every finite model, len(b)≥1\mathrm{len}(b) \geq 1. Follow b=e0,e1=next(e0),…b = e_0, e_1 = \mathrm{next}(e_0), \dots If the chain reaches nil\mathrm{nil} at step m≥1m \geq 1 without earlier contact, applying the axiom to e0,…,em−1e_0, \dots, e_{m-1} yields len(b)=m+len(nil)=m≥1\mathrm{len}(b) = m + \mathrm{len}(\mathrm{nil}) = m \geq 1. If never reached, finiteness forces cycle ei=eje_i = e_j with i<ji < j all distinct from nil\mathrm{nil}; summing the axiom from ii to j−1j-1 yields len(ei)=(j−i)+len(ei)\mathrm{len}(e_i) = (j - i) + \mathrm{len}(e_i), impossible.
  • But the query is satisfiable: in infinite model e0=b,e1,e2,…e_0 = b, e_1, e_2, \dots, with next(ek)=ek+1\mathrm{next}(e_k) = e_{k+1} and len(ek)=−1−k\mathrm{len}(e_k) = -1 - k, the axiom holds for every xx.

No finite model exists and no finite instance set is contradictory: neither E-matching nor MBQI can finish with an answer. unknown or timeout is all a solver can report.

Lab: quantifiers without surprises

The cell reproduces interactive scenarios in Z3 and records quantifier statistics. Each query uses a fresh Z3 context (z3.Context()): with quantifiers Z3 is sensitive to logically irrelevant details (assertion order, names, prior work in the same process), called instability and measured in real verifiers by Zhou et al. (2023). The last parts show a loop through two axioms: inferred patterns block obvious one-axiom loops (pi.block_loop_patterns, default enabled), but not cross-axiom loops.

[ ]Patterns, MBQI and a loop between two axiomsLocal GPU
import z3, time

def resuelve(construye, mbqi=True, ematching=True, timeout=5000):
    """construye(ctx) devuelve la lista de fórmulas; cada consulta usa un contexto de Z3 nuevo."""
    ctx = z3.Context()
    s = z3.Solver(ctx=ctx)
    s.set('auto_config', False, 'mbqi', mbqi, 'ematching', ematching, 'timeout', timeout)
    s.add(construye(ctx))
    t = time.perf_counter(); r = s.check(); t = time.perf_counter() - t
    st = s.statistics()
    q = {k: st.get_key_value(k) for k in st.keys() if k in ('quant instantiations', 'max generation', 'missed quant instantiations')}
    motivo = s.reason_unknown() if r == z3.unknown else ''
    motivo = ' (incomplete quantifiers)' if 'incomplete' in motivo else f' ({motivo})' if motivo else ''
    return f'{str(r) + motivo:<34} {t:6.3f} s  {q}'

def lista(patron, consulta):
    def construye(ctx):
        L = z3.DeclareSort('Lista', ctx)
        nil, a, b, x = z3.Consts('nil a b x', L)
        nxt = z3.Function('next', L, L); ln = z3.Function('len', L, z3.IntSort(ctx))
        pats = {'{len(x)}': [ln(x)], '{next(x)}': [nxt(x)], '{len(x), next(x)}': [z3.MultiPattern(ln(x), nxt(x))],
                '{len(next(x))}': [ln(nxt(x))]}[patron]
        F = [z3.ForAll([x], z3.Implies(x != nil, ln(x) == 1 + ln(nxt(x))), patterns=pats), ln(nil) == 0]
        if consulta == 'cerrada': F += [a != nil, nxt(a) != nil, nxt(nxt(a)) == nil, ln(a) != 2]
        if consulta == 'abierta': F += [ln(b) > 5]
        if consulta == 'negativa': F += [b != nil, ln(b) < 0]
        return F
    return construye

print('Lista de dos celdas, demostrar len(a) = 2, solo E-matching:')
for p in ['{len(x)}', '{next(x)}', '{len(x), next(x)}', '{len(next(x))}']:
    print(f'  {p:<19}', resuelve(lista(p, 'cerrada'), mbqi=False))
print('Lista abierta, len(b) > 5:')
for p in ['{len(x)}', '{len(x), next(x)}']:
    print(f'  {p:<19} solo E-matching', resuelve(lista(p, 'abierta'), mbqi=False))
    print(f'  {p:<19} con MBQI       ', resuelve(lista(p, 'abierta')))
print('Lista abierta, b != nil y len(b) < 0, con MBQI:')
print('  {len(x), next(x)}  ', resuelve(lista('{len(x), next(x)}', 'negativa')))

def dos_axiomas(explicitos):
    def construye(ctx):
        S = z3.DeclareSort('S', ctx)
        f, g, h = (z3.Function(n, S, S) for n in 'fgh')
        c, d, x, y = z3.Consts('c d x y', S)
        if explicitos:
            ax = [z3.ForAll([x], f(x) == g(h(x)), patterns=[f(x)]), z3.ForAll([y], g(y) == f(h(y)), patterns=[f(h(y))])]
        else:                                    # Z3 elige los patrones
            ax = [z3.ForAll([x], f(x) == g(h(x))), z3.ForAll([y], g(y) == f(h(y)))]
        return ax + [f(c) != d]
    return construye
print('Dos axiomas que se alimentan, consulta f(c) != d:')
print('  patrones de Z3, E-matching y MBQI ', resuelve(dos_axiomas(False)))
print('  patrones de Z3, solo E-matching   ', resuelve(dos_axiomas(False), mbqi=False))
print('  patrones de Z3, solo MBQI         ', resuelve(dos_axiomas(False), ematching=False))
print('  patrones {f(x)} y {f(h(y))}       ', resuelve(dos_axiomas(True)))
print('  ídem, solo E-matching             ', resuelve(dos_axiomas(True), mbqi=False))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Results query by query:

  • Two-cell list. All four patterns prove len(a)=2\mathrm{len}(a) = 2 with exactly 2 instances, as the interactive predicts.
  • Open list with {len(x)}\{\mathrm{len}(x)\} and only E-matching. The loop: max generation reaches 20 (lazy threshold), 21 instances and 11 missed, answer unknown (incomplete quantifiers). The multipattern yields no instances and the same answer: without MBQI it cannot say sat.
  • Open list with MBQI. Both answer sat in milliseconds, but multipattern uses 10 instances versus 34 for {len(x)}\{\mathrm{len}(x)\}: the loop still generates useless instances while MBQI works.
  • len(b)<0\mathrm{len}(b) < 0. Times out at 5 seconds with thousands of instances, as the argument predicts: only infinite models exist.
  • Two axioms. Z3’s inferred patterns (f(x)f(x) and g(y)g(y)) let each instance create a term triggering the other; defaults time out at 5 seconds, E-matching alone gives up with unknown and 39 instances, MBQI alone answers sat with 4. Pattern {f(h(y))}\{f(h(y))\} on the second axiom requires a term the first never creates, giving sat with 1 instance under defaults.

Practical lesson: write patterns for important axioms yourself, count instances (quant instantiations, max generation) as soon as things slow, and distrust max generation hitting the threshold.

Counterexample-guided synthesis

Synthesizing a program means finding one satisfying a specification for all inputs. With a sketch (a program with holes, in Solar-Lezama et al., 2006), the problem is

∃h∈H    ∀x∈X.    φ(P[h](x), x),\exists h \in \mathcal{H}\;\; \forall x \in \mathcal{X}.\;\; \varphi\big(P[h](x),\, x\big),

where hh are hole values, P[h]P[h] the resulting program and φ\varphi the specification. This formula has quantifier alternation ∃∀\exists\forall: it cannot be sent directly to a quantifier-free solver and MBQI often struggles. CEGIS avoids handling ∀\forall all at once.

The final exercise proves this. In practice bound ∣H∣\abs{\mathcal{H}} is huge but few rounds are needed because each counterexample eliminates every candidate failing on it, not just the proposed one. Both solvers are incremental: synthesis gets one new example per round and retains learning.

Exhaustive 8-bit CEGIS

The example computes the signed maximum of two integers without branches, using two bit-operation sketches. Both start from identity max⁡(x,y)=y⊕((x⊕y)∧m)\max(x, y) = y \oplus \big((x \oplus y) \wedge m\big), where mm is an all-ones mask if x≥yx \geq y and all-zero otherwise: the short sketch tries to get mm by arithmetic-shifting x?byx \mathbin{?_b} y and negating; the full sketch shifts a richer expression with four operator choices. Each ?? is a hole among +,−,⊕,∧,∨+, -, \oplus, \wedge, \vee, and shift kk is another. In 8 bits there are 216=65 5362^{16} = 65\,536 input pairs: the verifier can test them all and the synthesizer enumerate candidates.

[ ]Enumerative CEGIS for branch-free maximum, in 8 bitsBrowser
import itertools, time

B = 8                                             # ancho de palabra: 8 bits, 2^16 pares de entradas
def w(v):                                         # envuelve a B bits con signo (complemento a dos)
    return ((v + (1 << (B - 1))) & ((1 << B) - 1)) - (1 << (B - 1))
OPS = ['+', '-', '^', '&', '|']
F = [lambda a, b: w(a + b), lambda a, b: w(a - b), lambda a, b: a ^ b, lambda a, b: a & b, lambda a, b: a | b]

def corto(h, x, y):                               # y ^ ((x ?a y) & ~((x ?b y) >> ?k))
    a, b, k = h
    return y ^ (F[a](x, y) & ~(F[b](x, y) >> k))
def completo(h, x, y):                            # y ^ ((x ^ y) & ~(((x ?a y) ^ ((x ?b y) & ((x ?c y) ?d x))) >> ?k))
    a, b, c, d, k = h
    return y ^ ((x ^ y) & ~((F[a](x, y) ^ (F[b](x, y) & F[d](F[c](x, y), x))) >> k))
ESPACIO = {corto: list(itertools.product(range(5), range(5), range(B))),
           completo: list(itertools.product(range(5), range(5), range(5), range(5), range(B)))}
VALORES = range(-(1 << (B - 1)), 1 << (B - 1))

def cegis_enumerativo(sketch, ejemplo0=(0, 0)):
    espacio, ejemplos, i, traza = ESPACIO[sketch], [ejemplo0], 0, []
    while True:
        # síntesis: el primer candidato que acierta en todos los ejemplos. Los descartados no vuelven,
        # así que basta seguir desde i (los ejemplos solo crecen)
        while i < len(espacio) and any(sketch(espacio[i], x, y) != max(x, y) for x, y in ejemplos):
            i += 1
        if i == len(espacio):
            return None, traza, len(ejemplos)
        h = espacio[i]
        # verificación exhaustiva: el primer par (x, y) en que falla, si lo hay
        cex = next(((x, y) for x in VALORES for y in VALORES if sketch(h, x, y) != max(x, y)), None)
        traza.append((h, cex))
        if cex is None:
            return h, traza, len(ejemplos)
        ejemplos.append(cex)

for sk in (corto, completo):
    t0 = time.perf_counter(); h, traza, n_ej = cegis_enumerativo(sk); t = time.perf_counter() - t0
    print(f'sketch {sk.__name__}: {len(ESPACIO[sk])} candidatos, {len(traza)} candidatos propuestos, {n_ej} ejemplos, {t:.2f} s')
    for cand, cex in traza:
        print('   ', ' '.join(OPS[v] for v in cand[:-1]), f'k={cand[-1]}', '-> contraejemplo', cex)
    print('   resultado:', 'ningún programa del sketch es correcto' if h is None else
          'correcto en las 65536 entradas: ' + ' '.join(OPS[v] for v in h[:-1]) + f' k={h[-1]}')

The short sketch has 200 candidates; CEGIS proposes 9, all counterexamples at range extremes (the verifier starts inputs at −128-128), and concludes none is correct. The full sketch has 5000 candidates; after 10 proposals and 10 examples it finds (−,⊕,−,⊕,k=7)(-, \oplus, -, \oplus, k = 7), i.e.

max⁡(x,y)=y⊕((x⊕y)∧¬(((x−y)⊕((x⊕y)∧((x−y)⊕x)))≫7)).\max(x, y) = y \oplus \Big((x \oplus y) \wedge \neg\big(\big((x - y) \oplus ((x \oplus y) \wedge ((x - y) \oplus x))\big) \gg 7\big)\Big).

The shifted expression is what Hacker’s Delight (Warren) gives for signed predicate x<yx < y: its sign bit is that of the true difference x−yx - y, correcting overflow. This explains the short sketch’s failure: textbook trick (x−y)≫7(x - y) \gg 7 works only if x−yx - y does not overflow. The next cell checks that in 8 bits the found program is the only correct one of 5000.

[ ]How many correct programs does the full sketch have?Browser
import numpy as np

v = np.arange(-128, 128, dtype=np.int8)
X, Y = (a.ravel() for a in np.meshgrid(v, v))      # los 65536 pares de entradas, de una vez
M = np.maximum(X, Y)
G = [lambda a, b: a + b, lambda a, b: a - b, lambda a, b: a ^ b, lambda a, b: a & b, lambda a, b: a | b]
correctos = []
with np.errstate(over='ignore'):                    # int8 envuelve como el hardware de 8 bits
    for a, b, c, d in itertools.product(range(5), repeat=4):
        t = G[a](X, Y) ^ (G[b](X, Y) & G[d](G[c](X, Y), X))
        for k in range(8):
            if np.array_equal(Y ^ ((X ^ Y) & ~(t >> k)), M):
                correctos.append((a, b, c, d, k))
print(f'candidatos correctos del sketch completo en 8 bits: {len(correctos)} de 5000 ->',
      [' '.join(OPS[o] for o in h[:-1]) + f' k={h[-1]}' for h in correctos])

Lab: CEGIS with two 32-bit Z3 solvers

At 32 bits there are 2642^{64} input pairs and exhaustive verification is infeasible. Z3 bit-vectors replace it: the verifier seeks x,yx, y with P[h](x,y)≠max⁡(x,y)P[h](x, y) \neq \max(x, y) and, via bit-blasting, decides all 2642^{64} inputs at once. Synthesis encodes each operator hole as an integer 0 to 4 and the program with chained If; each round adds the new example constraint to the same solver. Besides maximum, the lab synthesizes absolute value and rounding up to a power of two (five logical-shift holes), ending with a typical mistake.

[ ]CEGIS with Z3: maximum, absolute value and power of twoLocal GPU
import z3, time

W = 32
OPS = ['+', '-', '^', '&', '|']

def op(h, a, b):
    """Operador del hueco h (entero de Z3 al sintetizar, entero de Python al verificar)."""
    tabla = [a + b, a - b, a ^ b, a & b, a | b]
    if isinstance(h, int):
        return tabla[h]
    r = tabla[-1]
    for i in reversed(range(len(OPS) - 1)):
        r = z3.If(h == i, tabla[i], r)
    return r

class Sketch:
    """Programa con huecos de dos clases: operador ('op') y desplazamiento ('sh', de 0 a W - 1)."""
    def __init__(self, nombre, huecos, cuerpo, spec, texto, pre=None):
        self.nombre, self.huecos, self.cuerpo, self.spec, self.texto = nombre, huecos, cuerpo, spec, texto
        self.pre = pre or (lambda *e: z3.BoolVal(True, e[0].ctx))

def cegis(sk, ejemplo0, max_vueltas=40):
    ctx = z3.Context()                               # contexto propio: la traza no depende de lo ejecutado antes
    H = {h: z3.Int(f'h_{h}', ctx) if t == 'op' else z3.BitVec(f'h_{h}', W, ctx) for h, t in sk.huecos.items()}
    sintesis = z3.Solver(ctx=ctx)                    # solver 1: ∃ huecos. el programa acierta en todos los ejemplos
    for h, t in sk.huecos.items():
        sintesis.add(z3.And(0 <= H[h], H[h] < len(OPS)) if t == 'op' else z3.ULT(H[h], W))
    entradas = [z3.BitVec(f'in{i}', W, ctx) for i in range(len(ejemplo0))]
    ejemplos, traza = [ejemplo0], []
    for _ in range(max_vueltas):
        e = [z3.BitVecVal(v, W, ctx) for v in ejemplos[-1]]
        sintesis.add(sk.cuerpo(H, *e) == sk.spec(*e))      # solo el ejemplo nuevo: el solver es incremental
        if sintesis.check() == z3.unsat:
            traza.append(dict(cand=None, cex=None))
            return None, traza
        m = sintesis.model()
        cand = {h: m.eval(H[h], model_completion=True).as_long() for h in sk.huecos}
        fijo = {h: v if sk.huecos[h] == 'op' else z3.BitVecVal(v, W, ctx) for h, v in cand.items()}
        verif = z3.Solver(ctx=ctx)                   # solver 2: ∃ entradas. el candidato falla
        verif.add(sk.pre(*entradas), sk.cuerpo(fijo, *entradas) != sk.spec(*entradas))
        if verif.check() == z3.unsat:
            traza.append(dict(cand=cand, cex=None))
            return cand, traza
        mv = verif.model()
        cex = tuple(mv.eval(v, model_completion=True).as_signed_long() for v in entradas)
        traza.append(dict(cand=cand, cex=cex))
        ejemplos.append(cex)
    return None, traza

def muestra(sk, cand):
    t = sk.texto
    for h, v in cand.items():
        t = t.replace('?' + h, OPS[v] if sk.huecos[h] == 'op' else str(v))
    return t

def informe(sk, ejemplo0):
    t0 = time.perf_counter(); cand, traza = cegis(sk, ejemplo0); t = time.perf_counter() - t0
    print(f'{sk.nombre}: {len(traza)} vueltas, {t:.2f} s')
    for i, paso in enumerate(traza):
        if paso['cand'] is None:
            print(f'  {i + 1}. síntesis unsat: ningún programa del sketch acierta en todos los ejemplos')
        else:
            print(f'  {i + 1}. {muestra(sk, paso["cand"])}   contraejemplo: {paso["cex"]}')
    return cand

maximo = lambda x, y: z3.If(x >= y, x, y)            # >= sobre vectores de bits de Z3: comparación con signo
corto = Sketch('máximo, sketch corto', {'a': 'op', 'b': 'op', 'k': 'sh'},
               lambda H, x, y: y ^ (op(H['a'], x, y) & ~(op(H['b'], x, y) >> H['k'])),
               maximo, 'y ^ ((x ?a y) & ~((x ?b y) >> ?k))')
completo = Sketch('máximo, sketch completo', {'a': 'op', 'b': 'op', 'c': 'op', 'd': 'op', 'k': 'sh'},
                  lambda H, x, y: y ^ ((x ^ y) & ~((op(H['a'], x, y) ^ (op(H['b'], x, y) & op(H['d'], op(H['c'], x, y), x))) >> H['k'])),
                  maximo, 'y ^ ((x ^ y) & ~(((x ?a y) ^ ((x ?b y) & ((x ?c y) ?d x))) >> ?k))')
informe(corto, (0, 0))
informe(completo, (0, 0))

absoluto = Sketch('valor absoluto', {'a': 'op', 'b': 'op', 'k': 'sh'},
                  lambda H, x: op(H['b'], op(H['a'], x, x >> H['k']), x >> H['k']),
                  lambda x: z3.If(x >= 0, x, -x), '(x ?a (x >> ?k)) ?b (x >> ?k)')

def potencia_de_dos(x):                              # la menor potencia de dos >= x, para 1 <= x <= 2^30
    r = z3.BitVecVal(2 ** 30, W, x.ctx)
    for i in reversed(range(30)):
        r = z3.If(z3.ULE(x, 2 ** i), z3.BitVecVal(2 ** i, W, x.ctx), r)
    return r
def cuerpo_pot2(H, x):
    v = x - 1
    for h in 'pqrst':
        v = v | z3.LShR(v, H[h])                     # desplazamiento lógico (>>> en C sin signo)
    return v + 1
potencia = Sketch('redondeo a potencia de dos', {h: 'sh' for h in 'pqrst'}, cuerpo_pot2, potencia_de_dos,
                  'v = x - 1; v |= v >> ?p; v |= v >> ?q; v |= v >> ?r; v |= v >> ?s; v |= v >> ?t; v + 1',
                  pre=lambda x: z3.And(z3.UGE(x, 1), z3.ULE(x, 2 ** 30)))
for sk, e0 in [(absoluto, (0,)), (potencia, (1,))]:
    cand = informe(sk, e0)
    print('  resultado:', muestra(sk, cand) if cand else 'ningún programa')

# El error de modelar con enteros matemáticos: ¿x - y < 0 equivale a x < y?
xi, yi = z3.Ints('x y')
s = z3.Solver(); s.add((xi - yi < 0) != (xi < yi)); print('enteros:', s.check())
xb, yb = z3.BitVecs('x y', W)
s = z3.Solver(); s.add((xb - yb < 0) != (xb < yb)); r = s.check(); m = s.model()
print('32 bits:', r, 'x =', m.eval(xb).as_signed_long(), 'y =', m.eval(yb).as_signed_long())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

At 32 bits the short sketch again has no solution: round 4 proposes exactly textbook trick y⊕((x⊕y)∧¬((x−y)≫31))y \oplus ((x \oplus y) \wedge \neg((x - y) \gg 31)), refuted by x=−1 073 741 825x = -1\,073\,741\,825, y=1 073 741 824y = 1\,073\,741\,824, where x−y=−231−1x - y = -2^{31} - 1 overflows to positive 231−12^{31} - 1. Synthesis then answers unsat. The full sketch finds the 8-bit formula in 7 rounds, now with k=31k = 31. Absolute value takes 6 rounds, (x⊕(x≫31))−(x≫31)(x \oplus (x \gg 31)) - (x \gg 31); power-of-two rounding takes 11 with shifts 8,4,16,2,18, 4, 16, 2, 1: any order of 1,2,4,8,161, 2, 4, 8, 16 works, since after five operations each bit ORs bits at distances formed by subset sums of the shifts, covering 0 through 31.

The lab’s final question illustrates the mistake: over mathematical integers x−y<0  ⟺  x<yx - y < 0 \iff x < y is valid (its negation unsat); at 32 bits Z3 immediately supplies a counterexample. A program synthesized or verified over Int may fail on real hardware.

InteractiveThe CEGIS loop
sketch: y ^ ((x ?a y) & ~((x ?b y) >> ?k))
candidate: y ^ ((x + y) & ~((x + y) >> 0))
Round 1: the candidate works on the single example, but the verifier finds x = 0, y = −1: it returns −1 instead of 0. The counterexample becomes another example.
Examples seen by the synthesizer
xymax(x, y)0000−1← counterexample
Try the candidate with your inputs
candidate: −1 · max: 2147483647 incorrect
round 1 / 5
Sketch
Examples1
Candidates consistent with examples800 of 800
Loop resultunrealizable sketch (5 rounds)
Real Z3 lab traces saved from the preceding cell with three different initial examples. Top: sketch holes orange and current candidate. Play rounds showing candidate, verifier counterexample and growing example set. ‘Compatible candidates’ is computed in your browser by enumerating the sketch space (800 or 20000 candidates): see how each example reduces it. In the short sketch it reaches 0 when synthesis says unsat. Try your inputs: preset (2³¹ − 1, −1) defeats the textbook trick; which full-sketch candidate passes? Change the initial example: does the final program change?

In the interactive, the initial example changes the path (4 to 7 rounds across six traces), not the destination: the short sketch is unrealizable from any example and the full sketch always ends at the same formula. This is superoptimization: search for the shortest or fastest program equivalent to a given one. Massalin (1987) named it, enumerating programs and testing them; with solvers, Gulwani, Jha, Tiwari and Venkatesan (2011) synthesize loop-free programs from components using such an inductive loop and reproduce Hacker’s Delight tricks; Souper applies this to LLVM optimization. The same two-solver “propose and refute” scheme appears in IC3 verification and agents generating a solution and calling a verifier.

Performance diagnosis

When a query is slow, use three tools in this order.

Statistics. s.statistics() shows solver work: conflicts and decisions from the SMT core, sat conflicts if preprocessing sent the problem to SAT, simplex arith-conflicts, quantifier quant instantiations and max generation, memory. Programming Z3 notes they are most valuable with detailed knowledge of decision procedures: compare orders of magnitude and ask which component is working.

Logic and tactics. z3.SolverFor('QF_BV') fixes the logic rather than letting auto_config guess. Tactics compose goal transformations: z3.Then('simplify', 'solve-eqs', 'bit-blast', 'sat') simplifies, eliminates variables via equality, bit-blasts and calls SAT; z3.Tactic('smt') is the SMT core without preprocessing; t.solver() converts a tactic to a solver. z3.describe_tactics() lists available tactics.

Reformulation. Explicit integer bounds, bit-vectors instead of nonlinear integer arithmetic, global constraints (Distinct, PbEq, AtMost) instead of decompositions, symmetry breaking, explicit patterns and incremental use. None is universally better: measure.

The lab shows an extreme case. Pigeonhole with n+1n + 1 pigeons and nn holes, expressed with integer variables xij∈{0,1}x_{ij} \in \{0, 1\}, ∑jxij≥1\sum_j x_{ij} \geq 1 per pigeon and ∑ixij≤1\sum_i x_{ij} \leq 1 per hole, is unsatisfiable by a one-line argument: summing gives n+1≤∑ijxij≤nn + 1 \leq \sum_{ij} x_{ij} \leq n. That is exactly what linear-arithmetic simplex sees: the linear relaxation is infeasible. Resolution instead requires exponential-size pigeonhole refutations (Haken, 1985), the wall seen in the CDCL lesson.

[ ]Pigeonhole: statistics and tactic selectionLocal GPU
import z3, time

def palomar(n, hacer_solver, timeout=20000):
    """n + 1 palomas en n huecos con variables enteras 0-1: x_ij = 1 si la paloma i va al hueco j."""
    x = [[z3.Int(f'x_{i}_{j}') for j in range(n)] for i in range(n + 1)]
    s = hacer_solver(); s.set('timeout', timeout)
    for fila in x:
        s.add([z3.And(0 <= v, v <= 1) for v in fila])
        s.add(z3.Sum(fila) >= 1)                                   # cada paloma, en algún hueco
    for j in range(n):
        s.add(z3.Sum([x[i][j] for i in range(n + 1)]) <= 1)        # cada hueco, como mucho una paloma
    t = time.perf_counter(); r = s.check(); t = time.perf_counter() - t
    st = s.statistics()
    claves = [k for k in st.keys() if 'conflicts' in k or k == 'decisions']
    return f'{str(r):8s} {t:7.3f} s  ' + ', '.join(f'{k}: {st.get_key_value(k)}' for k in claves)

for n in (10, 20):
    print(f'n = {n:3d}, Solver() por defecto:   ', palomar(n, z3.Solver))
for n in (10, 40, 100):
    print(f'n = {n:3d}, Tactic("smt").solver():', palomar(n, lambda: z3.Tactic('smt').solver()))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With default Solver(), n=10n = 10 takes seconds and over one hundred thousand sat conflicts (exact count varies); n=20n = 20 times out after 20 seconds. Statistics reveal why: all conflicts are SAT conflicts, so default preprocessing converted 0–1 integers to Booleans and sums to pseudo-Boolean constraints, landing in the exponential resolution setting. With Tactic('smt').solver(), which skips that preprocessing, arithmetic reaches simplex: one arithmetic conflict for n=10n = 10, 4040 and 100100 in milliseconds. No constraint changes; the procedure seeing the problem does.

Common mistakes

Exercises

NumericUnsatisfiable Fu–Malik calls
A partial MaxSAT instance has satisfiable hard constraints and 6 soft clauses of weight 1, and its optimum is 2. How many unsatisfiable calls does Fu–Malik make before the first satisfiable call, regardless of the core returned by the solver at each step?
NumericThe cost of minimization
You run Fu–Malik with deletion-based minimization of each core (without refinement). The instance has optimum 3, and at each iteration the solver returns a core of 5 soft clauses whose MUS has 2. How many solver calls does the algorithm make in total, including the final satisfiable call?
QuizIs this core minimal?
A solver returns an unsatisfiable core of 12 constraints, with core.minimize disabled. Which statement is correct?
QuizA pattern for the inverse
You want to axiomatize that ff is a left inverse of gg with ∀x. f(g(x))=x\forall x.\, f(g(x)) = x. Which pattern do you choose and why?
NumericRepairs from cores
A set of four rules A,B,C,DA, B, C, D has exactly three MUSes: {A,B}\{A, B\}, {B,C}\{B, C\} and {C,D}\{C, D\}. How many minimal correction sets (MCSes) does it have?
QuizWhat box returns
In the task lab, box mode returns (finish, energy) = (10, 30). What does that mean?
QuizAn unknown that more time cannot fix
With the list-length axiom, Z3 times out on the query b≠nil∧len(b)<0b \neq \mathrm{nil} \wedge \mathrm{len}(b) < 0 even with MBQI. What is the correct explanation?
ProofCEGIS is correct and terminates
Prove: Let H\mathcal{H} be a finite space of hole values and φ(h,x)\varphi(h, x) the specification of program P[h]P[h] on input xx. If the synthesizer and verifier are sound and complete, CEGIS makes at most ∣H∣+1\abs{\mathcal{H}} + 1 synthesis calls; if it returns hh, then φ(h,x)\varphi(h, x) holds for every xx, and if it declares that no program exists, no h∈Hh \in \mathcal{H} is correct.
0
Call EiE_i the set of examples before iteration ii and hih_i the candidate proposed by the synthesizer in that iteration, satisfying φ(hi,e)\varphi(h_i, e) for every e∈Eie \in E_i. If the verifier finds xix_i with ¬φ(hi,xi)\neg\varphi(h_i, x_i), then Ei+1=Ei∪{xi}E_{i+1} = E_i \cup \{x_i\}.

Step 1 of 4. Why does the synthesizer never propose the same candidate twice?

CodeDeletion-based minimization
Implement minimiza(check, nucleo): nucleo is a list of constraints (arbitrary objects) whose set is unsatisfiable, and check(lista) returns 'sat' or 'unsat' for a list of constraints. Return a list that is an inclusion-minimal core (MUS), contained in nucleo, making exactly len(nucleo) calls to check. Tests use random clause sets, check by brute force that the result is unsatisfiable and removing any element makes it satisfiable, and count calls.
def minimiza(check, nucleo):
  """Devuelve un MUS contenido en nucleo con len(nucleo) llamadas a check."""
  # tu código
  return list(nucleo)
Shift+Enter to run
CodeFu–Malik with a core-producing solver
Implement fu_malik(duras, blandas, Solver). duras and blandas are lists of clauses (lists of nonzero integers, as in DIMACS). Solver is the class from the lesson cell: s = Solver(), s.add(clausula), s.nueva_var(), s.nvars, s.check(suposiciones) returns 'sat' or 'unsat', s.core() the set of assumptions in the core, and s.model() a variable → bool dictionary. Return (coste, modelo) with the optimal cost (minimum number of violated soft clauses while satisfying all hard clauses) and a model achieving it, or (None, None) if the hard clauses are unsatisfiable. Tests compare it with brute force on random instances and check that the model satisfies hard clauses and violates exactly coste soft clauses.
def fu_malik(duras, blandas, Solver):
  """MaxSAT parcial con pesos 1 por el algoritmo de Fu y Malik."""
  s = Solver()
  for c in duras:
      s.add(c)
  # tu código: selectores, bucle de núcleos, relajación y restricción exactamente-una
  return 0, None
Shift+Enter to run

Summary

Key idea
An SMT solver’s performance depends on how it is used: one incremental solver with selectors and assumptions retains learned facts; cores explain conflicts and, minimized and enumerated, identify repairs; MaxSAT and OMT turn unsatisfiable calls into bounds rising to the optimum; with quantifiers, patterns and MBQI determine whether instance search terminates, and unknown is sometimes the only possible answer; CEGIS reduces an ∃∀ problem to two quantifier-free solvers exchanging counterexamples.
  • Assumptions are CDCL decisions, so everything learned with them follows from permanent assertions and survives across queries; assert_and_track is an p→Cp \rightarrow C selector. Over 196 queries on the 14 queens, reusing the solver was more than ten times faster.
  • A solver core reflects its refutation and need not be minimal. Deletion produces a MUS with one call per element; monotonicity makes checking subsets unnecessary. Repairs are sets hitting all MUSes (MUS–MCS duality): the firewall policy had 12 MUSes and a minimum repair of 5 requirements.
  • Fu–Malik relaxes each core using new variables and an exactly-one constraint; each core lowers the optimum by one, so it makes exactly opt\mathrm{opt} unsatisfiable calls, whether cores are minimal or not. Z3 uses MaxRes, which does not accumulate relaxation variables, and νZ combines objectives lexicographically, independently or by Pareto; box gives separate optima, not a solution.
  • With quantifiers, decidability is lost. E-matching instantiates patterns modulo the E-graph; a pattern that creates terms matching again causes a loop, which Z3 cuts off by generation and turns into unknown. MBQI instantiates where a finite candidate model fails and can answer sat, but not when only infinite models exist.
  • CEGIS alternates a synthesizer over examples and a complete verifier; it terminates on finite spaces and is correct. In the full sketch, 10 examples at 8 bits and 7 at 32 bits sufficed to find the branch-free maximum (at 8 bits, the only correct one of the 5000 candidates), and 5 examples proved that the short 32-bit sketch has none. Model machine programs using bit vectors.
  • For a slow query: use statistics to see which component is working, tactics and logic to choose who sees the problem, and reformulation so it sees it well. The integer pigeonhole problem goes from nontermination to a single simplex conflict just by changing the tactic.