Module contents
Lesson 12 of 23Advanced 120 min

CDCL: how modern SAT solvers work

Build a complete conflict-driven clause-learning SAT solver, analyze and measure its heuristics, and certify UNSAT with proof traces.

After this lesson you can

  • Build the implication graph and derive the 1-UIP clause as a resolution chain.
  • Implement nonchronological backjumping on the trail while preserving reasons and watch lists.
  • Implement VSIDS, Luby restarts and LBD-based clause deletion, and measure their contributions.
  • Emit and verify unsatisfiability proofs using reverse unit propagation.
  • Explain CDCL's limits as a proof system equivalent to resolution.

Before you start

From DPLL to CDCL: learning from every conflict

The previous lesson ended with an uncomfortable number. On an assignment problem with 24 tasks, your DPLL engine (trail, decision levels, two watched literals) needed over a thousand decisions and seconds; CaDiCaL needed a few hundred conflicts and hundredths of a second. Language explains part of the gap. The other part is that DPLL learns nothing from failure.

Consider DPLL when propagation finds a conflict at level 30: it undoes level 30’s decision and tries the other branch. If decisions at levels 2 and 5 actually caused the conflict and intermediate decisions are irrelevant, the same conflict returns in both branches of each of 25 intermediate decisions: up to 2252^{25} times. This is the thrashing seen in CSP, and the cure starts with the same conflict-directed backjumping, plus an idea that changes everything: write the cause as a new clause and add it to the formula. The clause logically follows from the formula, so its models are unchanged, but unit propagation now prevents repeating the mistake in any branch.

This is conflict-driven clause learning (CDCL). Its history fits in four systems:

  • GRASP (Marques-Silva and Sakallah, 1999) introduced implication-graph conflict analysis, learned clauses and nonchronological backjumping.
  • Chaff (Moskewicz et al., 2001) added watched literals and VSIDS. Its authors measured roughly 80% of time in propagation, 10% in decisions and 10% in conflict analysis on difficult problems, with one to two orders of magnitude improvement over GRASP and SATO.
  • MiniSat (Eén and Sörensson, 2004) condensed the ideas into short readable code underlying almost every later solver.
  • Glucose (Audemard and Simon, 2009) proposed measuring a learned clause’s quality by the decision levels it touches (LBD), and freely deleting others. Against 2007 competition winners it solved 176 of 234 industrial instances, versus about 140 for MiniSat and RSAT and 153 for PicoSAT.

The complete loop is short. Propagate to a fixed point. A level-0 conflict means the formula is unsatisfiable. At a higher level, analyze the conflict, learn a clause, jump to the level indicated and let the learned clause propagate. Without conflict, decide (or restart, or clean the clause database) and repeat. This lesson builds and measures each piece.

The implication graph

The previous lesson’s trail stores each assigned literal’s decision level and reason: the clause forcing it. This suffices to reconstruct why each literal is true.

It is a directed acyclic graph and the trail itself is a topological order: when RR propagated ℓ\ell, the aia_i were already assigned, so each edge goes from an earlier position to a later one. Trail order respecting implications lets us analyze conflicts backward along the trail without constructing the graph.

Two different numbers describe each node. Its trail position says when it was assigned; its level says how many decisions had been made. All literals of one level occupy a contiguous trail segment, but the current level may contain dozens of literals, and conflict analysis cares about their levels, not positions.

A small example, used throughout: the formula has eleven clauses over 14 variables and search decides x1x_1, x3x_3, x5x_5 and x7x_7, in that order, at levels 1 through 4:

C1=¬x1∨x2,C2=¬x3∨x4,C3=¬x5∨x6,C4=¬x7∨x8,C5=¬x8∨¬x2∨x9,C6=¬x8∨¬x4∨x10,C7=¬x8∨x14,C8=¬x9∨¬x10∨x11,C9=¬x11∨¬x5∨¬x6∨x12,C10=¬x11∨x13,C11=¬x12∨¬x13∨¬x4.\begin{aligned} &C_1 = \lnot x_1 \lor x_2, \quad C_2 = \lnot x_3 \lor x_4, \quad C_3 = \lnot x_5 \lor x_6, \quad C_4 = \lnot x_7 \lor x_8, \\ &C_5 = \lnot x_8 \lor \lnot x_2 \lor x_9, \quad C_6 = \lnot x_8 \lor \lnot x_4 \lor x_{10}, \quad C_7 = \lnot x_8 \lor x_{14}, \quad C_8 = \lnot x_9 \lor \lnot x_{10} \lor x_{11}, \\ &C_9 = \lnot x_{11} \lor \lnot x_5 \lor \lnot x_6 \lor x_{12}, \quad C_{10} = \lnot x_{11} \lor x_{13}, \quad C_{11} = \lnot x_{12} \lor \lnot x_{13} \lor \lnot x_4. \end{aligned}

The first cell propagates all four decisions using textbook unit propagation, recording each literal’s level and reason. Read the output as a graph table.

[ ]The example implication graph from scratchBrowser
import itertools, random, time

# El ejemplo: once cláusulas y cuatro decisiones. Todas las variables acaban verdaderas.
F_EJ = [[-1, 2], [-3, 4], [-5, 6], [-7, 8], [-8, -2, 9], [-8, -4, 10], [-8, 14],
        [-9, -10, 11], [-11, -5, -6, 12], [-11, 13], [-12, -13, -4]]
DECISIONES = [1, 3, 5, 7]

def propaga_con_registro(F, decisiones):
    """Propagación unitaria de libro con cola. Devuelve el trail [(literal, nivel, razón)] y la cláusula en conflicto.
    razón es el índice de la cláusula que forzó el literal (None en las decisiones)."""
    val, trail = {}, []
    valor = lambda l: 0 if abs(l) not in val else (val[abs(l)] if l > 0 else -val[abs(l)])
    def asigna(l, nivel, razon):
        val[abs(l)] = 1 if l > 0 else -1
        trail.append((l, nivel, razon))
    qhead = 0
    for d, nivel in zip(decisiones, itertools.count(1)):
        asigna(d, nivel, None)
        while qhead < len(trail):
            p = -trail[qhead][0]                     # p acaba de hacerse falso
            qhead += 1
            for ci, c in enumerate(F):
                if p not in c or any(valor(l) == 1 for l in c):
                    continue
                libres = [l for l in c if valor(l) == 0]
                if not libres:
                    return trail, ci
                if len(libres) == 1:
                    asigna(libres[0], nivel, ci)
    return trail, None

trail, conf = propaga_con_registro(F_EJ, DECISIONES)
nivel = {abs(l): d for l, d, _ in trail}
razon = {abs(l): r for l, _, r in trail}
pos = {abs(l): i for i, (l, _, _) in enumerate(trail)}
for i, (l, d, r) in enumerate(trail):
    print(f"pos {i:2d}  x{abs(l):<3d} nivel {d}  " + ("decisión" if r is None else f"razón C{r + 1} = {F_EJ[r]}"))
print(f"conflicto: C{conf + 1} = {F_EJ[conf]}")

# aristas del grafo de implicaciones: u -> w si ¬u está en la razón de w; κ (el 0) recibe la cláusula de conflicto
aristas = [(abs(q), abs(l)) for l, _, r in trail if r is not None for q in F_EJ[r] if abs(q) != abs(l)]
aristas += [(abs(q), 0) for q in F_EJ[conf]]

def resolvente(c1, c2, v):
    """Resolución sobre la variable v: c1 contiene un literal de v y c2 el contrario."""
    return sorted({l for l in c1 + c2 if abs(l) != v}, key=lambda l: -pos[abs(l)])

def cadena_1uip(conf):
    """La cláusula 1-UIP como cadena de resoluciones: se resuelve con la razón del literal del nivel actual más
    reciente en el trail hasta que solo queda uno de ese nivel."""
    dl = max(nivel.values())
    c = sorted(F_EJ[conf], key=lambda l: -pos[abs(l)])
    pasos = [c]
    while sum(nivel[abs(l)] == dl for l in c) > 1:
        v = max((abs(l) for l in c if nivel[abs(l)] == dl), key=lambda v: pos[v])
        c = resolvente(c, F_EJ[razon[v]], v)
        pasos.append(c)
    return pasos

for paso, c in enumerate(cadena_1uip(conf)):
    niveles = [nivel[abs(l)] for l in c]
    print(f"paso {paso}: {c}  niveles {niveles}  del nivel 4: {niveles.count(4)}")

At the first three levels, each decision causes one implication (x2x_2, x4x_4, x6x_6). At the fourth, x7x_7 triggers a cascade of seven literals and C11C_{11} ends with all literals false: x12x_{12} and x13x_{13} were assigned at level 4, and x4x_4 came from level 2. The last three steps are already conflict analysis, explained next.

Conflict analysis: cuts, UIPs and the 1-UIP clause

Which combination of assignments caused the conflict? Many answers are correct, one for each way to partition the graph.

Proof

Let σ\sigma satisfy FF and suppose it makes every frontier literal true. Traverse BB nodes in trail order. Each ℓ∈B\ell \in B other than κ\kappa is not a decision, so has reason R=(ℓ∨¬a1∨⋯∨¬ak)R = (\ell \lor \lnot a_1 \lor \dots \lor \lnot a_k), and each aia_i lies on the frontier (if ai∈Aa_i \in A) or is an BB node preceding ℓ\ell (if ai∈Ba_i \in B); either way σ(ai)=1\sigma(a_i) = 1, and since σ\sigma satisfies RR, also σ(ℓ)=1\sigma(\ell) = 1. At κ\kappa, all bjb_j are true and σ\sigma falsifies C⋆∈FC^\star \in F. Contradiction: σ\sigma falsifies some frontier literal, satisfying CA,BC_{A,B}.

∎

Not all clauses are equally useful. The learned one must escape the conflict; the key is how many current-level literals it contains. Try it: the interactive draws the example graph with one row per level and one column per trail position.

InteractiveCut the implication graph
level 1level 2level 3level 4position in trail →012345678910111213cutx₁x₂x₃x₄x₅x₆x₇x₈x₉x₁₀x₁₄x₁₁x₁₂x₁₃κ
  • conflict side
  • clause literals and edges crossing the cut
  • decision (double outline)
  • does not lead to conflict
