Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Solving constraints with SAT

Many problems ask for values that keep a list of rules: a puzzle, a timetable, a set of options that must fit together, or two pieces of code that must agree on every input. A SAT solver solves such a problem once you write the rules as clauses over true-or-false variables. The standard library has two solvers, both written in Vx:

  • std::algo::sat solves clauses. It is a CDCL solver (conflict-driven clause learning), in the style of MiniSat.
  • std::algo::smt solves formulas over fixed-width integers. It reads the standard SMT-LIB text format, and it uses std::algo::sat to find the answer.

vxc can use these solvers in place of z3 for some of its own checks, and #4268 plans to replace z3 with them.

Variables, literals and clauses

  • A variable has a number: 1, 2, 3 and so on. Its value is true or false.
  • A literal is a variable v, or its negation -v.
  • A clause is a list of literals. It holds when at least one of its literals is true.
  • A formula is a list of clauses. It holds when each of its clauses holds.

solve gives one of three answers:

  • Answer::Sat: values exist that make each clause hold. value(v) gives the value of variable v.
  • Answer::Unsat: no such values exist.
  • Answer::Unknown: the solver reached its step limit before it found an answer. A solver has no limit until you set one.

A first program

Three rules decide who comes to a party. Variable 1 is true when Alice comes, 2 when Bob comes, and 3 when Carol comes (book_sat_who_comes_to_the_party.vx):

import std::algo::sat;
import std::vec;

// Variable 1 is true when Alice comes, 2 when Bob comes, and 3 when Carol comes.
const ALICE : i32 = 1;
const BOB : i32 = 2;
const CAROL : i32 = 3;

// Adds the clause "a or b". When `b` is 0, the clause is only `a`.
fn clause(s : &mut Solver, a : i32, b : i32) -> void {
  let mut lits = Vec<i32>::new();
  lits.push(a);
  if b != 0 {
    lits.push(b);
  }
  s.add_clause(&lits);
}

fn report(s : &mut Solver) -> void {
  match s.solve() {
    Answer::Sat => {
      println!("sat: alice={} bob={} carol={}", s.value(ALICE), s.value(BOB), s.value(CAROL));
    },
    Answer::Unsat => {
      println!("unsat: no guest list keeps each rule");
    },
    Answer::Unknown => {
      println!("unknown");
    }
  }
}

fn main() -> i32 {
  let mut s = Solver::new();
  // If Alice comes, Bob comes: "Alice does not come, or Bob comes".
  clause(&mut s, -ALICE, BOB);
  // Bob and Carol do not both come.
  clause(&mut s, -BOB, -CAROL);
  // Alice or Carol comes.
  clause(&mut s, ALICE, CAROL);
  report(&mut s);
  // Carol cannot come.
  clause(&mut s, -CAROL, 0);
  report(&mut s);
  // Bob cannot come either.
  clause(&mut s, -BOB, 0);
  report(&mut s);
  return 0;
}

It prints:

sat: alice=false bob=false carol=true
sat: alice=true bob=true carol=false
unsat: no guest list keeps each rule
  • The rule “if Alice comes, Bob comes” is the clause -1 2: Alice does not come, or Bob comes.
  • A program can add clauses after solve, and call solve again. During a search, the solver adds learned clauses, which follow from the other clauses. It keeps them, so the next search is often faster.
  • After the last two clauses, neither Bob nor Carol can come. Alice cannot come either, because if she comes, Bob comes. But Alice or Carol must come, so the answer is Unsat.

Rules as clauses

Most rules become clauses in one of these ways:

RuleClauses
a is truea
if a, then b-a b
a exactly when b-a b and a -b
at least one of x1 to xnx1 x2 ... xn
at most one of x1 to xn-xi -xj for each pair i < j
exactly one of x1 to xnthe clauses of “at least one” and of “at most one”
c is a and b-c a, -c b and c -a -b
c is a or bc -a, c -b and -c a b
c is a xor b-c a b, -c -a -b, c -a b and c a -b

The last three rows make a new variable c equal to a part of a formula. Then a large formula becomes many short clauses, with one new variable for each part. This is the Tseitin translation. new_var gives the number of a new variable.

“At most one” needs a clause for each pair. For 8 variables, that is 28 clauses. For 1000 variables, it is 499,500 clauses. With extra variables, a long list needs fewer clauses. The sequential counter is one such translation.

