Get started

Ownership, lifetimes, and errors

Lifetimes

Every object created inside a Context holds an ArcPointer[_ContextOwner]. Because of that, Z3_del_context only runs after every Solver, Model, Ast, Optimize, Tactic, and RcfNum belonging to that context has been destroyed. A function can create a local Context, build a Solver, and return the Solver safely:

def make_solver() raises -> Solver:
    var ctx = Context()
    var s = Solver.for_logic(ctx, "QF_NRA")
    var x = ctx.mk_real_const("x")
    s.assert_formula(ctx.mk_lt(ctx.mk_mul(x, x), ctx.mk_real(0)))
    return s^  # safe: `s` keeps the context alive

Z3's 29 C handle types fall into four lifetime groups (recorded in api/z3-api.json):

Group Mojo traits Handles How they are freed
Context-managed Copyable, ImplicitlyCopyable, Movable Ast, App, Sort, FuncDecl, Pattern, Symbol Hash-consed and owned by the Context (Z3_mk_context), freed together when the context drops.
Ref-counted RAII Movable Solver, Model, Optimize, Fixedpoint, Tactic, Goal, ApplyResult, Probe, Simplifier, Params, ParamDescrs, Stats, AstVector, AstMap, FuncInterp, FuncEntry, ParserContext Z3_<name>_inc_ref in __init__, Z3_<name>_dec_ref in __deinit__.
Explicit-delete RAII Movable Config, Context, Constructor, ConstructorList, RcfNum Z3_del_* or Z3_rcf_del in __deinit__.
Borrowed Copyable, ImplicitlyCopyable, Movable SolverCallback Valid only during the Z3 callback that receives it.

Moving objects across contexts and threads

A Z3 Context is not thread-safe. If you solve in parallel, give each thread its own Context.

To copy terms, goals, models, solvers, optimizers, or AST vectors from one context to another, use Z3's translate methods:

var ctx1 = Context()
var ctx2 = Context()
var x1 = ctx1.mk_real_const("x")
var f2 = ctx1.translate(ctx1.mk_gt(x1, ctx1.mk_real(0)), ctx2)

Every translate method (Context.translate, Goal.translate, Model.translate, Solver.translate, Optimize.translate, and AstVector.translate) attaches the returned object to the destination context's owner, so ctx1 can be dropped right after the call.

Error handling

Left to its default settings, Z3's C API calls exit() when you pass bad arguments or trigger a sort error. Context.__init__ and Context.from_config immediately call Z3_set_error_handler(ctx, NULL) so Z3 records the error code on the context instead of exiting.

After every context call (other than destructors and the error-query functions themselves), the raw layer checks Z3_get_error_code(ctx) and raises a Mojo Error:

var ctx = Context()
try:
    _ = Tactic.create(ctx, "not-a-valid-tactic")
except e:
    print(e)  # z3: unknown tactic not-a-valid-tactic

Errors reported by Z3 itself start with "z3: ". Checks performed by the binding layer (such as embedded NUL bytes in a string argument or mismatched list lengths) start with "z3_mojo: ".

Callback lifetimes and error propagation

UserPropagator, ClauseHandler (OnClause), and ModelHandler (Optimize.set_on_model) store their heap-pinned state in an internal _CallbackRegistry owned by the Solver or Optimize handle:

  • When the Solver or Optimize handle is destroyed, Z3_solver_dec_ref / Z3_optimize_dec_ref runs before the callback registry frees its state, so Z3 never dereferences a destroyed handler.
  • Every abi("C") trampoline catches Mojo Errors instead of unwinding across C and stores the error on the registry. Solver.check(), Solver.check_assumptions(), and Optimize.check() re-raise any captured callback error immediately after the Z3 call returns.
  • Foreign Z3_context handles created internally by Z3 during fresh_eh are wrapped with owns_ctx=False so Mojo never calls Z3_del_context on them.

Manual ownership in z3_mojo.c

The low-level C API (from z3_mojo.c import c_api, ...) does not wrap handles in RAII destructors. You are responsible for calling Z3_set_error_handler(ctx, null[NoneType]()), pairing *_inc_ref/*_dec_ref (and Z3_inc_ref / Z3_dec_ref under Z3_mk_context_rc), and calling Z3_del_context(ctx) last. See the Low-level C API guide.

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