Learned clause(¬x₁₃ ∨ ¬x₁₂ ∨ ¬x₄)
Literals · at level 43 · 2
LBD (distinct levels)2
Backjump levelnot asserting
Resolutions from the conflict clause0
Not asserting: it has 2 level-4 literals and would force nothing after backtracking.
The example graph: rows by level, columns by trail position; each level's decision has a double border and x14x_{14} is dim because it does not lead to conflict. The cut starts against κ\kappa: its clause is C11C_{11} itself, with two level-4 literals, and is not asserting. Drag the cut left (or press ‘One more node’) and watch for a single level-4 literal. Press ‘All decisions’ and compare length and LBD. Click nodes to make nonvertical cuts and try moving a decision to the conflict side.

Moving the cut shows three things. Each step left replaces one level-4 literal by its reason’s literals, exactly one resolution step. Few cut positions give a clause with one level-4 literal: after x11x_{11}, x8x_8 and x7x_7. The first, closest to conflict, gives the shortest clause.

In the example UIPs are x11x_{11}, x8x_8 and x7x_7: every path from x7x_7 to κ\kappa passes x8x_8 and also x11x_{11}, because x9x_9 and x10x_{10} only lead to x11x_{11}. The first UIP is x11x_{11}. 1-UIP conflict analysis learns the cut clause placing everything after the first UIP on the conflict side:

C1UIP=¬x11∨¬x6∨¬x5∨¬x4.C_{\text{1UIP}} = \lnot x_{11} \lor \lnot x_6 \lor \lnot x_5 \lor \lnot x_4 .

The cell obtained it without constructing the graph, using three resolution steps on the trail, as a real solver does.

Proof

Each resolution is valid. If vv is true on the trail, CiC_i contains ¬v\lnot v and RvR_v contains vv; all other literals of both clauses are false under the current assignment, so no other complementary pair exists and the resolvent is not tautological. By resolution soundness each CiC_i follows from FF.

It terminates with one level-dd literal. In a solver propagating to a fixed point before every decision, a literal propagated at level dd has another level-dd literal in its reason: if all others belonged to earlier levels, the reason would have become unit earlier and the literal propagated at a lower level. Thus each step removes one level-dd literal and adds at least one, always earlier in position; the number of level-dd literals never falls below 1. Since the resolved literal’s position decreases, the process terminates, when exactly one remains. The same property says following level-dd reasons backward always reaches that level’s decision, so every level-dd node descends from it.

It is the first-UIP clause. After resolving variables v1,…,viv_1, \dots, v_i, CiC_i is the cut clause whose conflict side is {κ,v1,…,vi}\{\kappa, v_1, \dots, v_i\}, by induction: resolving vv moves it from frontier to conflict side and adds its predecessors to the frontier. Let uu be the sole level-dd literal remaining. A path from the decision to κ\kappa visits only level-dd nodes (all assigned after the decision) and crosses the cut by an edge from the frontier; the only level-dd frontier node is uu, so uu is a UIP. Suppose another UIP ww occurred later than uu in the trail, and consider the clause when the chain has resolved all level-dd literals after ww. A literal x≠wx \ne w of level dd in it would precede ww and have an edge to a node after ww (or to κ\kappa); since xx descends from the decision, a decision-to-κ\kappa path would avoid ww, contradicting ww being a UIP. Thus only one level-dd literal remained, ww, and the chain would have stopped at ww rather than uu. Therefore uu is the first UIP.

∎

In practice solvers do not resolve clause by clause. MiniSat marks seen variables and counts unresolved current-level literals; it scans the trail backward, skipping unmarked entries, and finds the UIP when the count reaches 1. Lower-level literals go straight into the learned clause. Cost is linear in the size of visited reasons.

Why the first rather than another? Two measured reasons. Zhang, Madigan, Moskewicz and Malik (2001) formulated learning schemes as different graph cuts and compared them; Chaff, MiniSat and successors adopted first UIP. And, as Audemard and Simon (2009) report citing Jabbour and Sais (2008), among asserting UIP clauses, first UIP has the smallest LBD, a quality measure discussed shortly. The interactive shows this: 1-UIP has 4 literals and LBD 3; second UIP, 5 literals and LBD 4; decisions, 4 literals and LBD 4.

Nonchronological backjumping and asserting clauses

A learned clause with exactly one literal at the conflict level is asserting. Its usefulness appears during backtracking.

Proof

Undoing to bb unassigns exactly variables above level bb. aia_i have level ≤b\le b and remain true, so ¬ai\lnot a_i remain false; uu has level d>bd > b and becomes free. Undoing to level b′<bb' < b would also free literal aja_j at level bb, leaving CC with two free literals.

∎

In the example the backjump level is 3: undo all level 4, add C1UIPC_{\text{1UIP}}, and propagation sets x11x_{11} false at level 3. This jump is one level, but if clause literals were at levels 4 and 1, two complete levels and their decisions would be skipped without exploring opposite branches: Prosser’s (1993) CSP conflict-directed backjumping, now with a clause remembering the reason. Undone decisions are not completely lost: if still good, they return through phase saving discussed below.

Computing bb correctly is essential. Jump below bb and CC has two free literals, forcing nothing; compute bb using trail position instead of level and the jump goes somewhere arbitrary.

Proof

Associate each state with sequence (n0,n1,…,nd)(n_0, n_1, \dots, n_d) of literal counts per level and order these lexicographically (an extension is greater). Propagation increases ndn_d; deciding adds a level; a conflict leaves levels 0,…,b−10, \dots, b - 1 intact and increases nbn_b by one (the asserted literal forced by the new clause), so state strictly increases in all three cases. At most nn literals are assigned, so only finitely many NN sequences exist and at most NN steps fit between restarts. Without restarts this proves termination. With unboundedly growing restart intervals, eventually an interval allows more than NN conflicts and must end in a model or level-0 conflict before running out. This is the abstract DPLL argument of Nieuwenhuis, Oliveras and Tinelli (J. ACM, 2006).

∎

Integration with the previous lesson’s engine

The previous engine already stores everything analysis needs: each variable’s level and reason, and the trail in assignment order. CDCL integration needs three details.

  1. Reason with forced literal at position 0. During propagation, the engine leaves the forced literal at c[0] and the false literal triggering the visit at c[1]. While the clause is a reason, neither watch moves (literal 0 is true), so analysis can scan c[1:] knowing these are causes.
  2. What to watch in the learned clause. Position 0 is the negated UIP, the only free literal after the jump. Position 1 must contain a literal at backjump level bb, the highest among the rest. This is the watched-literal invariant: if one watch is false, the other is true at no higher level. Watching a level-b′<bb' < b literal would break the invariant upon undoing to a level between b′b' and bb: the clause might later become unit without being visited.
  3. Locked clauses. A learned clause that is the reason for a trail literal is locked: do not delete it while that literal remains assigned, since later conflict analysis may need it. Database deletion must check this.

The complete solver fits in one cell: VSIDS heap, Luby sequence, 1-UIP analysis with minimization, backjumping, restarts and LBD deletion, explained below, plus a reference DPLL (previous lesson: chronological backtracking, no learning, fixed variable order). Validation matches DPLL verdicts on small random formulas in two configurations: normal and frequent restarts and database cleanups to exercise rare cases.

Lab 1: a complete CDCL in Python

[ ]A complete CDCL: heap VSIDS, minimized 1-UIP, backjump, Luby and LBDBrowser
class Heap:
    """Montículo binario de máximos indexado por variable (cola de prioridad indexada de m08).
    pos[v] es la posición de v en el montículo, o −1 si no está."""

    def __init__(self, n, key):
        self.key = key                        # lista de actividades, compartida con el resolvedor
        self.h = []
        self.pos = [-1] * (n + 1)

    def _up(self, i):
        h, pos, key = self.h, self.pos, self.key
        v = h[i]
        while i > 0:
            p = (i - 1) >> 1
            if key[h[p]] >= key[v]:
                break
            h[i] = h[p]; pos[h[i]] = i; i = p
        h[i] = v; pos[v] = i

    def _down(self, i):
        h, pos, key = self.h, self.pos, self.key
        v, n = h[i], len(h)
        while True:
            c = 2 * i + 1
            if c >= n:
                break
            if c + 1 < n and key[h[c + 1]] > key[h[c]]:
                c += 1
            if key[h[c]] <= key[v]:
                break
            h[i] = h[c]; pos[h[i]] = i; i = c
        h[i] = v; pos[v] = i

    def push(self, v):
        if self.pos[v] < 0:
            self.h.append(v)
            self._up(len(self.h) - 1)

    def increased(self, v):
        if self.pos[v] >= 0:
            self._up(self.pos[v])

    def pop(self):
        h = self.h
        v = h[0]
        last = h.pop()
        self.pos[v] = -1
        if h:
            h[0] = last
            self.pos[last] = 0
            self._down(0)
        return v


def luby(i):
    """Término i (desde 1) de la sucesión de Luby: 1, 1, 2, 1, 1, 2, 4, ..."""
    k = 1
    while (1 << k) - 1 < i:
        k += 1
    while True:
        if i == (1 << k) - 1:
            return 1 << (k - 1)
        if i >= (1 << (k - 1)):
            i -= (1 << (k - 1)) - 1
            k -= 1
        else:
            k -= 1