Eight queens

Put eight queens on a chess board so that no two share a row, a column or a diagonal. Variable r * 8 + c + 1 is true when a queen stands on row r and column c. The program prints the first solution, then counts all of them (book_sat_eight_queens.vx):

import std::algo::sat;
import std::vec;

const N : i32 = 8;

// The variable that is true when a queen stands on row `r` and column `c`.
fn square(r : i32, c : i32) -> i32 {
  return r * N + c + 1;
}

// Adds "at most one of `lits` is true": a clause "not x or not y" for each pair.
fn at_most_one(s : &mut Solver, lits : &Vec<i32>) -> void {
  for i in 0..lits.len() {
    for j in (i + 1)..lits.len() {
      let mut pair = Vec<i32>::new();
      pair.push(-lits.get(i));
      pair.push(-lits.get(j));
      s.add_clause(&pair);
    }
  }
}

fn print_board(s : &Solver) -> void {
  for r in 0..N {
    for c in 0..N {
      if c > 0 {
        print!(" ");
      }
      if s.value(square(r, c)) {
        print!("Q");
      } else {
        print!(".");
      }
    }
    println!("");
  }
}

fn main() -> i32 {
  let mut s = Solver::new();
  for r in 0..N {
    // Each row has a queen, and at most one.
    let mut row = Vec<i32>::new();
    for c in 0..N {
      row.push(square(r, c));
    }
    s.add_clause(&row);
    at_most_one(&mut s, &row);
  }
  for c in 0..N {
    let mut column = Vec<i32>::new();
    for r in 0..N {
      column.push(square(r, c));
    }
    at_most_one(&mut s, &column);
  }
  // Along one diagonal, r - c is the same. Along one antidiagonal, r + c is the same.
  for d in (1 - N)..N {
    let mut diagonal = Vec<i32>::new();
    for r in 0..N {
      if r - d >= 0 && r - d < N {
        diagonal.push(square(r, r - d));
      }
    }
    at_most_one(&mut s, &diagonal);
  }
  for e in 0..(2 * N - 1) {
    let mut antidiagonal = Vec<i32>::new();
    for r in 0..N {
      if e - r >= 0 && e - r < N {
        antidiagonal.push(square(r, e - r));
      }
    }
    at_most_one(&mut s, &antidiagonal);
  }
  let mut count = 0;
  loop {
    match s.solve() {
      Answer::Sat => {},
      _ => {
        break;
      }
    }
    count += 1;
    if count == 1 {
      print_board(&s);
    }
    // Block this solution: at least one of its queens must stand somewhere else.
    let mut block = Vec<i32>::new();
    for v in 1..(N * N + 1) {
      if s.value(v) {
        block.push(-v);
      }
    }
    s.add_clause(&block);
  }
  println!("{} solutions", count);
  return 0;
}

It prints:

. . . . . . . Q
. Q . . . . . .
. . . . Q . . .
. . Q . . . . .
Q . . . . . . .
. . . . . . Q .
. . . Q . . . .
. . . . . Q . .
92 solutions
  • A function such as square gives each fact its variable number. Keep that mapping in one place.
  • To find every solution, add a blocking clause after each Sat: a clause that does not hold for this solution. Here the clause names the 8 squares with a queen. Each other solution moves at least one queen, so the clause holds for it. When no solution remains, solve answers Unsat.

When no solution exists

Put 3 pigeons in 2 holes, so that each pigeon sits in a hole and no two pigeons share a hole. Variable p * 2 + h + 1 is true when pigeon p sits in hole h. The program also tries 10 pigeons in 9 holes, with a limit on the steps of the search (book_sat_pigeons_and_holes.vx):

import std::algo::sat;
import std::string;
import std::vec;

// The variable that is true when pigeon `p` sits in hole `h`.
fn sits(p : i32, h : i32, holes : i32) -> i32 {
  return p * holes + h + 1;
}

// Adds the clauses: each pigeon sits in a hole, and no two pigeons sit in one hole.
fn add_pigeons(s : &mut Solver, pigeons : i32, holes : i32) -> void {
  for p in 0..pigeons {
    let mut some_hole = Vec<i32>::new();
    for h in 0..holes {
      some_hole.push(sits(p, h, holes));
    }
    s.add_clause(&some_hole);
  }
  for h in 0..holes {
    for p in 0..pigeons {
      for q in (p + 1)..pigeons {
        let mut not_both = Vec<i32>::new();
        not_both.push(-sits(p, h, holes));
        not_both.push(-sits(q, h, holes));
        s.add_clause(&not_both);
      }
    }
  }
}

