Algorithm Search⌘K

Algorithmresearch

SAT-based design debugging

Also called Smith-Veneris debugging, SAT-based error localization.

Smith, Veneris and coauthors' method that adds a multiplexer at each suspect gate and asks a SAT solver which few gates can be changed to fix all failing traces.

Time
O(G^k 2^V V) worst
Space
O(V) extra
Where
G = the number of suspect gates; V = the number of variables and literals of the debug instance; k = the size of the corrections found
Properties
completedeterministicexactiterative
Origin
Alexander Smith, Andreas Veneris, Moayad Fahim Ali, Anastasios Viglas, 2005

SAT-based design debugging finds where a circuit that fails a set of tests can be changed so that it passes them. Smith, Veneris, Ali and Viglas (2005) build one formula. It holds a copy of the circuit for each test, with the inputs fixed to the test vector and the outputs fixed to the expected values. At each suspect gate a multiplexer chooses between the gate's own value and a free value. The select line of the multiplexer is one variable shared by all copies, and a cardinality constraint allows at most kk selects to be true. A model of the formula names kk gates and gives new values for them in each test that make every test pass. The gates are the places to look for the bug. Blocking each answer and solving again lists all sets of kk gates, and raising kk from 0 finds the least number of changes that explains the failures. The proof on this page shows that a select set makes the formula satisfiable exactly when those gates have new values that fix all tests.

In plain words

A circuit gives the wrong answer on some tests. You want to know which gates to look at.

Put a switch at every gate. When a switch is on, the gate's output is cut and replaced by any value you like. When it is off, the gate works as normal. Now ask a SAT solver: with at most one switch on, is there a choice of replacement values that makes every test give the right answer? Each switch is the same in all tests, but the replacement value may differ from test to test.

If the answer is yes, the switch that is on names a gate that can explain all the failures. Forbid that answer and ask again to find the others. If no single gate works, allow two switches, and so on.

The problem

Given a combinational circuit CC with gates in topological order, a set Σ\Sigma of suspect gates, tests (vj,yj)(v_j, y_j) for j=1,…,Tj = 1, \ldots, T, each an input vector and the expected outputs, and a bound kmax⁡k_{\max}. A set S⊆ΣS \subseteq \Sigma has correction values if there are values ω(g,j)∈{0,1}\omega(g, j) \in \{0, 1\} for g∈Sg \in S such that, for every test jj, simulating CC on vjv_j with each g∈Sg \in S forced to ω(g,j)\omega(g, j) gives yjy_j. Find the least k≤kmax⁡k \le k_{\max} for which a set of kk suspects has correction values, and all such sets of size kk. When the test inputs are pairwise distinct, SS has correction values exactly when the gates of SS can be replaced by new logic of the primary inputs that passes all tests. Usually the tests are the failing vectors that verification found, often with some passing vectors added so that the fix does not break them.

The algorithm

  1. SAT-DEBUG(C, Σ, tests, k_max)
  2. 1for each test (v_j, y_j) do make a copy C_j of the circuit, with units for the inputs v_j and the expected outputs y_j
  3. 2for each suspect g in Σ do replace g in C_j by MUX(s_g, w_{g,j}, op_g(fanins in C_j)), with s_g shared and w_{g,j} free
  4. 3write every other gate of C_j with its Tseitin clauses; F ← the conjunction of all copies
  5. 4for k ← 0 to k_max do
  6. 5F_k ← F ∧ (at most k of the selects s_g are true), by a sequential counter
  7. 6while F_k has a model M do
  8. 7S ← {g in Σ : s_g is true in M}
  9. 8report S; add the clause ∨_{g in S} ¬s_g to F_k ▷ block S and its supersets
  10. 9if some S was reported then return k and the reported sets
  11. 10return no set of at most k_max suspects explains the tests

The multiplexer of line L2 is four clauses: sg⇒(gj⇔wg,j)s_g \Rightarrow (g_j \Leftrightarrow w_{g,j}) and ¬sg⇒(gj⇔og,j)\neg s_g \Rightarrow (g_j \Leftrightarrow o_{g,j}), where og,jo_{g,j} is the gate's own value in copy jj. Line L5 uses the sequential counter of Sinz. The code of this page calls a small DPLL solver that decides the selects first, false before true.

Example

The intended circuit has inputs a,b,ca, b, c and gates g1=a∨bg_1 = a \vee b, g2=b∧cg_2 = b \wedge c, g3=g1⊕cg_3 = g_1 \oplus c and g4=g1∨g2g_4 = g_1 \vee g_2, with outputs g3g_3 and g4g_4. The implementation has the bug g1=a∧bg_1 = a \wedge b. It fails on the four vectors with a≠ba \ne b. Take the two failing tests abc=010abc = 010 and 011011.

test expected (g3,g4)(g_3, g_4) circuit (g3,g4)(g_3, g_4)
010010 (1,1)(1, 1) (0,0)(0, 0)
011011 (0,1)(0, 1) (1,1)(1, 1)

