Optional packages

judgment_search reference

The public API of the optional concurrent proof-search and lemma-checking package: every name its __init__.mojo exports, rendered from the sources' docstrings. The contract is on the concurrent proof search page. Build the package with pixi run build-search.

Example

first.mojo Download
"""Run three candidate programs on forks of one goal and commit the lowest-index success."""

from fp.effects.async_runtime import IORuntimeConfig, Profile
from judgment_shell import ExprData, Session, TacticData, arrow, exists
from judgment_search import SearchLimits, first


def main() raises:
    var s = Session()
    var T = s.declare_type("T")
    var R = s.symbol("R", arrow(T, s.prop_type()))
    var proof = s.theorem("witnessed")
    var a = proof.var("a", T)
    _ = proof.given("ra", R(a))
    var y = proof.bound_var("y", T)
    proof.goal(exists(y, R(y)))

    # Candidates in priority order: the first does not match, the last two solve.
    var witness = TacticData.witness(ExprData.name("a"))
    var candidates: List[TacticData] = [TacticData.split(), witness.then(TacticData.exact("ra")), witness.then(TacticData.assumption())]

    # Each runs in its own fork with 1,000 units; two run at once. The lowest
    # index that succeeds is selected, whatever finishes first.
    var config = IORuntimeConfig()
    config.profile = Profile.current_thread()
    var result = first(proof, candidates, 1000, SearchLimits(workers=2), config)
    print("selected:", result.index(), result.status(), result.evidence())
    print("outcomes:", result.statuses()[0], result.statuses()[1])
    print(proof.finish())

Run from the repository root pixi run mojo run -I src docs/examples/search/first.mojo

Output

selected: 1 solved replay
outcomes: no_match solved
⊢ ∀a:T. R(a) → (∃y:T. R(y))

first

def first(mut proof: _DagProof, candidates: List[TacticData], work_each: UInt64, limits: SearchLimits = SearchLimits(), config: IORuntimeConfig = IORuntimeConfig()) raises LibError -> SearchResult

Run candidate programs on the selected goal, each in its own fork, and commit the lowest-index success.

prepare_first, then the program of first_io on a runtime with config, then commit_first. A candidate succeeds with solved, progress or no_change, and fails with no_match or by exhausting its allowance; an error stops the search with that error, in index order. Every worker count and profile gives the same result; _dag_first.dag_first_sequential is the sequential reference without forks.

Arguments.

  • proof: The draft; its selected goal is searched.
  • candidates: The programs, in priority order.
  • work_each: Each candidate's allowance.
  • limits: Workers, capacities, ceiling and deadline.
  • config: The runtime's configuration, including its profile.

Returns. The committed result.

Raises.

  • LibError: As prepare_first and commit_first; LIMIT, committing nothing, if the host cancels the search program.

Defined in src/judgment_search/_dag_first_io.mojo.

SearchLimits

struct SearchLimits(ImplicitlyCopyable, Movable)
Field Type Description
workers Int Candidates run at once, 1 to MAX_WORKERS (32); 1 is the sequential reference.
candidates Int The most candidates accepted, at most 4,096.
work UInt64 The aggregate ceiling on the candidates' allowances and the replay.
deadline_ns Optional[Int] A wall-clock bound on the whole search, in nanoseconds; it never decides the winner.

The worker count, capacities, aggregate ceiling, and deadline of one search.

Defined in src/judgment_search/_search_common.mojo.

SearchLimits.__init__

def __init__(out self, workers: Int = 1, candidates: Int = 1024, work: UInt64 = UInt64.MAX, deadline_ns: Optional[Int] = None)

Set the limits.

Arguments.

  • workers: Candidates run at once, 1 to MAX_WORKERS (32).
  • candidates: The candidate capacity, at most 4,096.
  • work: The aggregate ceiling, below the draft's own allowance.
  • deadline_ns: An optional bound on the whole search's wall-clock time, at most 10¹⁸ nanoseconds.

SearchResult

struct SearchResult(Movable)

The committed outcome of a search: the selected candidate and its evidence.

Defined in src/judgment_search/_search_common.mojo.

SearchResult.__init__