fn name(a : Answer) -> String {
  match a {
    Answer::Sat => {
      return unsafe { String::from_c_str("sat") };
    },
    Answer::Unsat => {
      return unsafe { String::from_c_str("unsat") };
    },
    Answer::Unknown => {
      return unsafe { String::from_c_str("unknown") };
    }
  }
}

fn main() -> i32 {
  let mut small = Solver::new();
  small.enable_proof();
  add_pigeons(&mut small, 3, 2);
  let a = small.solve();
  println!("3 pigeons, 2 holes: {}", name(a));
  println!("{} clauses, {} proof steps", small.num_input_clauses(), small.proof_len());
  let mut proof = Vec<u8>::new();
  for k in 0..small.proof_len() {
    small.write_lrat_step(k, &mut proof);
  }
  let text = String::from_utf8(&proof).unwrap();
  print!("{}", text);

  let mut large = Solver::new();
  large.set_step_limit(100000i64);
  add_pigeons(&mut large, 10, 9);
  let b = large.solve();
  println!("10 pigeons, 9 holes: {} after {} conflicts", name(b), large.num_conflicts());
  return 0;
}

It prints:

3 pigeons, 2 holes: unsat
9 clauses, 7 proof steps
10 -2 0 7 8 2 3 6 0
11 1 0 10 1 0
12 -3 0 11 4 0
13 -5 0 11 5 0
14 4 0 12 2 0
15 6 0 13 3 0
16 0 15 14 9 0
10 pigeons, 9 holes: unknown after 6154 conflicts

A proof of Unsat

A wrong Sat is easy to check: put the values in each clause. A wrong Unsat is not, so the solver can write a proof. Call enable_proof before the first add_clause. After Unsat, the proof is in the LRAT format, one step on each line:

id  literals  0  hints  0
  • Each step adds a clause that follows from earlier clauses. The input clauses have the ids 1 to 9, in the order of add_clause, so the first step has the id 10.
  • The hints are the ids of the clauses that show why the new clause follows.
  • The last step adds the empty clause, which has no literals. If a formula implies the empty clause, the formula has no solution.

To check a step, assume that its clause is false. Then use each hint in order. Each hint must force one more value. The clause of the last hint must become false. Step 10 says -2: pigeon 0 is not in hole 1. Assume that pigeon 0 is in hole 1. Then variable 2 is true.

HintClauseWhat it gives
7-2 -4pigeon 1 is not in hole 1
8-2 -6pigeon 2 is not in hole 1
23 4pigeon 1 is in hole 0
35 6pigeon 2 is in hole 0
6-3 -5false: pigeons 1 and 2 are both in hole 0

A checker needs only this one check, so it can be short and simple. lrat-check, in the drat-trim repository, reads a DIMACS file and an LRAT proof. vxc has its own checker for the proofs of the queries that it sends.

A step limit

Some formulas need a very long search. A CDCL search that answers Unsat builds a proof by resolution: each step joins two clauses into one. For a pigeon formula, each such proof is exponentially long in the number of pigeons. set_step_limit sets the most steps that one solve may take. A step is a value that the search gives a variable, or a conflict: a clause with each literal false. The limit counts steps, not seconds, so the answer is the same on each machine. In this run, the limit of 100,000 steps stopped the search after 6154 conflicts.

Reading DIMACS files

DIMACS is the text format of the SAT Competition. A line p cnf <variables> <clauses> comes first, and each clause is a list of literals that ends with 0. add_dimacs reads it. It gives the number of clauses. For text with an error, it gives the position of the first wrong byte (book_sat_read_dimacs.vx):

import core::result;
import std::algo::sat;
import std::string;
import std::vec;

fn read(s : &mut Solver, text : &String) -> void {
  match s.add_dimacs(&text.to_bytes()) {
    Result<i32, i64>::Ok(n) => {
      println!("{} clauses", n);
    },
    Result<i32, i64>::Err(at) => {
      println!("not DIMACS at byte {}", at);
    }
  }
}