With all four gates suspect, the instance has 36 variables and 72 clauses. For k=0k = 0 the units propagate through both copies, and the outputs contradict the expected values, so line L6 finds no model. For k=1k = 1:

  • g1g_1. With wg1,1=wg1,2=1w_{g_1, 1} = w_{g_1, 2} = 1, both copies compute the intended values. This is the model that line L6 finds, and line L8 blocks {g1}\{g_1\}.
  • g3g_3 alone. It can fix g3g_3 in both tests, but g4=0g_4 = 0 in the first test stays wrong.
  • g4g_4 alone. It fixes g4g_4, but g3g_3 stays wrong in both tests.
  • g2g_2 alone. Setting g2=1g_2 = 1 in the first test fixes g4g_4, but g3=g1⊕c=0g_3 = g_1 \oplus c = 0 stays wrong.

After the blocking clause the formula is unsatisfiable, so the answer is k=1k = 1 and the one set {g1}\{g_1\}, with the correction value 1 in both tests. If k=2k = 2 were asked, the sets {g2,g3}\{g_2, g_3\} and {g3,g4}\{g_3, g_4\} would also explain the tests, besides the supersets of {g1}\{g_1\}.

Correctness

Two facts carry the proof. First, for a fixed select set SS, a model of the formula is the same thing as a set of correction values for SS: by induction over the topological order, each variable of copy jj equals the value of its signal in the simulation of test jj with the gates of SS forced to wg,jw_{g,j}, and the output units say that this simulation passes. Second, correction values are monotone: a set that works stays working when gates are added, by forcing each added gate to the value it has anyway. So at the first kk with a model, every model has exactly kk selects true, the blocking clause of line L8 removes exactly one set, and each set of size kk that works is a model of all the other blocking clauses. The loop therefore lists exactly the sets of size kk with correction values. When the test inputs are distinct, these are exactly the sets of kk gates that new logic can fix for the tests. The full proof, with the Tseitin clauses and the counter, is in the proof file.

The tests compare the result with brute force on 120 random circuits of 4 inputs and 10 gates, each with one gate of the wrong type and up to 3 failing tests. The brute force tries every single gate with every vector of values over the tests. The sets agree, the real error site is in a reported set, and the correction values of each set pass the tests in simulation. On 40 circuits with two wrong gates, the least kk and the sets of size kk agree with brute force over all pairs. The Tseitin clauses of every gate type and the counter for up to 5 variables are checked against their truth tables.

Proof: The debug instance is satisfiable exactly when the selected gates can fix the tests, and the loop reports all fixes of least sizefull

Setting. The circuit CC has inputs x1,…,xnx_1, \ldots, x_n, gates g1,…,gmg_1, \ldots, g_m in topological order, each with a Boolean function opg\mathrm{op}_g of earlier signals, and a list of outputs. The tests are pairs (vj,yj)(v_j, y_j), j=1,…,Tj = 1, \ldots, T, of an input vector and the expected output values. Σ\Sigma is the set of suspect gates. For S⊆ΣS \subseteq \Sigma:

  • Correction values for SS are values ω(g,j)∈{0,1}\omega(g, j) \in \{0, 1\} for g∈Sg \in S and every test jj such that, for every jj, simulating CC on vjv_j with the value of each g∈Sg \in S replaced by ω(g,j)\omega(g, j) gives yjy_j at the outputs.
  • A fix for SS is a family of Boolean functions fg:{0,1}n→{0,1}f_g : \{0, 1\}^n \to \{0, 1\}, g∈Sg \in S, such that the circuit C[S←f]C[S \leftarrow f], in which each g∈Sg \in S is replaced by new logic that computes fgf_g of the primary inputs, gives yjy_j on vjv_j for every test.

The debug formula FF of lines L1 to L3 has, for each test jj, a variable uju_j for every signal uu, unit clauses xi,j=vj(xi)x_{i,j} = v_j(x_i) and yj=yj(y)y_{j} = y_j(y) for the outputs yy, the Tseitin clauses of gj=opg(faninsj)g_j = \mathrm{op}_g(\text{fanins}_j) for g∉Σg \notin \Sigma, and for g∈Σg \in \Sigma the Tseitin clauses of og,j=opg(faninsj)o_{g,j} = \mathrm{op}_g(\text{fanins}_j) and the four multiplexer clauses

(¬sg∨¬wg,j∨gj) (¬sg∨wg,j∨¬gj) (sg∨¬og,j∨gj) (sg∨og,j∨¬gj),(\neg s_g \vee \neg w_{g,j} \vee g_j)\,(\neg s_g \vee w_{g,j} \vee \neg g_j)\,(s_g \vee \neg o_{g,j} \vee g_j)\,(s_g \vee o_{g,j} \vee \neg g_j),

which say gj=wg,jg_j = w_{g,j} if sgs_g and gj=og,jg_j = o_{g,j} otherwise. The selects sgs_g are shared by all tests, and the wg,jw_{g,j} are free.

Lemma 1 (Tseitin clauses). For fixed values of the inputs ins\mathit{ins} and the output out\mathit{out} of a gate, its clauses, with their auxiliary variables, are satisfiable if and only if out=op(ins)\mathit{out} = \mathrm{op}(\mathit{ins}).

