SMT: Boolean choices with arithmetic meaning
可满足性模理论
Build a small integer-difference solver, inspect a satisfying witness or negative cycle, and distinguish branch conflicts from exhaustive UNSAT.
smtA Boolean choice can fail an arithmetic check
Suppose two laboratory operations start at integer times A and B. They must be separated: either A starts at least two ticks before B, or B starts at least one tick before A. A checkpoint also requires A to start no later than B. These are the entire rules of this hypothetical example; no absolute start time or end-of-day deadline is imposed.
Name the three arithmetic statements and write the rules as a Boolean formula:
The Boolean setting (False, True, True) satisfies F. Its arithmetic requirements do not: B must be earlier than A, while A must be no later than B. By contrast, (True, False, True) is realized by A = −2 and B = 0. Since this example constrains only their difference, A = 0 and B = 2 also works.
Satisfiability modulo theories, or SMT, asks whether a formula has a model that respects its background theories. Arithmetic symbols keep their arithmetic meaning. Merely assigning independent truth values to the arithmetic atoms can admit impossible combinations. Here a model is a satisfying mathematical interpretation, not a trained neural network. Programming Z3, introduction and §6.1.1
This chapter connects SAT to a small theory solver. It uses quantifier-free integer difference logic, abbreviated QF_IDL: Boolean combinations of constraints on differences between integers. The official language includes more comparison forms and standalone Boolean symbols than our example interface. SMT-LIB: QF_IDL
From an arithmetic branch to a graph
An atom in our teaching fragment has the form x − y ≤ c, where x and y are integer variables or the zero reference and c is an integer. Integers are unbounded; no finite domain is supplied. Each atom receives a Boolean ID. A positive literal requires the atom to be true, and a negative literal requires it to be false.
The integer assumption determines the negation:
For x − y ≤ 3, the false branch requires y − x ≤ −4. Using −3 would allow x − y = 3 to count as both true and false. Over real numbers, the complement instead remains the strict inequality x − y > c; the integer “one step past the boundary” argument no longer applies.
A complete Boolean setting selects one inequality per atom: the original inequality for True and its complement for False. Even atoms absent from the CNF receive values in this implementation. For each selected inequality x − y ≤ c, add the directed edge y → x with weight c. Edge direction is part of the translation: it expresses x ≤ y + c.
A negative-weight directed cycle proves that this selected conjunction is impossible. Sum the inequalities around the cycle. Every variable appears once with each sign:
In our first Boolean branch, p₂ gives A → B with weight −1 and p₃ gives B → A with weight 0. Together they require 0 ≤ −1. This cycle refutes that branch. It does not refute F, which has another viable branch.
The converse also holds. Temporarily add a source with a zero-weight edge to every vertex. If there is no negative cycle, shortest-path distances are finite and satisfy every edge inequality. Integer edge weights give integer distances. The zero reference z can then be normalized to 0 without changing any difference:
This is why a graph test can produce a witness instead of merely failing to find a contradiction. The negative-cycle and shortest-path arguments are developed in MIT 6.046J, lecture 18 transcript, pp. 18–24.
The code uses Bellman–Ford relaxation: if an edge would lower its target’s distance, make that update. Initializing every distance to zero is equivalent to having already traversed the extra source’s edges. It also detects negative cycles in disconnected parts of the original graph. With N original vertices including z, a shortest simple path after the source uses at most N − 1 original edges. After N − 1 complete scans, a feasible graph is settled. A strict update on scan N therefore signals a negative cycle; a scan with no update allows an earlier return. Following N predecessor edges enters the cycle, whose edges are then returned in forward order.
Enumerating all Boolean settings and applying this complete conjunction test is a decision procedure for the fragment. A returned witness makes every atom agree with its Boolean value and satisfies the CNF. Conversely, any integer model induces a Boolean setting that enumeration eventually reaches. Without a budget limit, failure of every setting establishes UNSAT.
Return an integer model and retain one rejected branch
The following complete Python 3.10+ program uses the standard library. solve_smt accepts variable names, atoms (x, y, c), and CNF clauses of signed atom IDs starting at 1. All three collections, each atom and each clause must be a list or tuple. The input is validated and copied. Bounds and literal IDs reject floats and Python Booleans. Empty or repeated variable names, the reserved name $0, unknown variables and invalid literal IDs raise ValueError.
$0 denotes the zero reference, so ('X', '$0', 5) means X ≤ 5. Internally it is a graph vertex that is shifted to value 0 on return. Introducing a free origin variable and normalizing its value gives the same existence question for these difference constraints. The solver also permits self-comparisons, repeated atoms and unused variables; arithmetic consistency still applies when identical atoms receive different Boolean IDs.
Boolean settings follow lexicographic order with False before True. budget counts every complete setting inspected, including those rejected by the CNF. It excludes validation and does not bound the duration of one theory check. None removes this limit. The private helper _idl assumes a prepared model and exactly one Boolean per atom; it is not a separately validated public API.
SAT includes integer values and their boolean setting. UNSAT means enumeration finished without a witness. UNKNOWN means the budget stopped enumeration before either conclusion. The code does no preliminary simplification: with budget 0, even an empty clause gives UNKNOWN. With no atoms there is one empty Boolean setting, so budget 1 suffices to settle either an empty CNF or a CNF containing an empty clause.
last_conflict retains only the most recently rejected arithmetic branch, even if a later branch succeeds. Each cycle edge stores (source, target, weight, signed_atom_id). Check that these edges belong to that branch, join into a closed walk and have negative total weight. This is a checkable certificate for one conjunction. The result does not serialize a proof covering every rejected branch of a global UNSAT answer.
from itertools import product
ZERO = '$0'
def prepare(names, atoms, clauses):
"""Copy and validate the public input; atoms use 1-based clause IDs."""
def sequence(value):
if not isinstance(value, (list, tuple)):
raise ValueError('expected a list or tuple')
return tuple(value)
names = sequence(names)
if any(type(x) is not str or not x or x == ZERO for x in names):
raise ValueError('invalid or reserved variable name')
if len(set(names)) != len(names):
raise ValueError('duplicate variable name')
nodes = (ZERO,) + names
known = set(nodes)
copied_atoms = []
for atom in sequence(atoms):
atom = sequence(atom)
if len(atom) != 3:
raise ValueError('an atom must be (x, y, integer_bound)')
x, y, c = atom
if (type(x) is not str or type(y) is not str
or x not in known or y not in known or type(c) is not int):
raise ValueError('unknown variable or non-integer bound')
copied_atoms.append(atom)
copied_clauses = []
for clause in sequence(clauses):
clause = sequence(clause)
if any(type(lit) is not int or lit == 0
or abs(lit) > len(copied_atoms) for lit in clause):
raise ValueError('literal must name an existing atom')
copied_clauses.append(clause)
return nodes, tuple(copied_atoms), tuple(copied_clauses)
def _idl(nodes, atoms, bits):
"""Internal helper: prepared model, one bool per atom; no Boolean CNF."""
edges = []
for i, ((x, y, c), truth) in enumerate(zip(atoms, bits), 1):
# Edge (u, v, w, literal) means value[v] - value[u] <= w.
edges.append((y, x, c, i) if truth else (x, y, -c - 1, -i))
distance = dict.fromkeys(nodes, 0)
predecessor = {}
for _ in range(len(nodes)):
changed = None
for index, (u, v, w, _) in enumerate(edges):
candidate = distance[u] + w
if candidate < distance[v]:
distance[v] = candidate
predecessor[v] = index
changed = v
if changed is None:
origin = distance[ZERO]
return {v: distance[v] - origin for v in nodes}, ()
# An update on round N implies a negative cycle. Enter the cycle first.
vertex = changed
for _ in nodes:
vertex = edges[predecessor[vertex]][0]
start = vertex
backwards = []
while True:
edge = edges[predecessor[vertex]]
backwards.append(edge)
vertex = edge[0]
if vertex == start:
break
return None, tuple(reversed(backwards))
def solve_smt(names, atoms, clauses, budget=None):
"""Return the first integer model, exhaustive UNSAT, or budget UNKNOWN."""
if budget is not None and (type(budget) is not int or budget < 0):
raise ValueError('budget must be a nonnegative integer or None')
nodes, atoms, clauses = prepare(names, atoms, clauses)
tested = theory_checks = 0
last_conflict = None
def result(status, values=None, boolean=None):
return dict(status=status, values=values, boolean=boolean,
tested=tested, theory_checks=theory_checks,
last_conflict=last_conflict)
for bits in product((False, True), repeat=len(atoms)):
if budget is not None and tested >= budget:
return result('UNKNOWN')
tested += 1
if not all(any(bits[abs(lit) - 1] == (lit > 0) for lit in clause)
for clause in clauses):
continue
theory_checks += 1
values, cycle = _idl(nodes, atoms, bits)
if values is not None:
return result('SAT', values, bits)
last_conflict = dict(boolean=bits, cycle=cycle)
return result('UNSAT')
names = ('A', 'B')
atoms = (('A', 'B', -2), ('B', 'A', -1), ('A', 'B', 0))
clauses = ((1, 2), (3,))
answer = solve_smt(names, atoms, clauses)
print(answer['status'], answer['values'], answer['boolean'])
print(answer['tested'], answer['theory_checks'])
print(answer['last_conflict'])
print('cap 4:', solve_smt(names, atoms, clauses, budget=4)['status'])
print('force B first:', solve_smt(names, atoms, clauses + ((2,),))['status'])
The output is deterministic:
SAT {'$0': 0, 'A': -2, 'B': 0} (True, False, True)
6 2
{'boolean': (False, True, True), 'cycle': (('B', 'A', 0, 3), ('A', 'B', -1, 2))}
cap 4: UNKNOWN
force B first: UNSAT
The first CNF-satisfying setting is the fourth Boolean candidate, (False, True, True). Its cycle uses p₃ and p₂, with total weight −1. The sixth candidate gives the returned model, after two theory checks. At budget 4 the failed branch has been checked, but viable candidates remain; budget 5 is also UNKNOWN and budget 6 reaches SAT. Requiring p₂ as an extra unit clause rejects both CNF-satisfying settings and ends with UNSAT after all eight candidates and two theory checks.
For a safe work bound, let N include the zero reference, m be the number of atoms, q the number of clauses, L the number of literal occurrences, T the inspected Boolean settings and K the theory calls. Input validation costs O(1 + N + m + q + L). Building a tuple and checking its clauses costs O(1 + m + q + L) per setting. Each theory call builds m edges, scans them at most N times, and may reconstruct at most N cycle edges. Therefore:
The program uses O(1 + N + m + q + L) space, including its copied input, current graph, one witness or cycle and the most recent conflicting Boolean tuple. It stores neither all candidates nor all conflicts. These bounds treat variable names as atomic identifiers, use unit-cost integer operations and assume expected constant-time dictionary access; Python’s integer arithmetic also depends on operand bit length. The exponential enumeration describes this teaching solver, not a lower bound for every solver or a complexity classification for all SMT.
Choose the theory before choosing the solver
The example separates Boolean search from arithmetic feasibility, but it implements no conflict-driven clause learning, incremental theory state or theory propagation. The Z3 authors describe a CDCL(T) core in which SAT search and theory solvers exchange consequences and conflicts. Learning from a rejected branch can eliminate many later branches. That architecture is described in Programming Z3, §6.1; our exhaustive program is not an implementation of that core.
The zero reference is an origin, not a nonnegativity rule. To require X ≥ 0, add $0 - X <= 0 as an atom and require its positive literal. With no such rule, a negative start time is a valid model. A solver cannot infer an omitted deadline, resource limit or business objective. SAT answers feasibility; this program does not minimize completion time or count models.
Theory choice changes meaning. Int models mathematical integers, while fixed-width bit-vectors model finite bit patterns with their own operations. Real arithmetic permits values between consecutive integers. Uninterpreted functions constrain consistent use of a function without supplying an arithmetic formula for it; arrays provide read/write semantics. Quantifiers add another dimension to the problem. The official SMT-LIB logic catalogue distinguishes these families. General SMT is not one single complexity class or one universally terminating algorithm.
Our API handles a narrow QF_IDL fragment: CNF over difference-inequality atoms, with no independent Boolean variables, SMT-LIB parser, arrays, functions or quantifiers. Translating a larger expression into this input requires a correct encoding. A timeout from another solver may have a different cause from this program’s candidate budget, even if both interfaces use the word UNKNOWN.
Check the boundary, the witness and the stopping rule
1. Negate a negative bound
Let p mean X − Y ≤ −3. Write its integer complement. Does X − Y = −3 satisfy that complement?
Answer: The complement is X − Y ≥ −2, or Y − X ≤ 2. Equality at −3 makes p true, so it must fail the complement. Replacing the bound by 3 would incorrectly include that equality case.
2. Audit the returned times
Verify every atom for A = −2 and B = 0. Can both times be shifted by 2? What changes if a positive atom B − $0 ≤ 1 is added?
Answer: A − B = −2 satisfies p₁ and p₃; B − A = 2 makes p₂ false. The original constraints depend only on A − B, so shifting to A = 0, B = 2 preserves them. The added bound anchors B to the zero reference: the original witness still meets B ≤ 1, while the shifted one does not. Satisfiability remains true, but arbitrary translation of the activity times is no longer a symmetry of the augmented model.
3. A cycle is not yet a global refutation
What can be concluded from the weight −1 cycle at budget 4? How many Boolean settings and theory checks are needed when the extra unit clause (2,) forces B first?
Answer: The cycle rules out (False, True, True). Budget 4 and budget 5 both leave the original formula UNKNOWN; budget 6 finds its witness. With (2,), the two CNF-satisfying settings are (False, True, True) and (True, True, True), and both have contradictory arithmetic. The implementation inspects all eight settings, invokes the theory checker twice and returns UNSAT. A final stored cycle alone does not certify that those eight cases were exhausted.
4. Can bounded testing check unbounded integers?
For a fixed finite atom set, let C bound the absolute edge weight under either truth value. Explain why directly enumerating a finite integer box can nevertheless be a complete test oracle for the Boolean truth patterns of this fragment.
Answer: In any feasible selected graph, a shortest simple path from the temporary source uses at most N − 1 original edges. Distances lie between −(N − 1)C and 0. After subtracting the zero-reference distance, every variable therefore has some realizing value in the box
Thus every realizable truth pattern has a representative in that box. Tests can enumerate the box and evaluate the original inequalities directly. This argument justifies a small oracle; it does not make brute integer enumeration efficient. The solver itself supplies no finite domain and never enumerates this box.
Read the semantics and check the certificates
The SMT-LIB QF_IDL entry specifies the background integer theory and permitted atomic forms; the entry identifies its last update as 21 July 2024. The MIT lecture transcript supplies the difference-constraint graph argument. Programming Z3 connects Boolean abstraction to practical theory solvers. The lab, implementation and exercises here are original; no source program or figure is reproduced.
The accompanying tests compare each conjunction with Floyd–Warshall all-pairs closure, check every returned cycle’s provenance and weight, and compare full formulas with direct integer models using the proved box bound. They also cover disconnected contradictions, equality boundaries, self-atoms, repeated atoms, empty formulas, large integers, input validation, budget prefixes and bilingual code/equation agreement. These are AI-assisted technical checks on a finite teaching implementation, not human review or verification of a production SMT solver. Continue to constraint propagation to compare repeated domain deductions with this chapter’s complete theory check.
Make a prediction, then check
For integer atom p: X−Y≤3, which inequality must the theory checker receive when p=False?
Learning objectives
- Distinguish Boolean-abstraction satisfiability from theory satisfiability over shared integer variables, and choose the appropriate background theory.
- Derive integer-difference complements, graph orientation, negative-cycle contradictions and integer shortest-path witnesses, explaining zero-reference normalization.
- Implement reproducible Boolean enumeration plus theory checks, correctly interpreting SAT, exhaustive UNSAT, budget UNKNOWN and branch-certificate scope.
- Check results independently with all-pairs closure and a proved integer-box oracle, accounting for work without generalizing to all SMT.
Prerequisites & connections
Explore related knowledge →References
- SMT-LIB — QF_IDL logic, version 2.7
Cesare Tinelli · 2024 - SMT-LIB — Logics catalogue
SMT-LIB initiative - Programming Z3
Nikolaj Bjørner; Leonardo de Moura; Lev Nachmanson; Christoph Wintersteiger - MIT 6.046J, Fall 2005 — Lecture 18 transcript: shortest paths and difference constraints
MIT 6.046J course staff · 2005
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent finite-state oracles, bilingual review and second-agent cross-checks; not independent human peer review.
- Reread both languages for SMT/SAT semantics, the QF_IDL fragment boundary, integer complement −c−1, y→x orientation, branch-only negative-cycle claims, all-zero initialization/disconnected graphs, N scans and predecessor recovery, anchor normalization, integer shortest-path witnesses and exhaustive completeness. Six display equations and Python match exactly; six anchors match in order, with four answered exercises per language; review written.
- Eight tests executed and passed. Independent Floyd–Warshall all-pairs closure checks all length0–3 multisets from27 atoms on3 vertices and all truth assignments:30,799 conjunction queries. Every witness or cycle is checked for provenance, closure and negative weight. Another48 seeded3-atom models each use406 CNFs, totaling19,488 full-formula checks against truth patterns from direct integer enumeration; the article proves why its finite test box covers unbounded-integer realizability.
- Also checked4 main-example formulas×10 budget prefixes;9 bounds×13 fixed integer values for complements and9 equality exclusions; disconnected negative cycles, zero cycles, no atoms/empty CNF/empty clauses, zero variables, self-atoms, duplicate atoms, unused variables,10^100 integers and edge orders, input preservation and validation failures. The main example takes6 candidates/2 theory calls for A=−2,B=0 and retains the fourth candidate’s weight−1 cycle; budgets4/5 give UNKNOWN,6 SAT, and forcing p2 gives UNSAT after8 candidates/2 theory calls.
- Compiled each locale individually using the repository math plugins and KaTeX strict:error/throwOnError:true, then checked actual HTML via React renderToStaticMarkup:6 display equations and4 strong answer labels each, no KaTeX error or literal double asterisks. Final targeted stock-phrase scan had no hits. These are AI-assisted technical self-checks, not human review; no whole-site build, browser acceptance or production SMT backend tests. Only /tmp/aiwiki-next-smt was written.
- Read both complete articles, example.py, all eight tests and metadata without edits. Verified integer complement −c−1, edge orientation, N-pass all-zero Bellman–Ford and predecessor-cycle recovery, zero-origin normalization, branch-only certificates versus global UNSAT, candidate-count budgets and empty/self/duplicate cases. The finite-box proof is valid: every feasible truth pattern has a zero-relative representative within ±(N−1)C. Time/space bounds include N≥1 and zero atoms/clauses and state the unit-cost integer assumption.
- The independent script enumerates simple directed cycles as its feasibility reference, using neither author Bellman–Ford nor author-test Floyd–Warshall or integer-box enumeration. It exhausts length 0–4 multisets from 12 atoms on two vertices and adds 350 seeded models with 1–6 vertices and 0–7 atoms, checking every Boolean setting: 36,020 conjunctions. Checked every integer witness/origin/truth pattern/box bound and every returned cycle for literal provenance, closure, simplicity and negative weight.
- For those 2,170 models, generated one CNF allowing duplicates, tautologies and empty clauses, and ran caps 0, 1, 2, 2^m−1, 2^m and None: 13,020 runs. Verdict, first SAT Boolean witness, tested/theory_checks, latest failed branch, UNKNOWN versus exhaustion and unchanged input all agree. This covers the stated finite parameter set, not formal verification of arbitrary SMT or every Python failure.
- Reran all eight author tests successfully. Both Python blocks and six equations match exactly, with six stable anchors and four paired answers. Independently compiled with repository math plugins and strict:error/throwOnError:true KaTeX and actually rendered React static HTML: six displays/four strong answer labels each, no KaTeX errors or literal double asterisks outside code. Wrote only /tmp reference and review JSON; no draft/repository changes, whole-site or browser checks.
- Promotion preserves full prose, equations, program and exercises. Test loading alone changes from temporary drafts to repository articles; implementation and oracle logic are unchanged. Final review binds both MDX SHA-256 hashes.
- After promotion, the SMT bilingual test still required draft status written; it now explicitly requires published status checked. Secondary article readers in DPLL/CDCL/SMT also use repository paths, removing temporary example.py conditions and draft skips. Full bilingual parity and independent mathematical oracles remain, without weakening the assertion to accept arbitrary states.
Source locations checked:
- SMT-LIB — QF_IDL logic, version 2.7 · Actually read logics-all.shtml QF_IDL heading and lines634–663: version2.7, release/last-updated2024-07-21, Ints theory, Bool atoms and integer difference comparisons. Raw file click failed; full official HTML entry was readable. The program admits CNF of <= atoms plus a normalized zero origin and does not claim the entire SMT-LIB syntax.
- SMT-LIB — Logics catalogue · Actually read catalogue lines12–27 (sublogics and QF/IDL/IA/RA/BV/UF naming),59–72 (IDL and neighboring arithmetic/UF families). Only stable family distinctions are used, not later catalogue additions or a general SMT complexity classification.
- Programming Z3 · Actually read title/authors lines0–4, introduction around141, sorts239–240, arithmetic365–400, bit-vectors482–507 and §6.1 lines1105–1126 plus1159–1213 on CDCL(T), Boolean abstraction, clause learning and theory propagation. Source arithmetic implementation table is not a claim that this example reproduces Z3’s IDL implementation. No code execution/asset copying or website publication-date claim.
- MIT 6.046J, Fall 2005 — Lecture 18 transcript: shortest paths and difference constraints · Actually read28-page official lecture transcript: pp1–4 lines17–94 Bellman–Ford and final negative-cycle scan; pp7–10 lines140–240 early stopping/simple-path argument; pp18–19 lines414–448 inequality-to-edge orientation; pp19–21 lines448–493 cycle summation; pp21–24 lines498–558 zero-weight extra source and distance witness proof. Lines560–565 contain a contradictory transcription/utterance, explicitly not adopted. Classroom O(mn) assumes nontrivial counts (lines579–584); article derives its own zero-case-safe bound. No video/board visual inspection.
- SMT-LIB — QF_IDL logic, version 2.7 · Independently opened the official HTML QF_IDL entry and read lines 634–663: 2.7, last-updated 2024-07-21, Ints background, Bool atoms and allowed integer comparisons. Confirmed the article marks its <= CNF interface as a narrower fragment.
- SMT-LIB — Logics catalogue · Independently opened official catalogue lines 12–29 and 59–65 for sublogics, QF/IDL/IA/RA/BV/UF distinctions. No fresh release-date inference.
- Programming Z3 · Independently read official author tutorial §3.2 lines 365–400 and §6.1–6.1.1 lines 1105–1213: unbounded integers versus bit-vectors, IDL table, Boolean abstraction, theory rejection, learning and theory propagation. Did not run Z3 or conflate article Bellman–Ford with the tutorial’s IDL backend table.
- MIT 6.046J, Fall 2005 — Lecture 18 transcript: shortest paths and difference constraints · Independently opened official 28-page PDF text. Read Bellman–Ford scans lines 17–84 (PDF pages 1–4) and edge direction / telescoping contradiction / extra source / shortest-path witness lines 402–584 (PDF pages 18–25). Read the contradictory no-negative-cycle sentence at lines 560–565 and confirmed it is excluded in author metadata. Text inspection only; no video/board or rendered PDF visual verification by this reviewer.
Related topics