class CDCL:
    def __init__(self, n, clauses, vsids=True, restarts="luby", deletion="lbd", minimize=True,
                 luby_unit=100, first_reduce=2000, inc_reduce=300, proof=False, track=False):
        self.n = n
        self.vsids, self.restarts, self.deletion, self.minimize = vsids, restarts, deletion, minimize
        self.luby_unit, self.first_reduce, self.inc_reduce = luby_unit, first_reduce, inc_reduce
        self.clauses, self.learnt, self.lbd, self.cact = [], [], [], []
        self.watches = {}
        self.val = [0] * (n + 1)
        self.level = [0] * (n + 1)
        self.reason = [-1] * (n + 1)
        self.trail, self.lim, self.qhead = [], [], 0
        self.act = [0.0] * (n + 1)
        self.var_inc, self.var_decay = 1.0, 0.95
        self.cla_inc, self.cla_decay = 1.0, 0.999
        self.phase = [-1] * (n + 1)
        self.seen = [0] * (n + 1)
        self.heap = Heap(n, self.act)
        for v in range(1, n + 1):
            self.heap.push(v)
        self.conflicts = self.decisions = self.props = self.visits = 0
        self.restarts_done = self.reductions = self.deleted = 0
        self.lits_before = self.lits_after = self.lbd_baja = 0
        self.proof = [] if proof else None
        self.track = track
        self.uses = []                           # veces que cada cláusula interviene en un análisis
        self.born = []                           # conflicto en que se aprendió (−1 si es original)
        self.live = self.db_sum = 0             # cláusulas aprendidas vivas y su suma en cada conflicto
        self.ok = True
        for c in clauses:
            c = list(dict.fromkeys(c))
            if any(-l in c for l in c):
                continue                         # tautología
            self.add_clause(c, learnt=False)

    # --- estado básico ---------------------------------------------------------------------------
    def value(self, l):
        v = self.val[l if l > 0 else -l]
        return v if l > 0 else -v

    def assign(self, l, reason):
        v = l if l > 0 else -l
        self.val[v] = 1 if l > 0 else -1
        self.level[v] = len(self.lim)
        self.reason[v] = reason
        self.trail.append(l)

    def add_clause(self, c, learnt, lbd=0):
        ci = len(self.clauses)
        self.clauses.append(c)
        self.learnt.append(learnt)
        self.lbd.append(lbd)
        self.cact.append(0.0)
        self.uses.append(0)
        self.born.append(self.conflicts if learnt else -1)
        if len(c) == 0:
            self.ok = False
        elif len(c) == 1:
            if not learnt:
                if self.value(c[0]) == -1:
                    self.ok = False
                elif self.value(c[0]) == 0:
                    self.assign(c[0], ci)
        else:
            self.watches.setdefault(c[0], []).append(ci)
            self.watches.setdefault(c[1], []).append(ci)
        return ci

    # --- propagación con dos literales vigilados (la de la lección anterior) ---------------------
    def propagate(self):
        clauses, watches, value = self.clauses, self.watches, self.value
        while self.qhead < len(self.trail):
            p = -self.trail[self.qhead]
            self.qhead += 1
            lista = watches.get(p, [])
            nueva = []
            i, m = 0, len(lista)
            while i < m:
                ci = lista[i]
                i += 1
                c = clauses[ci]
                if c is None:                      # borrada: se cae de la lista
                    continue
                self.visits += 1
                if c[0] == p:
                    c[0], c[1] = c[1], c[0]
                if value(c[0]) == 1:
                    nueva.append(ci)
                    continue
                for k in range(2, len(c)):
                    if value(c[k]) != -1:
                        c[1], c[k] = c[k], c[1]
                        watches.setdefault(c[1], []).append(ci)
                        break
                else:
                    nueva.append(ci)
                    if value(c[0]) == -1:
                        nueva.extend(lista[i:])
                        watches[p] = nueva
                        return ci
                    self.assign(c[0], ci)
                    self.props += 1
            watches[p] = nueva
        return None

    def backtrack(self, lvl):
        if len(self.lim) <= lvl:
            return
        start = self.lim[lvl]
        for l in self.trail[start:]:
            v = l if l > 0 else -l
            self.phase[v] = self.val[v]            # guardado de fase
            self.val[v] = 0
            self.reason[v] = -1
            self.heap.push(v)
        del self.trail[start:]
        del self.lim[lvl:]
        self.qhead = len(self.trail)

    # --- VSIDS -----------------------------------------------------------------------------------
    def bump(self, v):
        self.act[v] += self.var_inc
        if self.act[v] > 1e100:                    # reescala para no desbordar
            for u in range(1, self.n + 1):
                self.act[u] *= 1e-100
            self.var_inc *= 1e-100
        self.heap.increased(v)

    def bump_clause(self, ci):
        self.cact[ci] += self.cla_inc
        if self.cact[ci] > 1e20:
            for j in range(len(self.cact)):
                self.cact[j] *= 1e-20
            self.cla_inc *= 1e-20

    # --- análisis de conflictos 1-UIP --------------------------------------------------------------
    def analyze(self, confl):
        seen, level, trail = self.seen, self.level, self.trail
        dl = len(self.lim)
        learnt = [0]
        counter, p, idx = 0, 0, len(trail) - 1
        while True:
            c = self.clauses[confl]
            self.uses[confl] += 1
            if self.learnt[confl]:
                self.bump_clause(confl)
            for q in (c if p == 0 else c[1:]):     # en una razón, c[0] es el literal que forzó
                v = q if q > 0 else -q
                if not seen[v] and level[v] > 0:
                    seen[v] = 1
                    if self.vsids:
                        self.bump(v)
                    if level[v] >= dl:
                        counter += 1
                    else:
                        learnt.append(q)
            while not seen[abs(trail[idx])]:
                idx -= 1
            p = trail[idx]
            idx -= 1
            seen[abs(p)] = 0
            counter -= 1
            if counter == 0:
                break
            confl = self.reason[abs(p)]
        learnt[0] = -p
        self.lits_before += len(learnt)
        lbd_antes = len({level[abs(q)] for q in learnt})
        if self.minimize:
            learnt = self.minimize_clause(learnt)
        else:
            for q in learnt[1:]:
                seen[abs(q)] = 0
        self.lits_after += len(learnt)
        # nivel de salto: el segundo nivel más alto; ese literal va a la posición 1 (se vigila)
        if len(learnt) == 1:
            bj = 0
        else:
            k = max(range(1, len(learnt)), key=lambda j: level[abs(learnt[j])])
            learnt[1], learnt[k] = learnt[k], learnt[1]
            bj = level[abs(learnt[1])]
        lbd = len({level[abs(q)] for q in learnt})
        self.lbd_baja += lbd < lbd_antes
        return learnt, bj, lbd

    def minimize_clause(self, learnt):
        """Minimización recursiva (MiniSat): quita q si su razón, recursivamente, solo lleva a literales de la cláusula
        o de nivel 0. abstract es un filtro barato de los niveles presentes."""
        seen, level, reason = self.seen, self.level, self.reason
        abstract = 0
        for q in learnt[1:]:
            abstract |= 1 << (level[abs(q)] & 31)
        toclear = list(learnt[1:])
        out = [learnt[0]]
        for q in learnt[1:]:
            v = abs(q)
            if reason[v] == -1 or not self._redundant(q, abstract, toclear):
                out.append(q)
        for q in toclear:
            seen[abs(q)] = 0
        return out

    def _redundant(self, p, abstract, toclear):
        seen, level, reason, clauses = self.seen, self.level, self.reason, self.clauses
        stack = [p]
        top = len(toclear)
        while stack:
            q = stack.pop()
            c = clauses[reason[abs(q)]]
            for r in c[1:]:
                v = abs(r)
                if not seen[v] and level[v] > 0:
                    if reason[v] != -1 and (abstract >> (level[v] & 31)) & 1:
                        seen[v] = 1
                        stack.append(r)
                        toclear.append(r)
                    else:
                        for x in toclear[top:]:
                            seen[abs(x)] = 0
                        del toclear[top:]
                        return False
        return True

    # --- borrado de cláusulas aprendidas --------------------------------------------------------
    def locked(self, ci):
        c = self.clauses[ci]
        v = abs(c[0])
        return self.reason[v] == ci and self.value(c[0]) == 1

    def reduce_db(self):
        cand = [ci for ci in range(len(self.clauses))
                if self.learnt[ci] and self.clauses[ci] is not None and len(self.clauses[ci]) > 2]
        if self.deletion == "lbd":       # Glucose: peores primero por LBD; las glue (LBD 2) no se tocan
            cand = [ci for ci in cand if self.lbd[ci] > 2]
            cand.sort(key=lambda ci: (-self.lbd[ci], self.cact[ci]))
        else:                            # MiniSat: por actividad
            cand.sort(key=lambda ci: self.cact[ci])
        quitar = len(cand) // 2
        for ci in cand[:quitar]:
            if self.locked(ci):
                continue
            if self.proof is not None:
                self.proof.append(("d", list(self.clauses[ci])))
            self.clauses[ci] = None
            self.deleted += 1
            self.live -= 1
        self.reductions += 1

    def learnt_count(self):
        return sum(1 for ci, c in enumerate(self.clauses) if c is not None and self.learnt[ci])

    # --- bucle principal ------------------------------------------------------------------------
    def pick(self):
        if self.vsids:
            while self.heap.h:
                v = self.heap.pop()
                if self.val[v] == 0:
                    return v if self.phase[v] == 1 else -v
            return 0
        for v in range(1, self.n + 1):
            if self.val[v] == 0:
                return v if self.phase[v] == 1 else -v
        return 0

    def solve(self, max_conflicts=None):
        if not self.ok:
            if self.proof is not None:
                self.proof.append(("a", []))
            return False
        run, budget = 1, (self.luby_unit * luby(1))
        since_restart = 0
        next_reduce = self.first_reduce
        lbd_queue, lbd_sum = [], 0
        while True:
            confl = self.propagate()
            if confl is not None:
                self.conflicts += 1
                since_restart += 1
                if not self.lim:
                    if self.proof is not None:
                        self.proof.append(("a", []))
                    return False
                learnt, bj, lbd = self.analyze(confl)
                self.backtrack(bj)
                if self.proof is not None:
                    self.proof.append(("a", list(learnt)))
                ci = self.add_clause(learnt, learnt=True, lbd=lbd)
                self.live += 1
                self.db_sum += self.live
                self.assign(learnt[0], ci)
                self.var_inc /= self.var_decay
                self.cla_inc /= self.cla_decay
                lbd_sum += lbd
                lbd_queue.append(lbd)
                if len(lbd_queue) > 50:
                    lbd_queue.pop(0)
                continue
            if max_conflicts is not None and self.conflicts >= max_conflicts:
                return None
            # reinicio
            if self.restarts == "luby" and since_restart >= budget:
                self.backtrack(0)
                self.restarts_done += 1
                run += 1
                budget, since_restart = self.luby_unit * luby(run), 0
                continue
            if (self.restarts == "glucose" and len(lbd_queue) == 50
                    and sum(lbd_queue) / 50 * 0.8 > lbd_sum / self.conflicts):
                self.backtrack(0)
                self.restarts_done += 1
                lbd_queue.clear()
                since_restart = 0
                continue
            if self.deletion != "none" and self.conflicts >= next_reduce:
                self.reduce_db()
                next_reduce = self.conflicts + self.first_reduce + self.inc_reduce * self.reductions
            l = self.pick()
            if l == 0:
                return True
            self.lim.append(len(self.trail))
            self.decisions += 1
            self.assign(l, -1)

    def model(self):
        return [v if self.val[v] == 1 else -v for v in range(1, self.n + 1)]