Proof. For AND, the clauses (¬out∨x)(\neg \mathit{out} \vee x) for each input and (out∨⋁¬x)(\mathit{out} \vee \bigvee \neg x) say out⇒⋀x\mathit{out} \Rightarrow \bigwedge x and ⋀x⇒out\bigwedge x \Rightarrow \mathit{out}. OR is dual, NAND and NOR use ¬out\neg \mathit{out} in place of out\mathit{out}, and NOT and BUF are two clauses of an equivalence. For XOR and XNOR, each auxiliary tt gets four clauses, one per row of the truth table of acc⊕x\mathit{acc} \oplus x, which force t=acc⊕xt = \mathit{acc} \oplus x. So the auxiliaries are determined, the last one is the XOR of all inputs, and the two final clauses say out\mathit{out} equals it or its negation. The tests check all gate types on all input values. □\square

Theorem 2 (selects and correction values). For S⊆ΣS \subseteq \Sigma, FF together with the units sgs_g for g∈Sg \in S and ¬sg\neg s_g for g∈Σ∖Sg \in \Sigma \setminus S is satisfiable if and only if SS has correction values.

Proof. (⇒\Rightarrow) Take a model and put ω(g,j)=wg,j\omega(g, j) = w_{g,j}. Fix a test jj and let val\mathrm{val} be the simulation of CC on vjv_j with the values of SS replaced by ω\omega. By induction over the topological order, uj=val(u)u_j = \mathrm{val}(u) in the model for every signal uu. The inputs agree by the unit clauses. For a gate g∉Σg \notin \Sigma, Lemma 1 gives gj=opgg_j = \mathrm{op}_g of the fanin variables, which agree with val\mathrm{val} by induction. For g∈Σ∖Sg \in \Sigma \setminus S, sgs_g is false, so gj=og,j=opg(…)g_j = o_{g,j} = \mathrm{op}_g(\ldots) in the same way. For g∈Sg \in S, gj=wg,j=ω(g,j)=val(g)g_j = w_{g,j} = \omega(g, j) = \mathrm{val}(g). The output units then say that val\mathrm{val} gives yjy_j.

(⇐\Leftarrow) Set sgs_g by SS, wg,j=ω(g,j)w_{g,j} = \omega(g, j) for g∈Sg \in S and wg,j=0w_{g,j} = 0 for the other suspects, each uju_j to val(u)\mathrm{val}(u) of test jj, each og,jo_{g,j} to opg\mathrm{op}_g of the fanin values, and the auxiliaries as in Lemma 1. The gate clauses hold by Lemma 1, the multiplexer clauses hold because gj=wg,jg_j = w_{g,j} for g∈Sg \in S and gj=og,jg_j = o_{g,j} for the other suspects, and the unit clauses hold because the inputs are vjv_j and ω\omega is a set of correction values. □\square

Theorem 3 (correction values and fixes). If SS has a fix, it has correction values. If the input vectors v1,…,vTv_1, \ldots, v_T are pairwise distinct, the converse holds.

Proof. Given a fix, simulate C[S←f]C[S \leftarrow f] on vjv_j and put ω(g,j)=fg(vj)\omega(g, j) = f_g(v_j). The simulation of CC with these replaced values computes the same values at every signal, by induction over the topological order, so it gives yjy_j. Conversely, with distinct vjv_j the definition fg(vj)=ω(g,j)f_g(v_j) = \omega(g, j), and fg=0f_g = 0 on the other input vectors, is a function, and the same induction shows that C[S←f]C[S \leftarrow f] gives yjy_j on each vjv_j. □\square

Without distinct vectors the converse fails: two tests with the same inputs and different expected outputs have correction values for the set of output gates, but no circuit passes both. The tests show this case.

Lemma 4 (monotone). If SS has correction values and S⊆S′⊆ΣS \subseteq S' \subseteq \Sigma, then S′S' has correction values.

Proof. For g∈S′∖Sg \in S' \setminus S put ω(g,j)\omega(g, j) equal to the value of gg in the simulation of test jj with the replaced values of SS. Replacing a value by itself changes nothing. □\square

Lemma 5 (sequential counter). For k<Nk < N, the counter clauses of line L5 on s1,…,sNs_1, \ldots, s_N with auxiliaries ri,jr_{i,j} (1≤i≤N−11 \le i \le N - 1, 1≤j≤k1 \le j \le k) are satisfiable together with a 0-1 assignment of the sis_i if and only if ∑isi≤k\sum_i s_i \le k. For k=0k = 0 they are the units ¬si\neg s_i, and for k≥Nk \ge N there are none.

Proof. The clauses are s1⇒r1,1s_1 \Rightarrow r_{1,1}, ¬r1,j\neg r_{1,j} for j>1j > 1, and for 1<i<N1 < i < N: si⇒ri,1s_i \Rightarrow r_{i,1}, ri−1,j⇒ri,jr_{i-1,j} \Rightarrow r_{i,j}, si∧ri−1,j−1⇒ri,js_i \wedge r_{i-1,j-1} \Rightarrow r_{i,j} for j>1j > 1, and ¬(si∧ri−1,k)\neg(s_i \wedge r_{i-1,k}), and last ¬(sN∧rN−1,k)\neg(s_N \wedge r_{N-1,k}). Let ci=∑t≤istc_i = \sum_{t \le i} s_t. (⇐\Leftarrow) Put ri,j=[ci≥j]r_{i,j} = [c_i \ge j]. Each implication holds because ci≥ci−1c_i \ge c_{i-1} and ci=ci−1+1c_i = c_{i-1} + 1 when si=1s_i = 1. ¬r1,j\neg r_{1,j} for j>1j > 1 holds as c1≤1c_1 \le 1. The clause ¬(si∧ri−1,k)\neg(s_i \wedge r_{i-1,k}) fails only if ci=ci−1+1≥k+1c_i = c_{i-1} + 1 \ge k + 1, which cN≤kc_N \le k excludes. (⇒\Rightarrow) In any model, ri,jr_{i,j} is true whenever ci≥jc_i \ge j, by induction on ii with the implications. If cN>kc_N > k, let ii be the index of the (k+1)(k+1)-th true ss. Then i>1i > 1 (for k≥1k \ge 1), ci−1=kc_{i-1} = k gives ri−1,kr_{i-1,k}, and si∧ri−1,ks_i \wedge r_{i-1,k} contradicts a clause. □\square