def __init__(out self, index: Int, var status: String, var goals: List[List[String]], work: UInt64, var program: Optional[TacticData], evidence: SearchEvidence, var statuses: List[String])

Internal constructor; produced by commit_first.

Arguments.

  • index: The selected index, or -1.
  • status: The selected candidate's status, or the search's failure.
  • goals: The goals the committed program leaves active.
  • work: The work charged to the draft's session.
  • program: The selected program.
  • evidence: How the result was committed.
  • statuses: The outcomes up to the selected index.

SearchResult.index

def index(self) -> Int

Read the selected candidate's input index.

Returns. The lowest index whose outcome is a success, or -1 when none is.

SearchResult.status

def status(self) -> String

Read the outcome.

Returns. The selected candidate's status (solved, progress, or no_change); otherwise no_match, or resource_exhausted when every candidate exhausted its allowance or the deadline passed.

SearchResult.goals

def goals(self) -> List[List[String]]

Read the paths of the goals the committed program leaves active.

Returns. As TacticReport.goals of the replay; empty when nothing was committed.

SearchResult.work

def work(self) -> UInt64

Read the work charged to the draft's session after the forks were made.

Returns. The forks' spent work for every index up to the decided one (each allowance in full after the deadline), plus the replay.

SearchResult.program

def program(self) -> Optional[TacticData]

Read the selected program.

Returns. The candidate's program as given, or None. Choice points are not resolved: an or_else under then may take different branches on different subgoals, which these data forms cannot fix.

SearchResult.evidence

def evidence(self) -> SearchEvidence

Read how the result reached the draft.

Returns. ADOPTION when a solved draft was completed with the fork's theorem, REPLAY when the program ran again in the draft, otherwise NONE.

SearchResult.statuses

def statuses(self) -> List[String]

Read the outcomes of the candidates up to the selected index, in order.

Returns. As SearchOutcome.statuses; the same for every worker count.

SearchEvidence

struct SearchEvidence(ImplicitlyCopyable, Movable, Equatable, Writable)
Field Type Description
code UInt8 The form's number.

How a selected candidate's result reaches the parent draft.

The forms are closed and numbered; a new form gets a new number. REPLAY runs the selected program again in the parent, from the same snapshot, where every step is a kernel-checked rule; the fork's report must equal the parent's or nothing is committed. ADOPTION completes the draft with the closed theorem the fork checked, without rerunning the program; lemma batches use it when transferring checked worker proofs. Candidate tactic search continues to report REPLAY.

Defined in src/judgment_search/_search_common.mojo.

SearchEvidence.NONE

comptime NONE = SearchEvidence(0)

Nothing was committed.

SearchEvidence.REPLAY

comptime REPLAY = SearchEvidence(1)

The selected program was replayed in the parent.

SearchEvidence.ADOPTION

comptime ADOPTION = SearchEvidence(2)

The parent adopted the theorem the fork checked.

SearchEvidence.__init__

def __init__(out self, code: UInt8)

Make a form from its number.

Arguments.

  • code: The number.

SearchEvidence.write_to

def write_to(self, mut writer: Some[Writer])

Write the form's name.

Arguments.

  • writer: The destination.

The three steps

prepare_first

def prepare_first(proof: _DagProof, candidates: List[TacticData], work_each: UInt64, limits: SearchLimits = SearchLimits()) raises LibError -> SearchPlan

Check a search's ceilings and fork the draft once per candidate, in input order, as prepare_first.