fn main() -> i32 {
  let mut s = Solver::new();
  // A comment, the header (2 variables, 2 clauses), then "x1 or x2" and "not x1".
  let good = unsafe {
    String::from_c_str("c an example\np cnf 2 2\n1 2 0\n-1 0\n")
  };
  read(&mut s, &good);
  match s.solve() {
    Answer::Sat => {
      println!("sat: x1={} x2={}", s.value(1), s.value(2));
    },
    _ => {
      println!("no solution");
    }
  }
  // The `x` at byte 12 is not a literal.
  let bad = unsafe { String::from_c_str("p cnf 1 1\n1 x 0\n") };
  read(&mut s, &bad);
  return 0;
}

It prints:

2 clauses
sat: x1=false x2=true
not DIMACS at byte 12

benchmarks/sat_solver/solve.vx is a complete program that reads a DIMACS file and solves it. The reports in benchmarks/sat_solver compare the solver with CaDiCaL and Kissat.

Integers of fixed width

Many questions about code are questions about integers of a fixed width: does this bit trick give the right answer for every u32? std::algo::smt answers them. A Session reads commands in SMT-LIB, the standard text format of SMT solvers, and writes the answers, as z3 -in does. It makes one SAT variable for each bit of each number, and solves the clauses with std::algo::sat.

The SMT-LIB logic is QF_BV. Its numbers are bit-vectors: (_ BitVec 32) is a 32-bit number. The operators include bvadd, bvsub, bvmul, bvand, bvor, bvxor, bvnot, bvneg, the comparisons (bvult, bvslt and the others), concat and extract. Division, remainder and shifts are not there yet.

This program factors 143, and tests two claims about +, |, & and ^ (book_smt_bit_vectors.vx):

import std::algo::smt;
import std::string;
import std::vec;

// Runs the SMT-LIB commands of `text`, and prints the answers.
fn run(s : &mut Session, text : &String) -> void {
  let mut out = String::new();
  s.run(&text.to_bytes(), &mut out);
  print!("{}", out);
}

fn main() -> i32 {
  let mut s = Session::new();
  // Two numbers above 1 whose product is 143. Below 256, the 16-bit product cannot wrap.
  let factor = unsafe {
    String::from_c_str("(set-logic QF_BV)
(declare-const x (_ BitVec 16))
(declare-const y (_ BitVec 16))
(push 1)
(assert (= (bvmul x y) #x008f))
(assert (bvugt x #x0001))
(assert (bvult x y))
(assert (bvult y #x0100))
(check-sat)
(get-value (x y))
(pop 1)")
  };
  run(&mut s, &factor);
  // To prove a fact for each value, ask for a value where it is false. `unsat` means none exists.
  let identities = unsafe {
    String::from_c_str("(declare-const a (_ BitVec 32))
(declare-const b (_ BitVec 32))
(push 1)
(assert (not (= (bvadd a b) (bvadd (bvor a b) (bvand a b)))))
(check-sat)
(pop 1)
(push 1)
(assert (not (= (bvadd a b) (bvxor a b))))
(check-sat)
(get-value (a b))
(pop 1)")
  };
  run(&mut s, &identities);
  return 0;
}

It prints:

sat
((x #x000b)
 (y #x000d))
unsat
sat
((a #x40000000)
 (b #xfffffffe))
  • get-value gives values in hexadecimal: x is 11 and y is 13, and 11 × 13 = 143.
  • push and pop put assertions in a scope. pop removes the assertions made after the matching push.
  • To prove a fact for every value, assert that the fact is false. If the answer is unsat, no value makes the fact false. So a + b == (a | b) + (a & b) holds for each of the 2^64 pairs of 32-bit numbers.
  • a + b == a ^ b does not hold. For the values above, a + b is #x3ffffffe and a ^ b is #xbffffffe. Bit 30 is 1 in both numbers, so its carry changes bit 31 of the sum.
  • String::from_c_str needs unsafe, because a string literal is a C pointer. #4331 tracks a safe way to make a String from a string literal.

After (set-option :produce-proofs true), (get-proof) gives the LRAT proof of an unsat answer.

How the solvers work

docs/solver/ explains the inside of the solvers, with examples: how the CDCL search works, the LRAT format, how operators become clauses, and how vxc checks each answer.