Theorem 6 (the loop). Let kk be the first value of line L4 at which line L6 finds a model. Then lines L6 to L8 report, each once, exactly the sets S⊆ΣS \subseteq \Sigma with ∣S∣=k\lvert S \rvert = k that have correction values, and no smaller set has correction values. If no k≤kmax⁡k \le k_{\max} finds a model, no set of at most kmax⁡k_{\max} suspects has correction values.

Proof. For k′<kk' < k the formula F∧(∑s≤k′)F \wedge (\sum s \le k') is unsatisfiable. If a set SS with ∣S∣≤k′\lvert S \rvert \le k' had correction values, Theorem 2 and Lemma 5 would give a model. So no set of size below kk has correction values, which also proves the last claim.

At kk, a model has a select set SS with ∣S∣≤k\lvert S \rvert \le k by Lemma 5, and the model itself satisfies the formula of Theorem 2 for SS, so SS has correction values. Hence ∣S∣=k\lvert S \rvert = k. The blocking clause ⋁g∈S¬sg\bigvee_{g \in S} \neg s_g of line L8 excludes exactly the models whose select set contains SS, and among sets of size at most kk that is SS alone. So no set is reported twice. Conversely, let SS have size kk and correction values. By Theorem 2 there is a model of FF with select set exactly SS. It satisfies the counter by Lemma 5, and every blocking clause of a reported set S′≠SS' \ne S, because ∣S′∣=∣S∣\lvert S' \rvert = \lvert S \rvert gives some g∈S′∖Sg \in S' \setminus S with sgs_g false. So the loop cannot stop at line L6 before SS is reported. Each round adds a clause that removes the reported set, there are finitely many sets, and so the loop ends. ■\blacksquare

Corollary. With pairwise distinct test inputs, the sets of Theorem 6 are exactly the sets of kk suspects that have a fix for the tests (Theorem 3), and by Lemma 4 every superset of a reported set also has one. A fix for the tests need not be a fix for the specification on inputs outside the tests.

Complexity

Let LL be the number of gates and pins of CC. The instance has V=O(TL+∣Σ∣k)V = O(T L + \lvert \Sigma \rvert k) variables and literals: one copy of the circuit per test, two extra variables and four clauses per suspect and test, and O(∣Σ∣k)O(\lvert \Sigma \rvert k) for the counter. Building it is linear in VV. Each call of the solver at line L6 takes O(2VV)O(2^V V) time in the worst case. The number of calls is at most kmax⁡+1k_{\max} + 1 plus the number of reported sets, which is at most (Gk)\binom{G}{k} for G=∣Σ∣G = \lvert \Sigma \rvert. Space is O(V)O(V).

The worst case cannot be avoided in general. Deciding whether a set of at most kk suspects has correction values is NP-complete. It is in NP, since SS and ω\omega can be checked by simulation. It is NP-hard by a reduction from circuit satisfiability: put a buffer with constant input 0 in front of each input xix_i of a circuit DD, make the buffers the suspects, and use one test with output 1 and kk equal to the number of inputs. Correction values are then exactly a satisfying assignment of DD. In practice the inputs of each copy are fixed, so unit propagation decides most of the formula once the selects are chosen.

Properties

  • Deterministic. The solver decides the variables in a fixed order, so the reported sets come in a fixed order.
  • Exact and complete for the tests. The reported sets are exactly the minimum-size sets of suspects with correction values. They say nothing about inputs outside the tests.
  • Not a repair. The result names locations and per-test values, not new gate functions. Finding the new logic is a separate step.

Variants and improvements

  • Sequential circuits. Ali, Veneris, Smith, Safarpour, Drechsler and Abadir (2004) unroll the circuit over the cycles of each failing trace, as in time-frame expansion. The select of a gate is shared by all cycles, and the free value is per cycle.
  • Maximum satisfiability. Chen, Safarpour, Marques-Silva and Veneris (2010) make the hard part the test copies and each ¬sg\neg s_g a soft clause. A correction set is then a minimal correction subset, and the least kk is the MaxSAT optimum. This drops the counter and allows core-guided solvers.
  • Unsatisfiable cores. Without multiplexers, the gates whose clauses appear in a minimal unsatisfiable subset of the test copies are candidates, which is cheaper but coarser.
  • Incremental solving. The copies do not change with kk. An incremental SAT solver keeps learned clauses and adds the counter and the blocking clauses with assumptions.
  • Fault diagnosis. With the tests of a failing chip in place of a specification, the same formula locates defects, as in effect-cause diagnosis. Smith and coauthors treat both uses.

