Guides

User propagators and callbacks

z3_mojo provides safe Mojo 1.2 trait wrappers for Z3's three solver and optimizer callback APIs:

  1. User Propagator (UserPropagator): plug a custom theory solver, domain propagator, decision heuristic, or quantifier-binding filter directly into Z3's CDCL(T) loop (Z3_solver_propagate_*).
  2. Clause listener (ClauseHandler / OnClause): observe asserted, inferred, and deleted CDCL(T) clauses (Z3_solver_register_on_clause).
  3. Optimizer model listener (ModelHandler / Optimize.set_on_model): receive each improving model as Optimize converges (Z3_optimize_register_model_eh).

Safety and lifetime guarantees

  • Automatic cleanup: callback state is stored in an internal registry owned by the Solver or Optimize handle. When Mojo drops the solver or optimizer, Z3_solver_dec_ref / Z3_optimize_dec_ref runs first and the heap-pinned callback state is destroyed afterwards.
  • Exception safety across C: every abi("C") trampoline catches Mojo Errors inside the callback instead of unwinding across C. The captured error is re-raised immediately when check() or check_assumptions() returns.
  • Pinned callback ASTs: ASTs delivered to callbacks are retained via Z3_inc_ref so they remain valid if your handler stores them across calls or inspects them after check().
  • Foreign sub-solver contexts: if Z3 invokes fresh_eh internally, the foreign Z3_context is wrapped with owns_ctx=False so Mojo never calls Z3_del_context on Z3-owned sub-contexts.

Writing a UserPropagator

Implement the UserPropagator trait on a Movable struct, wrap it in an ArcPointer, attach it with Solver.set_propagator, and enable only the hooks you need (fixed, final, eq, diseq, created, decide, on_binding). Register expressions to watch with s.propagate_register(expr) (or cb.add(expr) inside a callback).

from std.memory import ArcPointer
from z3_mojo import (
    Ast, BoolVar, Context, Or, SimpleSolver, SolverCallback, UserPropagator, unsat
)

struct ForbidBothTrue(UserPropagator):
    var fixed_vars: List[Ast]
    var fixed_vals: List[Bool]
    var limits: List[Int]

    def __init__(out self):
        self.fixed_vars = List[Ast]()
        self.fixed_vals = List[Bool]()
        self.limits = List[Int]()

    def push(mut self) raises:
        self.limits.append(len(self.fixed_vars))

    def pop(mut self, num_scopes: Int) raises:
        var idx = len(self.limits) - num_scopes
        if idx < 0:
            idx = 0
        var n = self.limits[idx]
        while len(self.limits) > idx:
            _ = self.limits.pop()
        while len(self.fixed_vars) > n:
            _ = self.fixed_vars.pop()
            _ = self.fixed_vals.pop()

    def fixed(mut self, cb: SolverCallback, term: Ast, value: Ast) raises:
        self.fixed_vars.append(term)
        self.fixed_vals.append(value.is_true())
        var trues = List[Ast]()
        for i in range(len(self.fixed_vars)):
            if self.fixed_vals[i]:
                trues.append(self.fixed_vars[i])
        if len(trues) >= 2:
            _ = cb.conflict(trues)

Inside any propagator callback, cb: SolverCallback provides:

  • cb.propagate(conseq, deps) and cb.propagate(conseq, deps, eq_lhs, eq_rhs): deduce a consequence justified by fixed terms and/or equalities.
  • cb.conflict(deps) and cb.conflict(deps, eq_lhs, eq_rhs): assert a theory conflict (propagate(False, ...)).
  • cb.add(expr): dynamically register a Boolean or BitVector term during search.
  • cb.next_split(term, idx=0, phase=Lbool.UNDEF): guide the next SAT decision (commonly used inside decide).
  • cb.ctx(): access the active Context.

To watch dynamically created function applications, declare the function with PropagateFunction(name, domain..., range_) and enable created=True.

Clause callbacks (ClauseHandler / OnClause)

Implement ClauseHandler and attach it with OnClause(solver, handler) or solver.register_on_clause(handler) (alias solver.on_clause(handler)):

from std.memory import ArcPointer
from z3_mojo import Ast, ClauseHandler, OnClause, SimpleSolver

struct ClauseCounter(ClauseHandler):
    var count: Int

    def __init__(out self):
        self.count = 0

    def on_clause(
        mut self,
        proof_hint: Optional[Ast],
        deps: List[Int],
        literals: List[Ast],
    ) raises:
        self.count += 1

Optimizer model callbacks (ModelHandler / Optimize.set_on_model)

Implement ModelHandler and attach it with opt.set_on_model(handler). The model: Model argument is borrowed for the duration of the callback, so extract any values you want to keep (model.eval(...), model.get_integer(...), model.get_rational(...)) inside on_model:

from std.memory import ArcPointer
from apn_mojo import Integer
from z3_mojo import Ast, Model, ModelHandler, Optimize

struct ProgressTracker(ModelHandler):
    var objective: Ast
    var values: List[Integer]

    def __init__(out self, objective: Ast):
        self.objective = objective
        self.values = List[Integer]()

    def on_model(mut self, model: Model) raises:
        var ev = model.eval(self.objective, model_completion=True)
        if ev:
            var iv = ev.value().as_integer()
            if iv:
                self.values.append(iv.value())

See the complete runnable example in docs/examples/callbacks_and_propagator.mojo and the trait reference in Pythonic API Reference.

z3_mojo v5.3.3.0 for Mojo 1.2 and Z3 5.3.3 · Apache License 2.0 with LLVM Exceptions · Source on GitHub