A CDCL SAT solver in Zig, built from scratch with an emphasis on perf-profiled BCP, modern clause learning, and SAT Competition-format I/O.
- CDCL with 1-UIP conflict analysis and recursive clause minimization
(MiniSat 2.2
litRedundant) - Two-watched-literal BCP with blocker optimization and in-place watcher list compaction
- Literal-indexed value table — one load + one compare per
valueOfLiteralcall, collapsing the 8-instruction / 3-branch chain that dominated earlier profiles - Flat clause arena — a single
ArrayList(Literal)backing store with 2-slot headers; a 3-literal clause takes 20 bytes - Glucose-style adaptive restarts — fast / slow LBD EMAs with Adam-style bias correction, plus a trail-length blocker that vetoes restarts when the current decision stack is clearly making progress
- LBD-based clause DB reduction with glue (LBD ≤ 2) and locked-reason protection, on an independent conflict-count budget
- VSIDS branching with exponential activity decay and phase saving
- Chronological backtracking when the backjump would skip many levels
- Focused / stable mode alternation with rephasing (best, original, inverted and random phases). Focused mode uses the Glucose restarts; stable mode turns them off and starts from the phases of the longest trail seen so far. Mode chunks start at 1000 conflicts and double
- Preprocessing and level-0 inprocessing: backward subsumption with
self-subsuming resolution (in practice mostly between binary clauses; see
subsume.zig), equivalent-literal substitution (SCCs of the binary implication graph), bounded variable elimination, failed-literal probing, and vivification of low-LBD learned clauses. Preprocessing runs subsumption, substitution, subsumption again, then elimination; probing and vivification run only during search. Each inprocessing pass is budgeted by the propagations made since its last run: probing may spend a tenth of them and vivification two tenths; subsumption caps the clause pairs it examines at max(2 M, 2/10 of that count) and elimination at max(1 M, 1/10). Preprocessing caps them at 100 M and 50 M. Equivalent-literal substitution runs in full - Arena compaction to reclaim the holes left by deleted clauses
- DRAT proof emission (
--proof PATH) for UNSAT verification - Model check against the input — eliminated variables are
reconstructed and every SAT model is checked against every clause of the
original formula before
s SATISFIABLEis printed; a failure is reported ass UNKNOWN - Tournament I/O — streaming DIMACS CNF parsing (the input is never
held in memory whole), transparent
.gzdecompression, stdin input,SIGINT/SIGTERM/SIGXCPU+--time-limithandling, SAT Competition output format (s SATISFIABLE/s UNSATISFIABLE/s UNKNOWN,v-prefixed models, exit codes 10 / 20 / 0)
zig build # debug
zig build -Doptimize=ReleaseFast # release
zig build test # unit tests + end-to-end
zig build unit -Dtest-filter=TEXT # only the tests/unit.zig tests matching TEXT
zig build run -- formula.cnf # build, then run the solverRequires Zig 0.17. flake.nix provides it (with zls) as a dev shell, which
direnv loads through .envrc.
# Read from a file:
./zig-out/bin/sat path/to/formula.cnf
# Read compressed input:
./zig-out/bin/sat path/to/formula.cnf.gz
# Read from stdin:
./zig-out/bin/sat < formula.cnf
# Emit a DRAT proof for UNSAT verification:
./zig-out/bin/sat --proof formula.drat formula.cnf
# With a wall-clock timeout:
./zig-out/bin/sat --time-limit 60 formula.cnfsat --help lists the options.
Exit codes follow SAT Competition convention: 10 = SATISFIABLE,
20 = UNSATISFIABLE, 0 = UNKNOWN (including on interrupt or timeout).
A parse error, a solver error or a failed proof write prints a c line
naming the error, then s UNKNOWN, and also exits 0. Exit code 1 means
the solver never ran or its answer was lost: a bad option, an input or
proof file that cannot be opened, or a failed write to stdout.
The parser is strict: a missing or repeated p cnf header, a bad token, a
variable above the declared count, an unterminated last clause or a clause
count that differs from the header is a parse error. It accepts up to
2^30 variables. The v line covers variables up to the highest one a
clause mentions, so trailing variables that the header declares but no
clause uses are left out; a variable the search left unassigned is printed
positive. DRAT proofs are written in the text format.
sat-sudoku solves a 9x9 Sudoku by encoding it as CNF for the solver: one
variable per (cell, digit), exactly one digit per cell, each digit exactly
once per row, column and box, and a unit clause per given digit.
zig build sudoku -- '53..7....6..195....98....6.8...6...34..8.3..17...2...6.6....28....419..5....8..79'
./zig-out/bin/sat-sudoku < puzzle.txt # a 9-line grid works tooCells are 1-9, with . or 0 for blanks; stdin input over 64 KiB is
refused.
Exit code 0 = solved, 1 = no solution, 2 = bad input or no answer.
zig build bench runs the ReleaseFast solver on 399 random 3-SAT instances
(uf200-860, uuf200-860, uf250-1065, uuf250-1065) under perf stat -M TopdownL1 + perf record --call-graph dwarf, then prints a report
table with per-instance distribution, hardware counters, Intel Topdown L1
breakdown, call-graph hotspots, and perf annotate output for the hottest
function. It needs the instances from bench/fetch.sh and
/proc/sys/kernel/perf_event_paranoid at 1 or lower. The run below was
taken at commit a6037aa (2026-10-14) on an Intel Core i7-14700K and
predates later solver changes; it has not been re-measured since:
wall time 234 930 ms (589 ms / instance)
p50 / p90 / p99 129 ms / 1.91 s / 3.98 s
decisions 21.69 M
conflicts 18.49 M
propagations 855.02 M
restarts 8.04 k (~1 per 2 300 conflicts)
reductions 3.86 k
peak RSS 40 MB
topdown L1
retiring 18.5 %
bad-speculation 49.3 %
frontend-bound 21.7 %
backend-bound 10.4 %
IPC 1.27
branch-miss rate 11.1 %
L1d miss rate 2.86 %
zig build bench-quick runs the same harness on smaller uf100 / uuf100
instances (~4 s) for fast iteration during development.
zig build bench-industrial profiles the crafted DIMACS families (bf, ssa,
hanoi, parity, aim) with a 30 s cap per instance, and zig build bench-satcomp profiles the SAT Competition 2025 subset from
bench/fetch_satcomp.sh with a 60 s cap.
zig build compete checks submission readiness: the bench/run.sh
sweep, gzipped input, SIGTERM handling and DRAT output. It then solves
10 uf250 instances with a 5 s limit each and takes perf stat figures on
uf100 / uuf100, set beside the SAT Competition 2025 main-track results
hard-coded in src/tools/compete.zig.
Correctness is checked by bench/run.sh, which runs the release binary
against the downloaded SATLIB / DIMACS instances and compares exit codes
with the known verdicts: 5067 / 5067 across uf20, uf50, uf100, uuf50,
uuf100, and the dimacs-{dubois, pret, bf, ii, hanoi} families, last run at
commit 62183d5 (2026-11-21).
A stricter sweep over all 5826 instances that bench/fetch.sh downloads
(60 s per instance) solved 5816 at commit a6037aa (2026-10-14); the other
10 are the par32 instances. Every SAT model was checked against the input
CNF and every UNSAT DRAT proof was accepted by drat-trim. That sweep
predates later solver changes and has not been re-run since.
bench/compare.py runs this solver side-by-side with MiniSat, CaDiCaL,
and Kissat under hard RLIMIT_CPU and RLIMIT_AS limits, cross-checks
verdicts to catch correctness bugs, and reports per-solver PAR-2 scores
plus a cactus plot.
To reproduce:
bench/build-solvers.sh # clones + builds CaDiCaL and Kissat
# into bench/solvers/
nix shell nixpkgs#minisat # MiniSat on $PATH
zig build -Doptimize=ReleaseFast # our solver
bench/compare.py --limit 10 # smoke run, this solver only
bench/compare.py --solvers sat-solver minisat cadical kissat
# full run (300s CPU / 4 GB per instance)A solver not found at its usual install paths is looked up on $PATH.
--compare-to PATH merges the rows of an earlier results CSV for solvers
not named in --solvers, so the reference solvers need not be re-run.
bench/compare.py --help lists the other options.
Methodology notes (all SAT Competition standard):
- Time limit is enforced via
setrlimit(RLIMIT_CPU)inside the forked child just beforeexecvp. CPU time, not wall time, so system load and thermal throttling don't confound the comparison. Default 300 s. - Memory limit via
setrlimit(RLIMIT_AS). Default 4 GB. - CPU time + peak RSS collected via
os.wait4rusage, not a GNU-time wrapper, so there's no extra process in the measurement path. - Verdict cross-check: if any two solvers produce different decisive
verdicts (SAT vs UNSAT) on the same instance, one of them is wrong —
flagged as a
CORRECTNESS WARNINGand the script exits non-zero. - PAR-2 scoring: solved instances contribute their CPU time, unsolved (timeout / error) instances contribute 2 × timeout. Lower is better. This is how SAT Competition ranks solvers.
- Cactus plot: sorted per-instance CPU times per solver, plotted on a log-scale y-axis. The curve that stays lower / further right wins.
Results go to bench/compare-results.csv and bench/compare-cactus.png.
The plot needs matplotlib; without it the script skips the plot.
Default run (uf200-860 + uuf200-860, 199 instances, 300 s CPU / 4 GB),
taken at commit a6037aa (2026-10-14) and not re-measured since:
solver solved timeouts errors avg (solved) PAR-2
sat-solver 199/199 0 0 0.08s 16.9s
minisat 199/199 0 0 0.09s 18.1s
kissat 199/199 0 0 0.15s 29.4s
cadical 199/199 0 0 0.18s 35.9s
MiniSat 2.2.1, CaDiCaL 3.0.1, Kissat 4.0.4. These instances take well under a second, so per-instance overhead dominates; on large industrial instances Kissat and CaDiCaL are far ahead.
- Far behind state-of-the-art solvers on industrial instances. The random 3-SAT results above don't carry over to large structured formulas.
- Some hard instances stay unsolved. The 10 par32 instances time out
at 60 s in the
a6037aasweep.b19_1from the SAT Competition 2025 set was not solved within an hour at around the same commit (2026-10-14); that predates later solver changes and has not been re-run since. - Bounded variable elimination has no memory cap. An elimination never
increases the clause count and its resolvents are at most 16 literals,
but a resolvent can be longer than the clauses it replaces, and
preprocessing may resolve up to 50 M clause pairs. In October 2026 one
pass on
pj2016_k100added about 450 M arena slots of resolvents and peaked at 14 GiB. That was before two fixes: BVE now resolves only irredundant clauses (2e6f529), and the first inprocessing pass no longer gets the preprocessing budget (f8c3789). The instance has not been re-measured since. - One solve per formula. Search is single-threaded, and there are no
assumptions or incremental clause additions between solves, so a caller
such as
sat-sudokubuilds a fresh solver for each formula.
The CDCL core lives in src/search/. Major subsystems:
propagate.zig— two-watched-literal BCP with blocker + in-place watcher list compaction, and a separate fast path for binary clauses that never touches the arena. The hot loop dominates runtime; the hot instructions are the watcher store, clause-header load, and thecmpbagainst the literal-indexed value table.analyze.zig— 1-UIP walk backward through the trail, followed by recursive minimization. Each non-asserting literal in the learned clause is checked for self-subsuming redundancy via an iterativelitRedundantwith a 64-bitabstract_levelsbitmask fast-reject.solve.zig— preprocessing, then the main loop with the Glucose restart decision: bias-corrected fast / slow LBD EMAs (α = 1/50and1/10 000), restart ratio threshold1.25, trail-length blocker at1.4 × trail_fast. Reductions, rephasing, mode switches and every inprocessing pass run at level 0 on their own conflict schedules; the return to level 0 they force is not counted as a restart. A backjump of more than 100 levels backtracks one level instead (chronological backtracking,backtrack.zig).solver.zig— theSolverstruct and its shared operations: VSIDS bump and decay, branching, rephasing and clause installation.inprocess/—reduce.zig(LBD-based reduction, arena compaction),subsume.zig,equiv.zig,bve.zig,probe.zigandvivify.zig, withcommon.zigholding level-0 clause normalisation and the propagation budget. Each emits DRAT additions before deletions so proofs stay checkable; BVE and equivalence substitution record witnesses thatmodel.zigreplays to extend a model to the eliminated variables.
Schedules, in conflicts (a schedule's first run comes after its initial interval):
- Reduction every 2000, growing by 300 each time, and only when the learned clauses outnumber a limit that starts at max(clause count, 1000) and grows by 11/10 per reduction. It deletes the worse half by LBD of the learned clauses that are neither glue nor locked.
- Rephasing every 1000; probing and equivalent-literal substitution every 10 000; vivification every 15 000; subsumption every 20 000; elimination every 40 000. Each of these intervals grows by 1.5x after a run.
- Probing tries the 1024 most active variables; vivification takes learned clauses of LBD 6 or less; elimination skips a variable whose positive and negative occurrence counts multiply to more than 10 000.
- Arena compaction runs after preprocessing and after each level-0 round once deleted clauses fill half the arena.
src/core/assignment.zig holds the trail, decision levels, and the
literal-indexed lit_values table — updated in pairs of adjacent slots so
valueOfLiteral(lit) is a single load + compare on the caller side.
src/tools/profile.zig is the zig build bench orchestrator — it spawns
the solver under perf stat and perf record and prints the report.
src/tools/report.zig parses the perf stat and sat-bench output and
renders the box-drawing tables with ANSI-colored verdicts for each metric;
compete.zig shares it.
src/
├── main.zig CLI entry point
├── root.zig the public `sat` module (used by tests/unit.zig)
├── core/ Literal / Formula, clause arena layout, assignment trail
├── io/ streaming DIMACS parser, DRAT writer
├── heuristics/ VSIDS heap, restart / rephase / mode schedules
├── search/ Solver, CDCL loop, propagate, analyze, backtrack,
│ │ model extension
│ └── inprocess/ subsume, equiv, bve, probe, vivify, reduce + compact,
│ common (shared level-0 helpers)
└── tools/ bench (batch runner), profile (perf), compete (readiness),
report (perf parsing + tables), instances (instance
listing), sudoku (Sudoku via CNF)
bench/
├── fetch.sh downloads SATLIB + DIMACS instance sets
├── fetch_satcomp.sh downloads a SAT Competition 2025 subset
├── run.sh correctness sweep with per-set timing
├── compare.py side-by-side comparison against reference solvers
├── build-solvers.sh builds CaDiCaL and Kissat for compare.py
└── README.md bench directory layout + usage
tests/
├── unit.zig unit tests
└── fixtures/ small .cnf files for round-trip tests
zig build test also runs the tests inside src/heuristics/,
src/tools/report.zig and src/tools/sudoku.zig, and the end-to-end
CLI and Sudoku cases defined in build.zig.
MIT. See LICENSE.