class DPLL(CDCL):
    """El motor de la lección anterior: vuelta atrás cronológica, sin aprender, orden fijo de variables."""

    def __init__(self, n, clauses):
        super().__init__(n, clauses, vsids=False, restarts="none", deletion="none", minimize=False)
        occ = [0] * (n + 1)
        for c in clauses:
            for l in c:
                occ[abs(l)] += 1
        self.order = sorted(range(1, n + 1), key=lambda v: -occ[v])

    def solve(self, max_decisions=None):
        if not self.ok:
            return False
        flipped = []
        while True:
            if self.propagate() is not None:
                self.conflicts += 1
                d = len(flipped) - 1
                while d >= 0 and flipped[d]:
                    d -= 1
                if d < 0:
                    return False
                l = self.trail[self.lim[d]]
                self.backtrack(d)
                del flipped[d:]
                self.lim.append(len(self.trail))
                self.assign(-l, -1)
                flipped.append(True)
                continue
            if max_decisions is not None and self.decisions >= max_decisions:
                return None
            v = next((v for v in self.order if self.val[v] == 0), 0)
            if v == 0:
                return True
            self.lim.append(len(self.trail))
            self.decisions += 1
            self.assign(-v, -1)
            flipped.append(False)


# Validación: el mismo veredicto que el DPLL de la lección anterior en fórmulas aleatorias pequeñas, con la
# configuración normal y con reinicios y limpiezas muy frecuentes (para ejercitar los casos raros).
def random_ksat(rng, n, m, k=3):
    return [[v if rng.random() < 0.5 else -v for v in rng.sample(range(1, n + 1), k)] for _ in range(m)]

def satisfies(F, model):
    s = set(model)
    return all(any(l in s for l in c) for c in F)

rng = random.Random(0)
t0 = time.perf_counter()
N_FORM, sat = 1500, 0
for t in range(N_FORM):
    n = rng.randint(3, 12)
    F = random_ksat(rng, n, int(rng.uniform(2.0, 7.0) * n), min(n, rng.choice([2, 3, 3, 4])))
    ref = DPLL(n, F).solve()
    for kw in ({}, {"luby_unit": 1, "first_reduce": 3, "inc_reduce": 1, "deletion": "activity"}):
        S = CDCL(n, F, **kw)
        r = S.solve()
        assert r == ref, (F, kw)
        if r:
            assert satisfies(F, S.model())
    sat += ref
print(f"{N_FORM} fórmulas, {sat} satisfacibles: CDCL (dos configuraciones) y DPLL coinciden siempre, "
      f"y cada modelo satisface su fórmula ({time.perf_counter() - t0:.1f} s)")

All 1500 formulas (931 satisfiable) give the same verdict in both configurations as DPLL, and every model satisfies its formula. Now the real question: how much is gained on structured problems? The next cell generates multi-agent planning on a grid (each agent goes from start to goal in TT steps, without sharing a cell or crossing; planning as satisfiability), sudoku, and the pigeonhole principle PHP(p,h)(p, h), saying pp pigeons cannot fit into h<ph < p holes one per hole.

[ ]DPLL versus CDCL on planning, sudoku and pigeonholeBrowser
def random_ksat(rng, n, m, k=3):
    return [[v if rng.random() < 0.5 else -v for v in rng.sample(range(1, n + 1), k)] for _ in range(m)]


def satisfies(F, model):
    s = set(model)
    return all(any(l in s for l in c) for c in F)


def php(p, h):
    """Principio del palomar: p palomas, h huecos. Variable x(i, j): la paloma i en el hueco j."""
    v = lambda i, j: i * h + j + 1
    F = [[v(i, j) for j in range(h)] for i in range(p)]
    F += [[-v(i, j), -v(k, j)] for j in range(h) for i in range(p) for k in range(i + 1, p)]
    return F, p * h


def mapf(w, h, muros, agentes, T):
    """Planificación multiagente en una cuadrícula: cada agente va de su inicio a su meta en exactamente T pasos
    (puede esperar), sin coincidir dos en una casilla ni cruzarse por la misma arista.
    Variable at(a, c, t): el agente a está en la casilla c en el instante t."""
    celdas = [(x, y) for y in range(h) for x in range(w) if (x, y) not in muros]
    idx = {c: i for i, c in enumerate(celdas)}
    vec = {c: [c] + [(c[0] + dx, c[1] + dy) for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1))
                     if (c[0] + dx, c[1] + dy) in idx] for c in celdas}
    A, C = len(agentes), len(celdas)
    at = lambda a, c, t: 1 + (a * (T + 1) + t) * C + idx[c]
    F = []
    for a, (s, g) in enumerate(agentes):
        F.append([at(a, s, 0)])
        F.append([at(a, g, T)])
        for t in range(T + 1):
            F.append([at(a, c, t) for c in celdas])
            for c1, c2 in itertools.combinations(celdas, 2):
                F.append([-at(a, c1, t), -at(a, c2, t)])
            if t < T:
                for c in celdas:
                    F.append([-at(a, c, t)] + [at(a, d, t + 1) for d in vec[c]])
    for t in range(T + 1):
        for a, b in itertools.combinations(range(A), 2):
            for c in celdas:
                F.append([-at(a, c, t), -at(b, c, t)])
            if t < T:
                for c in celdas:
                    for d in vec[c][1:]:
                        F.append([-at(a, c, t), -at(a, d, t + 1), -at(b, d, t), -at(b, c, t + 1)])
    return F, A * (T + 1) * C