When to use it

Use it after verification has found failing traces and the design has a reference: a golden model, a specification, or the expected values of a regression. It is the step between the miter or simulation that says "wrong" and the engineer who has to change the RTL. It fits when the bug is in few places. Many simultaneous errors need large kk, and the number of candidate sets grows like (Gk)\binom{G}{k}. For a first ranking, cheaper path-tracing or simulation-based methods find a superset of the candidates quickly, and the SAT step then prunes them.

Pitfalls

  • Too few tests. With one failing test, many gates can explain it, often every gate on the paths to the wrong outputs. Add more failing vectors, and passing vectors to keep the fix from breaking working behavior.
  • Equal inputs, different outputs. The free values are per test, so two tests with the same input vector and conflicting expected outputs still give a model. No circuit passes such tests. Remove duplicates before encoding.
  • Equivalent locations. A gate and a buffer chain or a gate with one fanout in front of it give the same corrections. The reported sets are candidates, not one true site.
  • Per-test values may not be a gate. The new values may not be a function of the gate's own fanins, so a reported set does not mean that a change of gate type fixes the bug.
  • A fix for the tests only. The reported sets pass the given tests. Check the repaired design against the full specification, for example with an equivalence check.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

dpll.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sat-based-design-debugging/. The authors are listed in prov/1D5R8Y.jsonl.
"""A small DPLL solver with two watched literals and chronological backtracking.

Literals are nonzero integers, -v is the negation of v. Clauses can be added
between calls of solve, which is enough for enumeration with blocking clauses.
"""

from __future__ import annotations

from typing import Iterable, Optional, Sequence


class Solver:
    def __init__(self) -> None:
        self.nvars = 0
        self.clauses: list[list[int]] = []
        self.units: list[int] = []
        self.empty = False
        self.order: list[int] = []          # decision order; others follow by index

    def new_var(self) -> int:
        self.nvars += 1
        return self.nvars

    def add_clause(self, lits: Iterable[int]) -> None:
        c = list(dict.fromkeys(lits))
        if any(-l in c for l in c):
            return                          # a tautology
        if not c:
            self.empty = True
        elif len(c) == 1:
            self.units.append(c[0])
        else:
            self.clauses.append(c)

    def solve(self, assumptions: Sequence[int] = ()) -> Optional[dict[int, bool]]:
        if self.empty:
            return None
        n = self.nvars
        val: list[Optional[bool]] = [None] * (n + 1)
        watches: dict[int, list[int]] = {}
        for ci, c in enumerate(self.clauses):
            watches.setdefault(c[0], []).append(ci)
            watches.setdefault(c[1], []).append(ci)
        trail: list[int] = []

        def value(lit: int) -> Optional[bool]:
            v = val[abs(lit)]
            return None if v is None else (v if lit > 0 else not v)

        def enqueue(lit: int) -> bool:
            v = value(lit)
            if v is not None:
                return v
            val[abs(lit)] = lit > 0
            trail.append(lit)
            return True

        def propagate(qhead: int) -> bool:
            """Unit propagation from trail[qhead:]; False on a conflict."""
            while qhead < len(trail):
                false_lit = -trail[qhead]
                qhead += 1
                ws = watches.get(false_lit, [])
                keep: list[int] = []
                ok = True
                for i, ci in enumerate(ws):
                    if not ok:
                        keep.append(ci)
                        continue
                    c = self.clauses[ci]
                    if c[0] == false_lit:
                        c[0], c[1] = c[1], c[0]
                    if value(c[0]) is True:
                        keep.append(ci)
                        continue
                    for k in range(2, len(c)):
                        if value(c[k]) is not False:
                            c[1], c[k] = c[k], c[1]
                            watches.setdefault(c[1], []).append(ci)
                            break
                    else:
                        keep.append(ci)
                        if not enqueue(c[0]):
                            ok = False
                watches[false_lit] = keep
                if not ok:
                    return False
            return True

        for lit in list(self.units) + list(assumptions):
            if not enqueue(lit):
                return None
        if not propagate(0):
            return None
        root = len(trail)
        order = list(dict.fromkeys(self.order + list(range(1, n + 1))))
        decisions: list[tuple[int, int, bool]] = []    # (trail length, literal, flipped)
        qhead = root
        while True:
            if propagate(qhead):
                qhead = len(trail)
                var = next((v for v in order if val[v] is None), None)
                if var is None:
                    return {v: bool(val[v]) for v in range(1, n + 1)}
                decisions.append((len(trail), -var, False))
                enqueue(-var)
                continue
            while decisions and decisions[-1][2]:
                start, _, _ = decisions.pop()
                for lit in trail[start:]:
                    val[abs(lit)] = None
                del trail[start:]
            if not decisions:
                return None
            start, lit, _ = decisions.pop()
            for l in trail[start:]:
                val[abs(l)] = None
            del trail[start:]
            decisions.append((start, -lit, True))
            enqueue(-lit)
            qhead = start
