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 , the commonest cause of
unknownand unexplained timeouts. - Synthesis. Finding a program satisfying a specification for every input is an 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 is (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 without adding them. If the answer is unsat, unsat_core() returns a subset already sufficient for contradiction. To assume an arbitrary constraint rather than a literal, use a selector: fresh Boolean , permanent assertion and assumption . 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 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: is permanent and always true ( false suffices), so learned clauses based on it, containing literal , 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 and row-1 queen in column ?”): a new solver per question, one solver with assumptions, and one with push/pop. Times vary by machine; the ratio matters.
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}')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 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 has unsatisfiable; the root has no decisions, so is a core.
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 alone are unsatisfiable (all four sign combinations over ), but DPLL first decides . In branch , and immediately conflict; in branch , and are satisfied and the refutation uses . Their union is a valid but nonminimal core: and were included only because of decision order. Six minimization calls reduce it to , 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
is always unsatisfiable: initially so, and is removed only if the rest remains unsatisfiable. Let be final and the value of when testing . Since remained, is satisfiable. Only elements are later removed, so , and a subset of a satisfiable set is satisfiable (any model of the larger satisfies the smaller). Removing any element of thus makes it satisfiable: a MUS. Each element of is tested once: calls.
∎The proof’s monotonicity (subsets of satisfiable sets are satisfiable) also avoids checking subsets for minimality: single deletions suffice. Two improvements are common. Core refinement: when is unsatisfiable, replace by that call’s possibly much smaller core, avoiding tests of dropped elements. QuickXplain (Junker, 2004) recursively halves the core and needs about calls when the MUS has elements, much less than for small . A minimum-cardinality core is harder: deciding whether a set is a MUS is already -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 is a correction set and some MUS does not intersect , then , and containing an unsatisfiable set would be unsatisfiable: contradiction. Conversely, if hits every MUS and were unsatisfiable, it would contain a MUS (remove elements while unsatisfiable; is finite), which would not intersect . 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).
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.
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 , already a MUS. Deleting from all ten depends on order: R1 to R10 ends at (ssl conflict), R10 to R1 at (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: , or , 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.
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)npm run lab and open the connection link.The first query returns core (a prefix cannot be both and ), just one of the policy’s 12 MUSes. There are obvious pairs (, ), triples (: not 22, below 1024, and 22 or 2222), and four-requirement conflicts hard to spot such as : 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 false soft clauses”, a direct solution searches linearly over . Add relaxation variable to each soft clause (becoming ), and ask for a model with . Decreasing 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 “ 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:
- Each soft clause has selector : add and assume .
- If is sat, return the model and accumulated cost.
- If unsat, core (restricted to selectors) identifies soft clauses incompatible with hard ones. If , hard clauses are unsatisfiable. Otherwise for each add a fresh relaxation variable (the soft clause becomes with fresh selector), add a hard exactly-one constraint on this core’s 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
() Let be optimal for . Since and is unsatisfiable, falsifies at least one . Extend with and all other : it satisfies and the new constraint, hence . Soft clauses outside are unchanged; those in except retain their value (their is 0); becomes satisfied. Cost falls exactly one, and .
() Let satisfy . Restricted to old variables it satisfies . Exactly one is 1. Soft clauses outside and with have the same value in both instances; the only clause that can hold in but fail in is . Thus and, taking optimal , .
For the algorithm: a satisfiable call satisfies all current soft and hard clauses together, so current optimum is 0. An unsatisfiable call with satisfiable has a soft clause in its core, and by the above the optimum drops by one. Starting at and never negative, there are exactly unsatisfiable calls before the first satisfiable one. The final model violates exactly that many original soft clauses: each violation needs its own true , each belongs to one group, and each group has one true , so violations are at most group count and at least .
∎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 unsatisfiable. Minimization costs calls and often saves constraint size, not iterations, which always equal the optimum.
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 (Bea and Ciro both want Monday afternoon), (Ana and Bea, Tuesday morning), and : after the second, one of or may be violated, but Ciro also wants Tuesday morning and only one of three can hold. Thus and 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 , and : 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 , duplicates each soft clause of weight into a copy of weight (relaxed) and one of weight (unchanged), then raises cost by . 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 soft clauses with new ones, 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.
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}')npm run lab and open the connection link.On shifts, Z3 finds different cores from DPLL (: Ana cannot work both Tuesday shifts; ; ), 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”.
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']))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 (, , and ) 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 and (energy, finish) . Mode box returns , individual optima that do not correspond to one solution: they are two different solutions. The Pareto front has 11 points, to , 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 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 -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 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 and :
Candidate patterns are , , and multipattern . has a problem: each instance on term creates , 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.
For the two-cell list (, , ), every pattern yields the two required instances and , immediately contradicting . Match of contributes nothing: guard is false. Pattern is curious: initially no term written exists, but matches modulo equality with . That is “modulo E”.
For the open list (only is known), tight patterns find no matching term because no 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 . 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 , with finite universe and function tables. For each construct , replacing uninterpreted symbols by their tables in , and ask whether is satisfiable, a quantifier-free query. If not, satisfies the quantifier. Otherwise the witness identifies where violates the axiom; translate it into ground terms and add instance 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 :
- In every finite model, . Follow If the chain reaches at step without earlier contact, applying the axiom to yields . If never reached, finiteness forces cycle with all distinct from ; summing the axiom from to yields , impossible.
- But the query is satisfiable: in infinite model , with and , the axiom holds for every .
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.
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))npm run lab and open the connection link.Results query by query:
- Two-cell list. All four patterns prove with exactly 2 instances, as the interactive predicts.
- Open list with and only E-matching. The loop:
max generationreaches 20 (lazy threshold), 21 instances and 11 missed, answerunknown (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 : the loop still generates useless instances while MBQI works.
- . Times out at 5 seconds with thousands of instances, as the argument predicts: only infinite models exist.
- Two axioms. Z3’s inferred patterns ( and ) let each instance create a term triggering the other; defaults time out at 5 seconds, E-matching alone gives up with
unknownand 39 instances, MBQI alone answers sat with 4. Pattern 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
where are hole values, the resulting program and the specification. This formula has quantifier alternation : it cannot be sent directly to a quantifier-free solver and MBQI often struggles. CEGIS avoids handling all at once.
The final exercise proves this. In practice bound 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 , where is an all-ones mask if and all-zero otherwise: the short sketch tries to get by arithmetic-shifting and negating; the full sketch shifts a richer expression with four operator choices. Each is a hole among , and shift is another. In 8 bits there are input pairs: the verifier can test them all and the synthesizer enumerate candidates.
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 ), and concludes none is correct. The full sketch has 5000 candidates; after 10 proposals and 10 examples it finds , i.e.
The shifted expression is what Hacker’s Delight (Warren) gives for signed predicate : its sign bit is that of the true difference , correcting overflow. This explains the short sketch’s failure: textbook trick works only if does not overflow. The next cell checks that in 8 bits the found program is the only correct one of 5000.
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 input pairs and exhaustive verification is infeasible. Z3 bit-vectors replace it: the verifier seeks with and, via bit-blasting, decides all 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.
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())npm run lab and open the connection link.At 32 bits the short sketch again has no solution: round 4 proposes exactly textbook trick , refuted by , , where overflows to positive . Synthesis then answers unsat. The full sketch finds the 8-bit formula in 7 rounds, now with . Absolute value takes 6 rounds, ; power-of-two rounding takes 11 with shifts : any order of 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 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.
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 pigeons and holes, expressed with integer variables , per pigeon and per hole, is unsatisfiable by a one-line argument: summing gives . 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.
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()))npm run lab and open the connection link.With default Solver(), takes seconds and over one hundred thousand sat conflicts (exact count varies); 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 , and in milliseconds. No constraint changes; the procedure seeing the problem does.
Common mistakes
Exercises
Step 1 of 4. Why does the synthesizer never propose the same candidate twice?
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)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, NoneSummary
- Assumptions are CDCL decisions, so everything learned with them follows from permanent assertions and survives across queries;
assert_and_trackis an 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 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;
boxgives 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.