Each fork gets work_each as its own allowance, which pays for opening it (its engine adopts the session's declarations, one unit each), selecting the goal, compiling the program and the attempt: on a large session it must cover the opening, or the fork is refused (LIMIT). The sum of the allowances plus one more for the replay must not exceed limits.work, and with the cost of copying the draft into every fork (fork_cost, charged by fork) it must not exceed the draft's remaining allowance; both are checked before the first fork. A deadline of zero or less passes before any fork.

Arguments.

  • proof: The draft; its selected goal is searched.
  • candidates: The programs, in priority order.
  • work_each: Each candidate's allowance.
  • limits: Workers, capacities, ceiling and deadline.

Returns. The plan.

Raises.

  • LibError: SHAPE for a worker count outside 1 to 32, or a goal that is not outstanding; LIMIT for too many candidates, a deadline above 10¹⁸ nanoseconds, or a ceiling the allowances exceed; as _DagProof.fork. The draft is then unchanged, apart from the forks already made and their copies' charge.

Defined in src/judgment_search/_dag_first_io.mojo.

SearchPlan

struct SearchPlan(Movable)

A prepared search over the session: one fork per candidate, made in input order, and what commit needs.

Defined in src/judgment_search/_dag_first_io.mojo.

SearchPlan.__init__

def __init__(out self, var units: List[_DagUnit], var stops: List[StopSignal], var programs: List[TacticData], var path: List[String], revision: UInt64, allowance: UInt64, limits: SearchLimits, expired: Bool)

Internal constructor; use prepare_first.

Arguments.

  • units: The forks, in input order.
  • stops: Their stop signals.
  • programs: The candidate programs.
  • path: The goal's path.
  • revision: The goal's revision token.
  • allowance: Each candidate's allowance.
  • limits: The search's limits.
  • expired: Whether the deadline had passed before any fork.

SearchPlan.count

def count(self) -> Int

The number of candidates.

first_io

def first_io(var plan: SearchPlan) -> IO[SearchOutcome, Never]

Build the program that runs a prepared search and selects, committing nothing, as first_io.

Arguments.

  • plan: The prepared search, consumed.

Returns. The program; it never fails, and it produces the decision.

Defined in src/judgment_search/_dag_first_io.mojo.

SearchOutcome

struct SearchOutcome(Movable)

What the search program decided, as plain data, before anything is committed.

Defined in src/judgment_search/_search_common.mojo.

SearchOutcome.__init__

def __init__(out self, var selection: _DagSelection, var programs: List[TacticData], var path: List[String], revision: UInt64, allowance: UInt64)

Internal constructor; produced by the program of first_io.

Arguments.

  • selection: The coordinator's decision.
  • programs: The candidate programs.
  • path: The goal's path.
  • revision: The goal's revision token.
  • allowance: Each candidate's allowance.

SearchOutcome.index

def index(self) -> Int

Read the decided index.

Returns. The selected or failing candidate's index; -1 when every candidate failed or the deadline passed.

SearchOutcome.statuses

def statuses(self) -> List[String]

Read the outcomes of the candidates up to the decided index, in order.

Returns. Each candidate's status, or "error" for one that raised; every candidate when all failed; empty after the deadline.

commit_first

def commit_first(mut proof: _DagProof, var outcome: SearchOutcome) raises LibError -> SearchResult

Charge the draft for the decided search and commit the selected candidate by replaying it, as commit_first.

The draft's session is charged the work every fork up to the decided index spent, or every allowance in full after the deadline. The selected candidate is replayed in the draft through by(candidate) on the same goal revision; its report must equal the fork's, or the draft is restored and nothing is committed. A search without a selection commits nothing.

Arguments.

  • proof: The draft the plan was made from, unchanged since.
  • outcome: The decision, consumed.

Returns. The selected candidate, its status, and its evidence (REPLAY, or NONE).

Raises.

  • LibError: The error of the lowest candidate that raised one, prefixed with its index; LIMIT when the allowance cannot pay; SHAPE when the goal changed since the plan or the replay's report differs from the fork's. The draft is then unchanged.

Defined in src/judgment_search/_dag_first_io.mojo.

Checking lemmas

lemmas.mojo Download
"""Check three lemmas in forks of one session at once and register them in order."""

from fp.effects.async_runtime import IORuntimeConfig, Profile
from judgment_shell import Expr, Fact, LibError, Proof, Session, TacticData, implies
from judgment_search import LemmaJob, check_lemmas


def st_identity(s: Session) raises LibError -> Expr:
    var P = s.import_symbol("P")
    return implies(P, P)


def st_constant(s: Session) raises LibError -> Expr:
    var P = s.import_symbol("P")
    var Q = s.import_symbol("Q")
    return implies(P, implies(Q, P))


def st_weakened(s: Session) raises LibError -> Expr:
    var P = s.import_symbol("P")
    var Q = s.import_symbol("Q")
    return implies(Q, implies(P, P))


def identity(mut proof: Proof, uses: List[Fact]) raises LibError:
    _ = proof.by(proof.compile(TacticData.intro("p").then(TacticData.exact("p"))))


def constant(mut proof: Proof, uses: List[Fact]) raises LibError:
    _ = proof.by(proof.compile(TacticData.intro("p").then(TacticData.intro("q")).then(TacticData.exact("p"))))


def weakened(mut proof: Proof, uses: List[Fact]) raises LibError:
    # The identity lemma is a declared dependency: it arrives as uses[0].
    _ = proof.intro("q")
    proof.exact(uses[0])


def main() raises:
    var s = Session()
    _ = s.prop("P")
    _ = s.prop("Q")
    var jobs: List[LemmaJob] = [
        LemmaJob("identity", st_identity, identity, 2000),
        LemmaJob("constant", st_constant, constant, 2000),
        LemmaJob("weakened", st_weakened, weakened, 2000, ["identity"]),
    ]
    var config = IORuntimeConfig()
    config.profile = Profile.current_thread()
    var report = check_lemmas(s, jobs, 2, config)
    var evidence = report.evidence()
    var facts = report.facts()
    for i in range(len(facts)):
        print(jobs[i].name, evidence[i], facts[i])
    print("registered:", s.fact("weakened"))

Run from the repository root pixi run mojo run -I src docs/examples/search/lemmas.mojo

Output

identity replay ⊢ P → P
constant replay ⊢ P → Q → P
weakened replay ⊢ Q → P → P
registered: ⊢ Q → P → P

check_lemmas

def check_lemmas(d: Session, jobs: List[LemmaJob], workers: Int = 1, config: IORuntimeConfig = IORuntimeConfig()) raises LibError -> LemmaReport

Check a dependency-ordered batch once, then adopt its checked proof DAG.

Arguments.

  • d: Parent session; callbacks see isolated forks.
  • jobs: Ordered lemma jobs over existing vocabulary.
  • workers: Concurrent proof workers, 1 to 32.
  • config: Runtime used to execute the owned batch coordinator.

Returns. The registered facts and adoption evidence.

Raises.

  • LibError: As preparation and commit; cancellation registers nothing.

Defined in src/judgment_search/_dag_lemmas_io.mojo.

LemmaJob

struct LemmaJob(Copyable, Movable)
Field Type Description
name String The name it is registered under; new to the session and unique among the jobs.
statement LemmaStatement Its closed statement.
prove LemmaProof Its proof.
work UInt64 Its private fork allowance, opening included; checked dependencies are reused. The sequential reference checks it for overflow only.
uses List[String] The names of earlier jobs whose lemmas the proof uses, in the order of its facts.

One lemma to check: its name, statement, proof, allowance and dependencies.

Defined in src/judgment_search/_dag_lemmas.mojo.

LemmaJob.__init__

def __init__(out self, name: String, statement: LemmaStatement, prove: LemmaProof, work: UInt64, uses: List[String] = List[String]())

Describe a job.

Arguments.

  • name: The lemma's name.
  • statement: Its statement.
  • prove: Its proof.
  • work: Its allowance.
  • uses: Earlier jobs it depends on.

LemmaProof

comptime LemmaProof = def(mut Proof, List[Fact]) thin raises LibError -> None

A job's proof: given the draft, its goal stated, and the facts of the declared dependencies, in order.

Defined in src/judgment_search/_dag_lemmas.mojo.

LemmaReport

struct LemmaReport(Movable)

The registered lemmas, in job order, with how each was accepted.

Defined in src/judgment_search/_dag_lemmas.mojo.

LemmaReport.__init__

def __init__(out self, var facts: List[Fact], var evidence: List[SearchEvidence])

Internal constructor; produced by dag_check_lemmas.

Arguments.

  • facts: The registered lemmas.
  • evidence: How each was accepted.

LemmaReport.facts

def facts(self) -> List[Fact]

One fact per job, in job order, each also registered under its name.

LemmaReport.evidence

def evidence(self) -> List[SearchEvidence]

How each lemma was accepted: concurrent ADOPTION or direct REPLAY.

prepare_lemmas

def prepare_lemmas(d: Session, jobs: List[LemmaJob], workers: Int = 1) raises LibError -> LemmaPlan

Validate jobs and create the isolated staging fork; callbacks have not run.

Statements use vocabulary already declared on the parent. Callbacks may construct terms and proof steps, but must not add theory declarations or leave transactions open. Each dependency is an earlier job. The caller leaves the parent idle until execution has joined and commit has finished.

Arguments.

  • d: The parent session.
  • jobs: Ordered names, statements, proofs, allowances and dependencies.
  • workers: Concurrent proof workers, 1 to 32.

Returns. An owned plan.

Raises.

  • LibError: Invalid jobs or workers, taken names, or insufficient work.

Defined in src/judgment_search/_dag_lemmas_io.mojo.

LemmaPlan

struct LemmaPlan(Movable, ThreadTransferable)

An isolated staging fork and validated jobs ready for bounded execution.

Defined in src/judgment_search/_dag_lemmas_io.mojo.

LemmaPlan.__init__

def __init__(out self, var staging: ForkUnit, var jobs: List[LemmaJob], workers: Int, allowance: UInt64)

Internal; use prepare_lemmas.

Arguments.

  • staging: Batch's isolated fork.
  • jobs: Jobs in declaration order.
  • workers: Concurrent jobs.
  • allowance: Staging fork's original allowance.

LemmaPlan.count

def count(self) -> Int

Count the prepared jobs.

Returns. The number of jobs.

lemmas_io

def lemmas_io(var plan: LemmaPlan) -> IO[LemmaOutcomes, Never]

Build a deferred, joined batch execution without changing the parent.

Arguments.

  • plan: Prepared jobs, consumed.

Returns. The IO; failures are values in its ordered batch result.

Defined in src/judgment_search/_dag_lemmas_io.mojo.

LemmaOutcomes

struct LemmaOutcomes(Movable, ThreadTransferable)

Joined batch result before the staging fork is merged into the parent.

Defined in src/judgment_search/_dag_lemmas_io.mojo.

LemmaOutcomes.__init__

def __init__(out self, var staging: ForkUnit, var names: List[String], var error: Optional[LibError], failed: Int, spent: UInt64)

Internal; produced by lemmas_io.

Arguments.

  • staging: Joined staging fork.
  • names: Original ordered job names.
  • error: First refusal, if any.
  • failed: Refused job's index, or -1.
  • spent: Work consumed, including worker and fork costs.

LemmaOutcomes.failed

def failed(self) -> Int

Identify the first failing job.

Returns. Its index, or -1 after success.

commit_lemmas

def commit_lemmas(d: Session, jobs: List[LemmaJob], var outcomes: LemmaOutcomes) raises LibError -> LemmaReport

Merge the successful staging fork once; never rerun author callbacks.

Arguments.

  • d: Original parent, idle since preparation.
  • jobs: Same ordered jobs.
  • outcomes: Joined execution result, consumed.

Returns. Facts in job order, with ADOPTION evidence.

Raises.

  • LibError: The first failed job, mismatched names or a refused merge. Worker work is charged on failure as well as success.

Defined in src/judgment_search/_dag_lemmas_io.mojo.

Capacities

MAX_WORKERS

comptime MAX_WORKERS = 32

The most candidates or jobs the session's search runs at once: each worker may hold two of the bank's 128 reader slots, so 32 leaves room for the parent and another search.

Defined in src/judgment_search/_search_common.mojo.

MAX_CANDIDATES

comptime MAX_CANDIDATES = 4096

The most candidates one search accepts.

Defined in src/judgment_search/_search_common.mojo.

MAX_JOBS

comptime MAX_JOBS = 4096

The most jobs one check accepts.

Defined in src/judgment_search/_dag_lemmas.mojo.

Additional session and checked exports

LemmaStatement

comptime LemmaStatement = def(Session) thin raises LibError -> Expr

A job's closed statement, built in the session.

Defined in src/judgment_search/_dag_lemmas.mojo.

judgment v1.0.0 for Mojo 1.2 · Apache License 2.0 with LLVM Exceptions · Source on GitHub