sat_based_design_debugging.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sat-based-design-debugging/. The authors are listed in prov/1D5R8Y.jsonl.
"""SAT-based design debugging with correction multiplexers.

A circuit is a list of gates in topological order. Each gate is
(name, op, fanins), with op in AND, OR, XOR, NAND, NOR, XNOR, NOT, BUF, and the
fanins are names of inputs or of earlier gates. A test is (inputs, expected),
two dicts from names to 0 or 1.

debug() returns every set of at most k_max suspect gates, of the least size
that works, such that new values at those gates make every test give its
expected outputs.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional, Sequence

from dpll import Solver

Gate = tuple[str, str, tuple[str, ...]]
Test = tuple[dict[str, int], dict[str, int]]

OPS = {
    "AND": lambda xs: int(all(xs)),
    "OR": lambda xs: int(any(xs)),
    "XOR": lambda xs: sum(xs) & 1,
    "NAND": lambda xs: 1 - int(all(xs)),
    "NOR": lambda xs: 1 - int(any(xs)),
    "XNOR": lambda xs: 1 - (sum(xs) & 1),
    "NOT": lambda xs: 1 - xs[0],
    "BUF": lambda xs: xs[0],
}


@dataclass
class Circuit:
    inputs: list[str]
    gates: list[Gate]
    outputs: list[str]


def simulate(c: Circuit, inputs: dict[str, int], override: Optional[dict[str, int]] = None) -> dict[str, int]:
    """Values of all signals; override replaces the values of some gates."""
    v = dict(inputs)
    for name, op, fanins in c.gates:
        if override and name in override:
            v[name] = override[name]
        else:
            v[name] = OPS[op]([v[f] for f in fanins])
    return v


def gate_clauses(s: Solver, op: str, out: int, ins: list[int]) -> None:
    """Tseitin clauses of out = op(ins)."""
    if op in ("NOT", "BUF"):
        a = ins[0] if op == "BUF" else -ins[0]
        s.add_clause([-out, a])
        s.add_clause([out, -a])
        return
    if op in ("XOR", "XNOR"):
        acc = ins[0]
        for x in ins[1:]:
            t = s.new_var()
            for a, b, r in ((1, 1, -1), (1, -1, 1), (-1, 1, 1), (-1, -1, -1)):
                s.add_clause([-a * acc, -b * x, r * t])
            acc = t
        sign = 1 if op == "XOR" else -1
        s.add_clause([-out, sign * acc])
        s.add_clause([out, -sign * acc])
        return
    neg = op in ("NAND", "NOR")
    o = -out if neg else out
    if op in ("AND", "NAND"):
        for x in ins:
            s.add_clause([-o, x])
        s.add_clause([o] + [-x for x in ins])
    else:
        for x in ins:
            s.add_clause([o, -x])
        s.add_clause([-o] + list(ins))


def at_most(s: Solver, xs: list[int], k: int) -> None:
    """Sinz's sequential counter for sum(xs) <= k."""
    n = len(xs)
    if k >= n:
        return
    if k == 0:
        for x in xs:
            s.add_clause([-x])
        return
    r = [[s.new_var() for _ in range(k)] for _ in range(n - 1)]
    s.add_clause([-xs[0], r[0][0]])
    for j in range(1, k):
        s.add_clause([-r[0][j]])
    for i in range(1, n - 1):
        s.add_clause([-xs[i], r[i][0]])
        s.add_clause([-r[i - 1][0], r[i][0]])
        for j in range(1, k):
            s.add_clause([-xs[i], -r[i - 1][j - 1], r[i][j]])
            s.add_clause([-r[i - 1][j], r[i][j]])
        s.add_clause([-xs[i], -r[i - 1][k - 1]])
    s.add_clause([-xs[n - 1], -r[n - 2][k - 1]])


def debug_instance(c: Circuit, tests: Sequence[Test], suspects: Sequence[str]):
    """The CNF of lines L1 to L3. Returns the solver, the select variables, and
    for each test the map from signal names to variables."""
    s = Solver()
    select = {g: s.new_var() for g in suspects}
    s.order = list(select.values())
    copies = []
    for inputs, expected in tests:                                      # @line L1
        var = {x: s.new_var() for x in c.inputs}
        for x in c.inputs:
            s.add_clause([var[x] if inputs[x] else -var[x]])
        for name, op, fanins in c.gates:
            out = s.new_var()
            if name in select:                                          # @line L2
                orig, w, sel = s.new_var(), s.new_var(), select[name]
                gate_clauses(s, op, orig, [var[f] for f in fanins])
                s.add_clause([-sel, -w, out])
                s.add_clause([-sel, w, -out])
                s.add_clause([sel, -orig, out])
                s.add_clause([sel, orig, -out])
            else:
                gate_clauses(s, op, out, [var[f] for f in fanins])     # @line L3
            var[name] = out
        for y in c.outputs:
            s.add_clause([var[y] if expected[y] else -var[y]])
        copies.append(var)
    return s, select, copies


def debug(c: Circuit, tests: Sequence[Test], k_max: int,
          suspects: Optional[Sequence[str]] = None) -> tuple[int, list[frozenset[str]]]:
    """(k, all correction sets of size k) for the least k <= k_max that has one,
    or (-1, []) if there is none."""
    suspects = list(suspects) if suspects is not None else [g[0] for g in c.gates]
    base, select, _ = debug_instance(c, tests, suspects)
    for k in range(k_max + 1):                                          # @line L4
        s = Solver()
        s.nvars, s.clauses, s.units, s.order = base.nvars, [list(x) for x in base.clauses], list(base.units), base.order
        at_most(s, list(select.values()), k)                            # @line L5
        found = []
        while (model := s.solve()) is not None:                         # @line L6
            sol = frozenset(g for g, v in select.items() if model[v])   # @line L7
            found.append(sol)
            s.add_clause([-select[g] for g in sol])                     # @line L8
        if found:                                                       # @line L9
            return k, found
    return -1, []                                                       # @line L10