def sudoku(pistas):
    """Sudoku 9 × 9: variable s(f, c, d) = la casilla (f, c) lleva el dígito d. pistas: cadena de 81 caracteres."""
    s = lambda f, c, d: 81 * f + 9 * c + d
    F = []
    grupos = [[(f, c) for c in range(9)] for f in range(9)] + [[(f, c) for f in range(9)] for c in range(9)]
    grupos += [[(3 * bf + i, 3 * bc + j) for i in range(3) for j in range(3)] for bf in range(3) for bc in range(3)]
    for f in range(9):
        for c in range(9):
            F.append([s(f, c, d) for d in range(1, 10)])
            for d1, d2 in itertools.combinations(range(1, 10), 2):
                F.append([-s(f, c, d1), -s(f, c, d2)])
    for g in grupos:
        for d in range(1, 10):
            for (a, b), (e, f2) in itertools.combinations(g, 2):
                F.append([-s(a, b, d), -s(e, f2, d)])
    for i, ch in enumerate(pistas):
        if ch not in ".0":
            F.append([s(i // 9, i % 9, int(ch))])
    return F, 729


def mapf_aleatorio(seed, k, T, w=4, h=4):
    """k agentes con inicio y meta al azar en una cuadrícula w × h sin muros."""
    rng = random.Random(seed)
    celdas = [(x, y) for y in range(h) for x in range(w)]
    return mapf(w, h, set(), list(zip(rng.sample(celdas, k), rng.sample(celdas, k))), T)

DIFICIL = "8..........36......7..9.2...5...7.......457.....1...3...1....68..85...1..9....4.."
casos = [("planificación, 12 agentes, T = 4", mapf_aleatorio(0, 12, 4)),
         ("planificación, 12 agentes, T = 5", mapf_aleatorio(0, 12, 5)),
         ("sudoku difícil", sudoku(DIFICIL)),
         ("palomar, 7 palomas y 6 huecos", php(7, 6))]
LIMITE = {"palomar, 7 palomas y 6 huecos": 5000}    # presupuesto del DPLL: 2500 decisiones (5000 en el palomar, que acaba antes)
for nombre, (F, n) in casos:
    t0 = time.perf_counter(); D = DPLL(n, F); rd = D.solve(max_decisions=LIMITE.get(nombre, 2500)); td = time.perf_counter() - t0
    t0 = time.perf_counter(); S = CDCL(n, F); rc = S.solve(); tc = time.perf_counter() - t0
    fmt = lambda r: "SAT" if r else "UNSAT" if r is False else "sin acabar"
    print(f"{nombre} ({n} var., {len(F)} cl.)")
    print(f"   DPLL: {fmt(rd):10s} {D.conflicts:6d} conflictos {D.decisions:6d} decisiones  {td:.2f} s")
    print(f"   CDCL: {fmt(rc):10s} {S.conflicts:6d} conflictos {S.decisions:6d} decisiones  {tc:.2f} s")

On both planning instances and sudoku, DPLL exhausts its 2500-decision budget without deciding; CDCL finishes in 44, 13 and 63 conflicts. Pigeonhole differs: CDCL needs 821 conflicts versus DPLL’s 3246, only a fourfold improvement; the lesson’s end shows this is not bad luck.

What each piece contributes

To measure each component’s contribution, the next cell removes them one at a time across a family of unsatisfiable instances: an 5×35 \times 3 puzzle with 14 agents and one free cell, like the 15-puzzle with simultaneous moves, unsolvable in T=5T = 5 steps. Six instances are split across three short cells.

[ ]Ablation (1 of 3): remove each componentBrowser
# Rompecabezas 5 × 3 con 14 agentes y una sola casilla libre, en T = 5 pasos: seis instancias insatisfacibles
# (las semillas 1, 5, 10, 11, 12 y 19, las seis primeras con más de 120 conflictos con el resolvedor completo).
CONFIGS = {"completo": {}, "sin VSIDS": {"vsids": False}, "sin reinicios": {"restarts": "none"},
           "sin minimizar": {"minimize": False}}
tabla = {nombre: [] for nombre in CONFIGS}

def ablacion(semillas):
    for s in semillas:
        F, n = mapf_aleatorio(s, 14, 5, w=5, h=3)
        for nombre, kw in CONFIGS.items():
            S = CDCL(n, F, **kw)
            assert S.solve() is False
            tabla[nombre].append(S)
        print(f"semilla {s:2d}: " + "  ".join(f"{k} {tabla[k][-1].conflicts}" for k in CONFIGS))

ablacion([5, 10, 11])
[ ]Ablation (2 of 3)Browser
ablacion([1])
[ ]Ablation (3 of 3) and summaryBrowser
ablacion([12, 19])
base = tabla["completo"]
print()
for nombre, xs in tabla.items():
    conf = sum(S.conflicts for S in xs)
    vis = sum(S.visits for S in xs)
    peor = sum(S.conflicts > B.conflicts for S, B in zip(xs, base))
    print(f"{nombre:14s} conflictos {conf:5d} (×{conf / sum(B.conflicts for B in base):.2f})  "
          f"visitas ×{vis / sum(B.visits for B in base):.2f}  reinicios {sum(S.restarts_done for S in xs):3d}  "
          f"peor que el completo en {peor} de 6")
quitados = sum(S.lits_before - S.lits_after for S in base) / sum(S.lits_before for S in base)
aprendidas = sum(S.conflicts - 1 for S in base)
print(f"\nminimización: quita el {100 * quitados:.1f} % de los literales 1-UIP; "
      f"baja el LBD de {sum(S.lbd_baja for S in base)} de {aprendidas} cláusulas aprendidas")

The numbers tell a clear story for two components and leave another open:

  • VSIDS matters most. Without it (fixed variable order), conflicts multiply by 3.37 and clause visits by 4.08; it is worse on all six instances.
  • Minimization helps. It removes 28.0% of 1-UIP clause literals; without it there are 1.18 times as many conflicts, worse on five of six.
  • Restarts have little effect here. With MiniSat’s Luby unit (100 conflicts) and runs of 125 to 381 conflicts, the full solver restarts only 7 times total; removing them gives 0.94 times the conflicts (worse on one of six). Their benefit appears in long runs, explained in the restart section.

A general lesson: on small instances, an inactive component cannot help, and a single measurement cannot distinguish improvement from luck. Measuring components needs an instance family and a count of improvements, not just a total.

Heuristics: VSIDS, EVSIDS and phase saving

Chaff described its heuristic in five rules (Moskewicz et al., 2001):

  1. every variable, in each polarity, has a counter initialized to 0;
  2. adding a clause to the database increments each literal’s counter;
  3. decide the free variable with highest counter in that polarity;
  4. break ties randomly;
  5. periodically divide every counter by a constant.

Dividing by δ\delta looks like a trick, but is exactly rule 5’s decay performed each conflict without traversing variables.

Proof

With g0=1g_0 = 1, the increment at conflict tit_i is gti=δ−tig_{t_i} = \delta^{-t_i}, so sv(t)=∑iδ−tis_v(t) = \sum_i \delta^{-t_i} and sv(t)/gt=∑iδ−tiδt=∑iδt−tis_v(t) / g_t = \sum_i \delta^{-t_i} \delta^{t} = \sum_i \delta^{t - t_i}. Since gtg_t is common to all variables, dividing does not change their order.

∎

With δ=0.95\delta = 0.95, a bump 50 conflicts ago weighs under 8% of a current one (0.9550≈0.0770.95^{50} \approx 0.077): the heuristic has short memory and follows the formula region producing conflicts. Choosing the most active variable must be cheap, since every decision does it and activity changes each conflict. MiniSat keeps free variables in a variable-indexed max binary heap, an indexed priority queue: increasing activity is _up from the variable’s position, O(log⁡n)\bigO(\log n); assigned variables are lazily removed when at the top and returned on unassignment. This is the cell’s Heap class.

Phase saving (Pipatsrisawat and Darwiche, 2007) completes the decision: choose the variable’s last value as polarity. A backjump or restart undoes many assignments unrelated to the conflict, such as an independent formula region already satisfied. Phase saving reconstructs them when those variables are decided again, rather than rediscovering them.

The next interactive runs a complete CDCL (propagation, 1-UIP analysis, backjump, VSIDS with δ=0.95\delta = 0.95, phase saving and Luby restarts) and saves a snapshot of each step.

InteractiveThe life of a CDCL
Search begins: nothing assigned.
Trail by decision level
empty
Learned clauses (0)
none yet
VSIDS activity by variable
x₁
0.0
x₂
0.0
x₃
0.0
x₄
0.0
x₅
0.0
x₆
0.0
x₇
0.0
x₈
0.0
x₉
0.0
x₁₀
0.0
x₁₁
0.0
x₁₂
0.0
  • next variable to decide
  • unassigned
  • assigned (level color)
1 / 74
Conflicts · decisions0 · 0
Propagations · restarts0 · 0
At completionunsatisfiable: 7 conflicts, 9 decisions
Real computation in your browser on three small instances. Left: trail by level (each decision bold) and learned clauses with LBD and backjump; right: each variable's VSIDS activity, next decision orange. Initially, first learning on pigeonhole 4 into 3: after the first conflict the solver learns a clause and jumps from level 3 to 2. Go back to see the conflict and forward: the second conflict returns it to level 0. Find a jump skipping levels (3 to 1). Enable restarts and compare totals; switch to pigeonhole 5 into 4 and disable VSIDS.

For 4 pigeons and 3 holes, the full solver needs 7 conflicts and learns LBD-1 and LBD-2 clauses; three of six jumps skip at least one level. Notice that on 5 into 4, fixed order needs fewer conflicts than VSIDS (18 versus 28). On tiny perfectly symmetric instances variable order barely matters and VSIDS has no structure to find; its advantage appeared in planning, concentrating search on the formula region causing conflicts.

Restarts and clause-database management

Restarting without forgetting

A restart undoes all decisions (returns to level 0) while retaining learned clauses, activities and saved phases. Original motivations were statistical: randomized search runtime often has a heavy-tailed distribution, and restarting cuts off unlucky runs (Gomes, Selman, Crato and Kautz, 2000). With saved phases the meaning has changed: as Audemard and Simon (2009) note, a restart no longer goes elsewhere in the space, but reorders variable dependencies using current activities and returns by another path to a similar state.

How often to restart? Luby, Sinclair and Zuckerman (1993) solved a broader problem: given a Las Vegas algorithm with unknown runtime distribution, what cutoff sequence t1,t2,…t_1, t_2, \dots (run for tit_i steps then restart) minimizes expected time?

The sequence is self-similar: each block ending at 2k−12^{k-1} repeats the preceding block twice. Thus the algorithm spends approximately the same total time on each cutoff size without knowing which is best. MiniSat restarts by Luby with unit 100 conflicts (defaults luby = true, rfirst = 100). Glucose uses dynamic restarts: restart when mean LBD of the last 50 learned clauses times K=0.8K = 0.8 exceeds the global mean (recent clauses are worse than usual), and block restart if the current trail exceeds R=1.4R = 1.4 times the mean over the last 5000 conflicts (possibly near a model). These are its source-code defaults.

The previous termination guarantee still applies to Luby: terms are unbounded, so a restart-free interval as long as needed eventually arrives.

Which learned clauses to keep

Each conflict adds a clause. After a million conflicts the learned database far exceeds the formula, and propagation, almost all runtime, visits more and more clauses. Deletion is needed; which clauses?

MiniSat ranks by activity: every clause participating in analysis receives a bump decaying as in VSIDS (δ=0.999\delta = 0.999), and the least active half is deleted. Glucose changed the criterion to LBD and measured why it works, running MiniSat on SAT-Race 2006 instances:

  • glue clauses perform 40% of learned-clause propagations, versus 20% for binary clauses;
  • half of learned clauses used in conflict analysis have LBD below 6, while length needs to reach 13 literals to cover the same half;
  • a glue clause participates on average in 1827 conflict analyses, an LBD-4 clause only 136.

Glucose therefore deleted freely: half of learned clauses every 20000+500x20000 + 500x conflicts (xx previous cleanups), retaining reason clauses. Current Glucose code sorts learned clauses by LBD (activity breaks ties), deletes the worst half and never touches binary, glue or locked clauses. Analysis is connected: among UIP clauses, 1-UIP has minimum LBD. Audemard and Simon’s sketched argument matches the resolution-chain proof: resolving a reason cannot remove a level, because a level-ℓ\ell literal’s reason contains another level-ℓ\ell literal.

To see this in your solver, the following cells run six planning instances (4×44 \times 4, 15 agents, T=5T = 5) without deletion, and at each scheduled cleanup snapshot potentially deletable clauses with LBD, activity and use count so far. Finally each clause knows how often it participated in analysis and how long it lived.

[ ]Six traces without deletion (1 of 2)Browser
class Traza(CDCL):
    """No borra nada: en cada limpieza programada fotografía las aprendidas que se podrían borrar
    (las no bloqueadas de más de dos literales) con su LBD, su actividad y sus usos hasta ese momento."""
    def reduce_db(self):
        self.fotos.append((self.conflicts, [(ci, self.lbd[ci], self.cact[ci], self.uses[ci])
                           for ci in range(len(self.clauses)) if self.learnt[ci] and len(self.clauses[ci]) > 2
                           and not self.locked(ci)]))
        self.reductions += 1

def traza(semilla):
    F, n = mapf_aleatorio(semilla, 15, 5)
    S = Traza(n, F, first_reduce=100, inc_reduce=50)
    S.fotos = []
    S.solve()
    return S

trazas = [traza(s) for s in (0, 1, 2)]
print([S.conflicts for S in trazas])
[ ]Six traces without deletion (2 of 2) and uses by LBDBrowser
trazas += [traza(s) for s in (3, 4, 6)]
print([S.conflicts for S in trazas], "conflictos;", sum(S.conflicts - 1 for S in trazas), "cláusulas aprendidas\n")
# usos en análisis según el LBD (las de LBD ≥ 12, juntas), por cláusula y por 1000 conflictos de vida
por_lbd = {}
for S in trazas:
    for ci in range(len(S.clauses)):
        if S.learnt[ci] and len(S.clauses[ci]) > 1:
            t = por_lbd.setdefault(min(S.lbd[ci], 12), [0, 0, 0])
            t[0] += 1; t[1] += S.uses[ci]; t[2] += S.conflicts - S.born[ci]
for b in sorted(por_lbd):
    c, u, v = por_lbd[b]
    print(f"LBD {b:2d}{'+' if b == 12 else ' '}: {c:4d} cláusulas, {u:5d} usos, {u / c:5.2f} por cláusula, "
          f"{1000 * u / v:5.2f} por 1000 conflictos de vida")

The trend matches Glucose. Each glue clause participates in 8.16 analyses on average (18.22 per 1000 conflicts of life), while LBD 12 or more averages 1.26 (2.36 per 1000). Lifetime normalization rules out a trivial explanation: late-learned clauses have less time to be used, but the order remains.

What would each deletion criterion do? The next cell simulates the same traces: each cleanup deletes clauses with LBD above kk, or the same number with lowest activity, counting lost later uses and average memory. This is counterfactual: it assumes unchanged search, which is false (deletion changes later conflicts), but measures how well each criterion predicts future utility.

[ ]Counterfactual deletion: LBD versus activityBrowser
def simula(S, criterio, k):
    """Borrado contrafactual sobre la traza: en cada limpieza caen las cláusulas con LBD > k (criterio "lbd"),
    o el mismo número de cláusulas, las de menor actividad ("actividad"). Devuelve los usos posteriores que se
    habrían perdido, los usos totales y la memoria media (aprendidas vivas por conflicto)."""
    borrada = {}
    for t, foto in S.fotos:
        vivas = [x for x in foto if x[0] not in borrada]
        cuantas = sum(1 for x in vivas if x[1] > k)
        quitar = [x for x in vivas if x[1] > k] if criterio == "lbd" else sorted(vivas, key=lambda x: x[2])[:cuantas]
        for ci, _, _, usos in quitar:
            borrada[ci] = (t, usos)
    perdidos = sum(S.uses[ci] - u for ci, (t, u) in borrada.items())
    total = sum(S.uses[ci] for ci in range(len(S.clauses)) if S.learnt[ci])
    vida = sum((borrada[ci][0] if ci in borrada else S.conflicts) - S.born[ci]
               for ci in range(len(S.clauses)) if S.learnt[ci])
    return perdidos, total, vida / S.conflicts

for criterio in ("lbd", "actividad"):
    for k in (2, 3, 4, 5, 6, 8, 10):
        r = [simula(S, criterio, k) for S in trazas]
        print(f"{criterio:9s} k = {k:2d}: usos perdidos {100 * sum(x[0] for x in r) / sum(x[1] for x in r):5.1f} %, "
              f"memoria media {sum(x[2] for x in r) / len(r):6.1f} cláusulas")
print(f"sin borrar: memoria media {sum(simula(S, 'lbd', 99)[2] for S in trazas) / len(trazas):6.1f} cláusulas")

The answer depends on aggressiveness. At moderate thresholds LBD predicts better: with k=5k = 5 it loses 5.3% of future uses with 215.1 clauses on average, while activity with similar memory (211.7, k=6k = 6) loses 8.4%. Very aggressive thresholds reverse this: with k=3k = 3 LBD loses 24.7% with 140.9 clauses and activity 24.2% with 125.2. The criteria coexist: Glucose orders by LBD, breaks ties by activity, and many successors protect low-LBD clauses while managing others by activity.

What about a real run where deletion changes search? The next cell repeats six instances with actual deletion by each criterion and threshold. These are 96 runs (a few minutes in the browser), so automatic checks do not execute it; output from the same code outside the browser feeds the interactive.

[ ]Actual threshold deletion (96 runs, a few minutes)Browser
class Umbral(CDCL):
    """Borrado real con umbral: en cada limpieza caen las aprendidas no bloqueadas con LBD > k ("lbd"),
    o el mismo número, las de menor actividad ("actividad")."""
    k = 4
    def reduce_db(self):
        cand = [ci for ci in range(len(self.clauses)) if self.learnt[ci] and self.clauses[ci] is not None
                and len(self.clauses[ci]) > 2 and not self.locked(ci)]
        cuantas = sum(1 for ci in cand if self.lbd[ci] > self.k)
        quitar = ([ci for ci in cand if self.lbd[ci] > self.k] if self.deletion == "lbd"
                  else sorted(cand, key=lambda ci: self.cact[ci])[:cuantas])
        for ci in quitar:
            self.clauses[ci] = None
            self.deleted += 1
            self.live -= 1
        self.reductions += 1

formulas = [mapf_aleatorio(s, 15, 5) for s in (0, 1, 2, 3, 4, 6)]
for criterio in ("lbd", "actividad"):
    for k in (2, 3, 4, 5, 6, 8, 10, None):
        Umbral.k = 0 if k is None else k
        res = []
        for F, n in formulas:
            S = Umbral(n, F, deletion="none" if k is None else criterio, first_reduce=100, inc_reduce=50)
            S.solve()
            res.append(S)
        conf = sum(S.conflicts for S in res)
        mem = sum(S.db_sum / S.conflicts for S in res) / len(res)
        vpp = sum(S.visits for S in res) / sum(S.props for S in res)
        etiqueta = "sin borrar" if k is None else f"k = {k:2d}"
        print(f"{criterio:9s} {etiqueta:10s}: {conf:5d} conflictos, memoria media {mem:6.1f}, "
              f"{vpp:.3f} visitas por propagación, {sum(S.visits for S in res)} visitas")

The robust results are memory and propagation: deletion with k=2k = 2 reduces average memory from 343.4 to 131.9 clauses and propagation visits from 6,450 to 5,980, at the cost of 5478 conflicts versus 4121 without deletion. Intermediate-threshold conflict counts fluctuate between 3187 and 4689 without a clear winner: with six instances of hundreds of conflicts, each deletion’s search effect is noise. In such instances the database barely grows enough to matter; in Glucose’s SAT-Race instances MiniSat’s database grew until propagation slowed, while aggressive LBD deletion retained speed.

InteractiveWhich learned clauses to keep
Learned clauses by LBD and later use
00.03109.162018.223456789101112+Clause LBD when learned
  • retained clauses (glue, LBD 2, in green)
  • deleted by LBD at this threshold
  • analysis uses per 1000 lifetime conflicts (right axis)
Memory versus future uses lost (deletion on the same trace)
0 %10 %20 %30 %40 %0100200300average memory: live learned clausesno deletion
  • delete by LBD (LBD > k)
  • delete by activity (same count)
LBD ≤ 4
Readout criterion
Uses (top)
Trace: future uses lost14.3 %
Trace: average memory (live learned clauses)179.7
Actual run: conflicts (4121 without deletion)3320
Actual run: memory · visits per propagation160.8 · 6.16
At k = 4, the LBD criterion loses 14.3% of future uses with 180 clauses on average; the other loses 15.6% with 155.
Data from the preceding cells: six 4×44 \times 4 planning instances with 15 agents. Top: learned-clause counts by LBD (bars) and each one's later conflict-analysis uses (magenta curve). Bottom: average memory versus future uses lost in counterfactual deletion, by LBD (blue) and activity (orange). Start at k=4k = 4: per 1000 lifetime conflicts, glue (green) is used nearly eight times more than LBD 12 or above. Move the threshold right and compare lower curves; then switch to k=2k = 2 and read how many more conflicts the actual run needs.

Learned-clause minimization

The example’s 1-UIP clause, (¬x11∨¬x6∨¬x5∨¬x4)(\lnot x_{11} \lor \lnot x_6 \lor \lnot x_5 \lor \lnot x_4), has a redundant literal. The reason for x6x_6 is C3=(¬x5∨x6)C_3 = (\lnot x_5 \lor x_6), and ¬x5\lnot x_5 is already in the clause. Resolving with C3C_3 on x6x_6 gives (¬x11∨¬x5∨¬x4)(\lnot x_{11} \lor \lnot x_5 \lor \lnot x_4), which subsumes the original: self-subsumption from the previous lesson applied to a learned clause.

MiniSat’s recursive minimization generalizes this: learned-clause literal ¬p\lnot p is redundant if all literals in the reason for pp are in the clause, at level 0, or recursively redundant by the same criterion. This is backward DFS over the implication graph, failing upon reaching a decision outside the clause. The cell implementation (minimize_clause and _redundant) keeps already-proved redundant literals marked to avoid repeating work, and uses a cheap filter, a bitmask of levels in the clause, to immediately reject paths leaving those levels.

Sörensson and Biere (SAT 2009) measured MiniSat and PicoSAT on SAT-Race 2008: recursive minimization removes one third of 1-UIP literals on average, increases solved instances about 9%, and halves memory. Your solver removed 28.0% of literals and reduced conflicts on five of six ablation instances.

What about LBD? The ablation counted it: minimization reduced LBD of none of 1154 learned clauses. This is no coincidence.

Proof

Let ¬p\lnot p be a removed literal, with pp at level ℓ>0\ell > 0. Decisions are never removed (no reason), so pp was propagated and, as in the 1-UIP proof, its reason contains another literal r1r_1 at level ℓ\ell. To remove ¬p\lnot p, r1r_1 must be covered: its negation is in the clause or it is itself removable (not level 0). In the latter case r1r_1 is not a decision and its reason contains an earlier trail literal r2r_2 at level ℓ\ell, which must be covered, and so on. Positions decrease, so the chain ends at a level-ℓ\ell literal whose negation lies in the clause and differs from ¬p\lnot p. Level ℓ\ell remains represented after removing ¬p\lnot p, and by the same argument after all removals.

∎

Minimization shortens clauses, reducing memory and watching cost, but does not change their LBD quality. Choosing another UIP can reduce LBD, and first UIP already has the minimum.

Certifying UNSAT: DRUP and DRAT proofs

When a solver says “satisfiable”, it returns a model, trivial to check. When it says “unsatisfiable”, why believe it? Solvers have bugs, and answers may assert that a chip has no flaws or a combinatorial theorem is true. Have the solver emit a proof checkable by a small independent program.

Reverse-unit-propagation checking is due to Goldberg and Novikov (2003). DRAT and reference checker drat-trim are by Wetzler, Heule and Hunt (2014): RAT also certifies preprocessing and reasoning adding non-implied clauses, while deletion lines make verification practical by dropping clauses the solver discarded.

For CDCL, write each learned clause when learned and each deletion when performed. A nearly proven theorem establishes correctness.

Proof

Assigning ¬C\lnot C makes the cut frontier literals true. Traverse the conflict side in trail order: every node’s reason has all literals false except its own, since predecessors lie on the frontier or have already propagated; unit propagation deduces them, finally falsifying clause C⋆C^\star. Propagation may reach another conflict earlier, also sufficient. For the minimized clause, removed literals are deducible by propagation from those remaining (what recursive search checks), so the argument repeats. A level-0 conflict means propagation on the database without assumptions already reaches a false clause: the empty clause is RUP.

∎

Lab 2: build a proof checker

The checker inherits the solver’s watched propagation and checks forward: for each added clause assign its negation at a temporary level, propagate, require conflict, undo, then add it. drat-trim checks backward from the empty clause, marking only actually used clauses; much faster for large proofs and able to trim them, but checking the same idea.

[ ]A DRUP proof checkerBrowser
class VerificadorRUP(CDCL):
    """Comprueba una prueba DRUP hacia delante: cada cláusula añadida C debe ser RUP respecto a la base actual
    (asignar ¬C y propagar llega a un conflicto); los borrados la quitan de la base. Reutiliza la propagación con
    vigilados del resolvedor. Como drat-trim, ignora el borrado de una cláusula que es razón en el nivel 0."""

    def __init__(self, n, clauses):
        super().__init__(n, clauses, vsids=False, restarts="none", deletion="none")
        self.indice = {}
        for ci, c in enumerate(self.clauses):
            self.indice.setdefault(tuple(sorted(c)), []).append(ci)
        self.raiz_inconsistente = (not self.ok) or self.propagate() is not None
        self.comprobaciones = 0

    def es_rup(self, C):
        if self.raiz_inconsistente:
            return True                                  # la base ya es inconsistente por propagación
        self.comprobaciones += 1
        self.lim.append(len(self.trail))                 # un nivel provisional para ¬C
        conflicto = False
        for l in C:
            if self.value(l) == 1:                       # ¬C contradice algo ya deducido
                conflicto = True
                break
            if self.value(l) == 0:
                self.assign(-l, -1)
        if not conflicto:
            conflicto = self.propagate() is not None
        self.backtrack(0)
        return conflicto

    def anade(self, C):
        C = list(dict.fromkeys(C))
        ci = len(self.clauses)
        self.clauses.append(C); self.learnt.append(True); self.lbd.append(0); self.cact.append(0.0)
        self.uses.append(0); self.born.append(0)
        self.indice.setdefault(tuple(sorted(C)), []).append(ci)
        if self.raiz_inconsistente:
            return
        C.sort(key=lambda l: self.value(l) == -1)        # primero los literales no falsos: vigilancia válida
        libres = [l for l in C if self.value(l) != -1]
        if any(self.value(l) == 1 for l in C):
            pass
        elif not libres:
            self.raiz_inconsistente = True
            return
        elif len(libres) == 1:
            self.assign(libres[0], ci)                   # unitaria en la raíz
            if self.propagate() is not None:
                self.raiz_inconsistente = True
                return
        if len(C) >= 2:
            self.watches.setdefault(C[0], []).append(ci)
            self.watches.setdefault(C[1], []).append(ci)

    def borra(self, C):
        for ci in self.indice.get(tuple(sorted(C)), []):
            c = self.clauses[ci]
            if c is None:
                continue
            if self.reason[abs(c[0])] == ci or (len(c) > 1 and self.reason[abs(c[1])] == ci):
                return                                    # razón en la raíz: se ignora
            self.clauses[ci] = None
            return


def verifica(n, F, prueba):
    """Devuelve (True, None) si la prueba certifica UNSAT, o (False, i) con el primer paso que falla."""
    V = VerificadorRUP(n, F)
    for i, (tipo, C) in enumerate(prueba):
        if tipo == "d":
            V.borra(C)
            continue
        if not V.es_rup(C):
            return False, i
        V.anade(C)
        if len(C) == 0:
            return True, None
    return False, len(prueba)                             # nunca llegó a la cláusula vacía


F, n = php(6, 5)
S = CDCL(n, F, proof=True, first_reduce=50, inc_reduce=20)
print("palomar 6 en 5:", "UNSAT" if S.solve() is False else "SAT", f"con {S.conflicts} conflictos")
anadidas = sum(t == "a" for t, _ in S.proof)
borradas = sum(t == "d" for t, _ in S.proof)
print(f"prueba DRUP: {anadidas} cláusulas añadidas (la última, la vacía) y {borradas} borrados")
t0 = time.perf_counter()
print("verificación de la prueba original:", verifica(n, F, S.proof), f"({time.perf_counter() - t0:.2f} s)")

The 6-into-5 pigeonhole proof has 164 added clauses (163 learned plus empty) and 70 deletions, and the checker accepts it in hundredths of a second. A checker accepting everything is worthless, so the next cell gives it four manipulated proofs.

[ ]Four manipulated proofsBrowser
# Pruebas manipuladas: ¿las detecta el verificador?
P = S.proof
lemas = [i for i, (t, C) in enumerate(P) if t == "a" and len(C) >= 3]
i = lemas[len(lemas) // 2]
quita_literal = P[:i] + [("a", P[i][1][1:])] + P[i + 1:]           # un lema más fuerte de lo que se dedujo
sin_vacia = [x for x in P if x != ("a", [])]                         # falta la cláusula vacía
inventada = [("a", [1])] + P                                         # «la paloma 1 va al hueco 1», sin justificar
primeras = [j for j, (t, _) in enumerate(P) if t == "a"][:40]
sin_primeras = [x for j, x in enumerate(P) if j not in set(primeras)]  # faltan los 40 primeros lemas
for nombre, Q in [("lema con un literal menos", quita_literal), ("sin la cláusula vacía", sin_vacia),
                  ("unitaria inventada al principio", inventada), ("sin los 40 primeros lemas", sin_primeras)]:
    ok, paso = verifica(n, F, Q)
    print(f"{nombre:32s} -> " + ("aceptada" if ok else f"rechazada en el paso {paso}"
          + (f": {Q[paso][1]}" if paso < len(Q) else ": no llega a la cláusula vacía")))

All four are rejected, each revealing something. A lemma missing a literal is stronger than what was derived and is no longer RUP. Without the empty clause, the proof concludes nothing. An invented initial unit does not follow from the formula. Without the first 40 lemmas, the second remaining step is no longer RUP because it needed one of them: a proof is not independent assertions but a chain whose steps use earlier ones.

CDCL as a proof system

Pigeonhole resisted. This is not an implementation defect but a theorem about all CDCL solvers.

A CDCL run ending “unsatisfiable” is a resolution refutation: each learned clause ends a chain of resolutions with reasons (proved for 1-UIP; minimization adds the same kind), and the empty clause comes from the last level-0 conflict. Refutation size is polynomially bounded in conflicts and variables. Thus any lower bound on resolution-refutation size lower-bounds the conflict count of every CDCL, regardless of heuristic, restarts or deletion policy. This is proof complexity applied to solvers.

The classical proof (Haken, 1985) counts critical assignments placing hh pigeons in hh distinct holes and leaving one out. In the modern version simplified by Beame and Pitassi, the explicit bound is 2h/202^{h/20} (as in the University of Washington proof-complexity course, 2020). The constant is tiny: the proved bound says nothing useful for h=10h = 10, but shows an exponential wall exists. DPLL without learning, whose proof system is tree resolution, has a larger and easier bound: pigeonhole tree refutations have at least 2h2^h clauses (an exercise in the same course treats the refutation as a DPLL tree and counts branches).

The opposite direction is equally strong. Pipatsrisawat and Darwiche (2011) showed CDCL with restarts as a proof system (allowing decisions to be chosen) polynomially simulates general resolution without extra techniques. CDCL and resolution have equal power up to a polynomial: what one can prove at reasonable size the other can too, and what one cannot, neither can the other.

The next three cells measure the wall.

[ ]The pigeonhole wall with your CDCLBrowser
# El muro del palomar: nuestro CDCL en PHP(h + 1, h)
muro = []
for h in range(3, 8):
    F, n = php(h + 1, h)
    t0 = time.perf_counter()
    S = CDCL(n, F)
    S.solve()
    muro.append((h, n, len(F), S.conflicts, time.perf_counter() - t0))
    print(f"h = {h}: {n:3d} variables, {len(F):4d} cláusulas -> {S.conflicts:6d} conflictos en {muro[-1][4]:.2f} s")
[ ]DPLL and CaDiCaL on pigeonholeBrowser
from pysat.solvers import Solver

for h in range(3, 8):
    F, n = php(h + 1, h)
    D = DPLL(n, F)
    D.solve()
    print(f"h = {h}: DPLL {D.conflicts:6d} conflictos   (2^h = {2 ** h})")
for h in range(3, 9):
    F, n = php(h + 1, h)
    with Solver(name="cadical153", bootstrap_with=F) as s:
        t0 = time.perf_counter()
        r = s.solve()
        dt = time.perf_counter() - t0
        print(f"h = {h:2d}: CaDiCaL {'SAT' if r else 'UNSAT'} con {s.accum_stats()['conflicts']:6d} conflictos en {dt:.3f} s")

Your CDCL multiplies conflicts by 4 to 6 per extra hole (821 with h=6h = 6, 3637 with h=7h = 7), DPLL by 5.8 to 10.1 (32781 with h=7h = 7), and industrial CaDiCaL is no better: 994 conflicts with h=6h = 6, 6383 with h=7h = 7 and 37288 with h=8h = 8, nearly sixfold per extra hole. From h=6h = 6, CaDiCaL needs more conflicts than your solver. Its advantage is speed per conflict, not proof-system power.

InteractiveThe pigeonhole wall
11010010³10⁴10⁵10301003001000variables (logarithmic scale)h = 7
  • pigeonhole: our CDCL
  • pigeonhole: CaDiCaL
  • pigeonhole: DPLL without learning
  • bound 2h2^h (tree resolution)
  • bound 2h/202^{h/20} (general resolution)
  • planning and sudoku: our CDCL (filled), CaDiCaL (outline)
7
Vertical axis
Selected pigeonhole56 variables, 204 clauses
Our CDCL: conflicts (versus h − 1)3637 (×4.4)
CaDiCaL: conflicts (versus h − 1)6383 (×6.4)
DPLL without learning: conflicts32.8 k (×10.1)
Bounds 2h2^h · 2h/202^{h/20}128 · 1.27
With 56 variables, pigeonhole already needs 6383 CaDiCaL conflicts; planning with 1440 variables was solved with 1170 (ours) and 935 (CaDiCaL).
Conflicts (or time) versus variable count, both axes logarithmic; data from lesson cells. Curves show pigeonhole PHP(h+1,h)(h + 1, h) with your CDCL (blue), CaDiCaL (orange) and DPLL without learning (red); squares are planning instances and sudoku. Dashed lines show refutation-size bounds 2h2^h (tree resolution) and 2h/202^{h/20} (general resolution) as reference. Start at h=7h = 7: 56 variables need 3637 conflicts in your solver, more than planning with 1440 variables. Raise h=8h = 8 and switch the axis to time.

The figure summarizes the lesson. Structured instances with tens of thousands of clauses solve in tens or hundreds of conflicts because they have short refutations (or models) found by conflict analysis. Pigeonhole with hundreds of clauses lacks short resolution refutations; no heuristic can invent what the proof system lacks. Escaping the wall requires a stronger proof system: extended resolution allows new variables and polynomial pigeonhole refutations (Cook, 1976); cutting planes reason with linear inequalities like pseudo-Boolean solvers and also do so (Cook, Coullard and Turán, 1987); Buss gave polynomial-size Frege proofs. In practice avoid pure CNF pigeonhole: break problem symmetries or reason with cardinalities.

Lab 3: reading an industrial solver’s statistics

PySAT exposes CaDiCaL from Python, including in the browser. The cell solves identical instances with both solvers and compares statistics.

[ ]CaDiCaL versus your solverBrowser
# Laboratorio 3: las mismas instancias con CaDiCaL y con el resolvedor propio
instancias = [("planificación 4 × 4, 15 agentes, T = 5", mapf_aleatorio(0, 15, 5)),
              ("sudoku difícil", sudoku(DIFICIL)), ("palomar, 8 palomas y 7 huecos", php(8, 7))]
for nombre, (F, n) in instancias:
    t0 = time.perf_counter(); S = CDCL(n, F); r = S.solve(); t1 = time.perf_counter() - t0
    with Solver(name="cadical153", bootstrap_with=F) as s:
        t0 = time.perf_counter(); rc = s.solve(); t2 = time.perf_counter() - t0
        st = s.accum_stats()
    assert r == rc
    print(f"{nombre} -> {'SAT' if r else 'UNSAT'}")
    print(f"   propio : {S.conflicts:6d} conflictos {S.decisions:6d} decisiones {S.props:8d} propagaciones "
          f"{S.restarts_done:4d} reinicios | {S.props / t1:9.0f} prop./s  {t1:.3f} s")
    print(f"   CaDiCaL: {st['conflicts']:6d} conflictos {st['decisions']:6d} decisiones {st['propagations']:8d} propagaciones "
          f"{st['restarts']:4d} reinicios | {st['propagations'] / max(t2, 1e-4):9.0f} prop./s  {t2:.3f} s")

Three observations:

  • Propagations per second measure engineering. In this run CaDiCaL performs about 15 times as many propagations per second as your solver on planning, 24 times on pigeonhole. Compiled C++ versus interpreted Python, plus years of cache-conscious data structures. Individual times vary; their order of magnitude does not.
  • Conflicts measure search. On planning, CaDiCaL needs 935 conflicts versus 1170; on sudoku, 563 versus 63; on pigeonhole, 6383 versus 3637. One case per family yields no winner: industrial heuristics do not dominate everything, and a particular instance’s conflict count depends heavily on details.
  • Restarts reveal strategy. CaDiCaL restarts 357 times on pigeonhole and 33 on sudoku with its dynamic policy, versus your Luby solver’s 18 and 0.

Finally, what an industrial solver should provide: a proof with “unsatisfiable”. PySAT requests text DRAT from CaDiCaL and Glucose, and your checker verifies it. Reading discards lines not ending in 0, which are not complete clauses.

[ ]CaDiCaL and Glucose proofs checked by your verifierBrowser
def lee_drat(lineas):
    """Pasa las líneas de una prueba DRAT en texto («1 -2 0», «d 1 -2 0») al formato del verificador."""
    prueba = []
    for linea in lineas:
        xs = linea.split()
        if xs and xs[-1] == "0":
            prueba.append(("d", [int(x) for x in xs[1:-1]]) if xs[0] == "d" else ("a", [int(x) for x in xs[:-1]]))
    return prueba

F, n = mapf_aleatorio(0, 15, 5)
for nombre in ("cadical153", "glucose4"):
    with Solver(name=nombre, bootstrap_with=F, with_proof=True) as s:
        assert s.solve() is False
        P = lee_drat(s.get_proof())
    t0 = time.perf_counter()
    ok, paso = verifica(n, F, P)
    print(f"{nombre}: {len(P)} pasos ({sum(t == 'a' for t, _ in P)} añadidas, {sum(t == 'd' for t, _ in P)} borrados) -> "
          + ("certificada" if ok else f"rechazada en el paso {paso}") + f" en {time.perf_counter() - t0:.2f} s")

Both proofs certify. CaDiCaL’s has 43701 steps, 40732 deletions: it records every clause deleted or rewritten during simplification, including many original clauses (its first line already deletes one). Glucose’s has 6822 steps. Your checker of a few dozen lines has independently confirmed that no 5-step plan gets all 15 agents to their goals.

Common mistakes

Exercises

ProofThe 1-UIP clause is implied and asserting
Prove: Consider a level-d>0d > 0 conflict in a CDCL solver propagating to a fixed point before each decision, with conflict clause C⋆C^\star. Let CC be the 1-UIP clause produced by chain C0=C⋆C_0 = C^\star, Ci+1=Ci⊗vRvC_{i+1} = C_i \otimes_v R_v (resolve with the reason for the latest-assigned level-dd variable). Prove F⊨CF \models C, the chain ends with one level-dd literal, and after jumping to level bb (the highest level of other CC literals, or 0 if none), CC is unit.
0
Write the final clause C=(¬u∨¬a1∨⋯∨¬ak)C = (\lnot u \lor \lnot a_1 \lor \dots \lor \lnot a_k), with uu at level dd and the aia_i at lower levels; FF includes previously learned clauses.

Step 1 of 5. Why is each Ci⊗vRvC_i \otimes_v R_v step a valid resolution with a nontautological resolvent?

Code1-UIP analysis from the trail
Implement analyze_conflict(trail, reasons, conflict). trail lists (literal, nivel) pairs in assignment order; reasons maps each variable to its reason (a literal list containing the forced literal), or None for a decision; conflict is the clause with all literals false. Return (clausula, nivel_de_salto): the unminimized 1-UIP clause with the first UIP's negation at position 0, and the backjump level. Tests use the lesson example and 300 implication graphs generated by propagation with random decisions, comparing with the first-UIP cut computed on the graph; they also check that the clause is asserting and follows from the formula.
def analyze_conflict(trail, reasons, conflict):
  """trail: [(literal, nivel)], reasons: {variable: lista o None}, conflict: lista de literales.
  Devuelve (cláusula 1-UIP con la UIP negada en la posición 0, nivel de salto)."""
  nivel = {abs(l): d for l, d in trail}
  dl = max(nivel[abs(q)] for q in conflict)
  # tu código: recorre el trail hacia atrás resolviendo con las razones
  # hasta que quede un solo literal del nivel dl
  return [], 0
Shift+Enter to run
NumericTen Luby restarts
Write the first 15 terms L1,…,L15L_1, \dots, L_{15} of the Luby sequence. With unit 100, run ii lasts 100 Li100\,L_i conflicts and ends with restart ii. How many conflicts are allowed in total from the start through the tenth restart inclusive?
QuizWhich can be deleted?
The trail at level 1 is x7x_7 (decision), x6x_6 (reason C3C_3, original), x2x_2 (reason C5C_5, original), x5x_5 (reason A1A_1) and x3x_3 (reason A2A_2); at level 2, x4x_4 (decision) and x8x_8 (reason A3A_3). Learned clauses are A1=(¬x2∨x5∨¬x7)A_1 = (\lnot x_2 \lor x_5 \lor \lnot x_7), A2=(x3∨¬x5)A_2 = (x_3 \lor \lnot x_5), A3=(¬x4∨¬x6∨x8)A_3 = (\lnot x_4 \lor \lnot x_6 \lor x_8), A4=(x9∨x2∨¬x3)A_4 = (x_9 \lor x_2 \lor \lnot x_3) and A5=(¬x8∨x10∨x11)A_5 = (\lnot x_8 \lor x_{10} \lor x_{11}). Database cleanup begins. Which statements are true?

More than one answer may be correct.

NumericLBD of a learned clause
A learned clause has nine literals. The first-UIP literal is at level 17, and the other eight are at levels 11, 4, 11, 9, 4, 11, 4 and 9. What is its LBD when learned?
QuizWhat to watch in the learned clause
You just learned (¬u∨¬a∨¬b∨¬c)(\lnot u \lor \lnot a \lor \lnot b \lor \lnot c), with uu at level 12 and aa, bb, cc at levels 7, 3 and 5. You jump to level 7 and the clause forces ¬u\lnot u. Which two literals should be watched?
NumericEVSIDS memory
With EVSIDS and δ=0.95\delta = 0.95, what is the smallest number kk of conflicts such that an activity bump received kk conflicts ago weighs less than half a bump received now?
QuizWhat a checker certifies
Your checker accepts a solver's DRUP proof that FF is unsatisfiable. Assuming the checker is correct, what follows?
QuizEscaping the wall
Your CDCL has spent hours on PHP(13,12)(13, 12). What change can turn it into a problem solved in seconds?

Summary

Key idea
CDCL is DPLL that, at each conflict, traverses the implication graph backward, learns the first-UIP clause as a resolution chain and asserting clause, then jumps to the level where it propagates. Around this core, VSIDS and phase saving decide, restarts reorder without forgetting, LBD decides what to keep, and a DRAT proof checks each “unsatisfiable” answer without trusting the solver. As a proof system it is resolution and inherits its limits.
  • Implication-graph nodes are trail literals and κ\kappa; the trail is their topological order. Each cut gives an implied clause; the first-UIP clause resolves backward until one current-level literal remains.
  • The backjump level is the highest level among other learned-clause literals; after jumping the clause is unit. Watch the UIP and a literal at that level, and never delete a locked clause.
  • EVSIDS is an exponential moving average of conflict participation maintained in an indexed heap; phase saving reconstructs undone choices. In ablation, removing VSIDS multiplied conflicts by 3.37.
  • Luby restarts have a logarithmic optimality guarantee; Glucose restarts based on recent LBD. LBD predicts future clause utility; recursive minimization removes 28% of literals without changing LBD, a theorem.
  • Every learned clause is RUP: writing them with deletions gives a DRUP proof checkable by a short verifier. DRAT adds RAT for techniques that do not preserve equivalence.
  • CDCL equals general resolution (Pipatsrisawat and Darwiche); by Haken, pigeonhole requires exponentially many conflicts for any CDCL, including CaDiCaL.