def correction_values(c: Circuit, tests: Sequence[Test], fix: frozenset[str]) -> Optional[list[dict[str, int]]]:
    """Values at the gates of fix, one dict per test, that make all tests pass."""
    s, select, copies = debug_instance(c, tests, sorted(fix))
    model = s.solve([select[g] for g in fix])
    if model is None:
        return None
    return [{g: int(model[var[g]]) for g in fix} for var in copies]
test_sat_based_design_debugging.py 176 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sat-based-design-debugging/. The authors are listed in prov/1D5R8Y.jsonl.

import random
from itertools import combinations, product

from dpll import Solver
from sat_based_design_debugging import OPS, Circuit, at_most, correction_values, debug, simulate

BINARY = ("AND", "OR", "XOR", "NAND", "NOR", "XNOR")


# ------------------------------------------------------------------ references

def passes(c, tests, override_per_test=None):
    for j, (inputs, expected) in enumerate(tests):
        v = simulate(c, inputs, override_per_test[j] if override_per_test else None)
        if any(v[y] != expected[y] for y in c.outputs):
            return False
    return True


def brute_force_fixes(c, tests, size):
    """All gate sets of the given size where some values per test fix every test."""
    names = [g[0] for g in c.gates]
    out = []
    for fix in combinations(names, size):
        for bits in product((0, 1), repeat=size * len(tests)):
            over = [dict(zip(fix, bits[j * size:(j + 1) * size])) for j in range(len(tests))]
            if passes(c, tests, over):
                out.append(frozenset(fix))
                break
    return out


def random_circuit(rng, n_in, n_gates, n_out):
    inputs = [f"i{j}" for j in range(n_in)]
    gates = []
    for j in range(n_gates):
        pool = inputs + [g[0] for g in gates]
        if rng.random() < 0.15:
            gates.append((f"g{j}", "NOT", (rng.choice(pool),)))
        else:
            a, b = rng.sample(pool, 2)
            gates.append((f"g{j}", rng.choice(BINARY), (a, b)))
    return Circuit(inputs, gates, [g[0] for g in gates[-n_out:]])


def all_vectors(c):
    return [dict(zip(c.inputs, bits)) for bits in product((0, 1), repeat=len(c.inputs))]


def make_tests(golden, vectors):
    return [(v, {y: simulate(golden, v)[y] for y in golden.outputs}) for v in vectors]


def mutate(rng, c, count):
    """A copy of c with the type of count random two-input gates changed."""
    gates = list(c.gates)
    sites = rng.sample([j for j, g in enumerate(gates) if g[1] != "NOT"], count)
    for j in sites:
        name, op, fanins = gates[j]
        gates[j] = (name, rng.choice([o for o in BINARY if o != op]), fanins)
    return Circuit(c.inputs, gates, c.outputs), {gates[j][0] for j in sites}


# ----------------------------------------------------------------------- tests

EXAMPLE_GOLDEN = Circuit(["a", "b", "c"],
                         [("g1", "OR", ("a", "b")), ("g2", "AND", ("b", "c")),
                          ("g3", "XOR", ("g1", "c")), ("g4", "OR", ("g1", "g2"))],
                         ["g3", "g4"])
EXAMPLE_BUGGY = Circuit(["a", "b", "c"],
                        [("g1", "AND", ("a", "b")), ("g2", "AND", ("b", "c")),
                         ("g3", "XOR", ("g1", "c")), ("g4", "OR", ("g1", "g2"))],
                        ["g3", "g4"])


def test_example_of_the_page():
    failing = [v for v in all_vectors(EXAMPLE_BUGGY)
               if any(simulate(EXAMPLE_BUGGY, v)[y] != simulate(EXAMPLE_GOLDEN, v)[y] for y in ("g3", "g4"))]
    assert [(v["a"], v["b"], v["c"]) for v in failing] == [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1)]
    tests = make_tests(EXAMPLE_GOLDEN, failing[:2])
    k, fixes = debug(EXAMPLE_BUGGY, tests, 2)
    assert k == 1 and set(fixes) == {frozenset({"g1"})}
    assert correction_values(EXAMPLE_BUGGY, tests, frozenset({"g1"})) == [{"g1": 1}, {"g1": 1}]
    # With one test only, the two outputs can also be fixed at g3 and g4 together, but not by one other gate.
    k, fixes = debug(EXAMPLE_BUGGY, tests[:1], 2)
    assert k == 1 and set(fixes) == {frozenset({"g1"})}


def test_tseitin_gates_and_counter():
    for op in OPS:
        arity = 1 if op in ("NOT", "BUF") else 3
        for bits in product((0, 1), repeat=arity):
            s = Solver()
            ins = [s.new_var() for _ in bits]
            out = s.new_var()
            from sat_based_design_debugging import gate_clauses
            gate_clauses(s, op, out, ins)
            want = OPS[op](list(bits))
            units = [x if b else -x for x, b in zip(ins, bits)]
            assert s.solve(units + [out if want else -out]) is not None
            assert s.solve(units + [-out if want else out]) is None
    for n, k in product(range(1, 6), range(0, 6)):
        for bits in product((0, 1), repeat=n):
            s = Solver()
            xs = [s.new_var() for _ in range(n)]
            at_most(s, xs, k)
            ok = s.solve([x if b else -x for x, b in zip(xs, bits)]) is not None
            assert ok == (sum(bits) <= k)


def test_single_gate_debug_matches_brute_force():
    rng = random.Random(1606)
    checked = 0
    while checked < 120:
        golden = random_circuit(rng, 4, 10, 3)
        buggy, sites = mutate(rng, golden, 1)
        failing = [v for v in all_vectors(golden) if simulate(golden, v) != simulate(buggy, v)
                   and any(simulate(golden, v)[y] != simulate(buggy, v)[y] for y in golden.outputs)]
        if not failing:
            continue
        rng.shuffle(failing)
        tests = make_tests(golden, failing[:3])
        k, fixes = debug(buggy, tests, 1)
        assert k == 1
        assert set(fixes) == set(brute_force_fixes(buggy, tests, 1))
        assert sites <= set().union(*fixes)          # the real error site is found
        for fix in fixes:                            # each reported set really fixes the tests
            over = correction_values(buggy, tests, fix)
            assert passes(buggy, tests, over)
        checked += 1


def test_two_errors_against_brute_force():
    rng = random.Random(2005)
    checked = 0
    while checked < 40:
        golden = random_circuit(rng, 3, 8, 2)
        buggy, sites = mutate(rng, golden, 2)
        failing = [v for v in all_vectors(golden)
                   if any(simulate(golden, v)[y] != simulate(buggy, v)[y] for y in golden.outputs)]
        if not failing:
            continue
        tests = make_tests(golden, failing[:3])
        k, fixes = debug(buggy, tests, 2)
        assert k in (1, 2)
        assert brute_force_fixes(buggy, tests, k - 1) == []
        assert set(fixes) == set(brute_force_fixes(buggy, tests, k))
        if k == 2:
            assert all(len(f) == 2 for f in fixes)
        checked += 1


def test_passing_circuit_needs_no_fix_and_impossible_tests_have_none():
    rng = random.Random(3)
    golden = random_circuit(rng, 4, 10, 2)
    tests = make_tests(golden, all_vectors(golden))
    assert debug(golden, tests, 2) == (0, [frozenset()])
    # Two tests with the same inputs and different expected outputs: no circuit
    # can pass both, but the instance gives each test its own correction values,
    # so it is satisfiable. The theorem needs distinct input vectors.
    v, e = tests[0]
    flipped = {y: 1 - b for y, b in e.items()}
    k, fixes = debug(golden, [(v, e), (v, flipped)], 3)
    assert k >= 1 and set(fixes) == set(brute_force_fixes(golden, [(v, e), (v, flipped)], k))
    # With a bound below the number of outputs that must change, there is no answer.
    assert debug(golden, [(v, e), (v, flipped)], k - 1) == (-1, [])


def test_suspect_list_restricts_the_answer():
    tests = make_tests(EXAMPLE_GOLDEN, [{"a": 0, "b": 1, "c": 0}, {"a": 1, "b": 0, "c": 1}])
    k, fixes = debug(EXAMPLE_BUGGY, tests, 2, suspects=["g2", "g3", "g4"])
    assert k == 2 and frozenset({"g3", "g4"}) in fixes
    assert set(fixes) == set(f for f in brute_force_fixes(EXAMPLE_BUGGY, tests, 2) if "g1" not in f)

History

Smith, Veneris, Ali and Viglas presented the SAT formulation of logic debugging and fault diagnosis with correction multiplexers and published the journal version in 2005. Ali and coauthors extended it to sequential circuits at ICCAD 2004. Safarpour, Chen, Marques-Silva and Veneris then recast it as maximum satisfiability, with the journal paper in 2010. Later work added abstraction and refinement, hierarchical debugging, and unsatisfiable cores to handle large designs.

References

  1. A. Smith, A. Veneris, M. F. Ali and A. Viglas, Fault diagnosis and logic debugging using Boolean satisfiability, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 24(10), 1606 to 1621, 2005, the copies of the circuit per test vector, the multiplexer with a select line and a free value at each suspect, the bound on the number of active selects, and the enumeration of all solutions with blocking clauses
  2. M. F. Ali, A. Veneris, A. Smith, S. Safarpour, R. Drechsler and M. Abadir, Debugging sequential circuits using Boolean satisfiability, IEEE/ACM International Conference on Computer-Aided Design (ICCAD 2004), 204 to 209, 2004, the extension to sequential circuits by unrolling the circuit over the clock cycles of each failing trace, with one select per suspect shared by all cycles
  3. Y. Chen, S. Safarpour, J. Marques-Silva and A. Veneris, Automated design debugging with maximum satisfiability, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 29(11), 1804 to 1817, 2010, debugging as maximum satisfiability, in which the correction sets are the minimal correction subsets of soft constraints on the suspects

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example