Proof libraries & OpenTheory

Changing a library

This guide reads a proof-DAG library as a theorem database and publishes its next version: theorems added from articles or from a proof session, and statements withdrawn. A version is never edited in place. A change is written as a new version whose parent is the one you opened, and it becomes CURRENT atomically (ST7.2).

Creating a library

var lib = Library.create(path, "classical")   # "none", "classical" or "isabelle"

Library.create publishes a library's first version over a profile. That version provides the profile's statements and has no theorem of its own; its theorems come with the changes below. create refuses with CONFLICT when the directory already holds a library.

Reading a version

var lib = Library.open(path)              # CURRENT; Library.open(path, Optional(v)) for an ancestor
for t in lib.theorems():                  # name, kind, statement identity, partition, provider
    print(t)
var found = lib.find("judgment.stmt.<sid>")   # a statement identity, an alias or a declaration name
var citing = lib.dependents(key)              # statements whose providers cite it, by record or by proof

Library.open reads the version's manifest alone, with no partition file and no proof row. A theorem's name is its alias, if the manifest has one. Otherwise it is its provider's declaration name, and failing that its canonical name judgment.stmt.<sid>. dependents reads the manifest's declaration index (section 7), which every version has; a new library's is empty. A library written before format 2.2 is not opened: Library.open refuses it with VERSION.

Theorem names

A theorem's name is a dotted long name in snake_case, such as hol_probability.martingale.martingale_convergence: dot-separated components, each matching [a-z][a-z0-9_]*, the first not judgment (valid_theorem_name). Names are aliases of statements (manifest section 4); a statement's identity does not depend on its name. The components form the library's catalogue:

lib.categories()                                  # the top-level categories, e.g. hol_probability
lib.categories(under="hol_probability")           # the categories just below it, e.g. martingale
lib.theorems(under="hol_probability.martingale")  # the theorems below a category
lib.find("hol_probability.martingale.martingale_convergence")

The last component is the theorem's own and is not a category. A category is matched by whole components: theorems(under="hol") does not list hol_probability's theorems. A theorem with no alias has its canonical name judgment.stmt.<sid>. A session theorem may be added under its own canonical name, which adds no alias; the canonical name of another statement is refused with LIBRARY.

Importing into a session

A Library is a TheoremSource: a proof session imports its theorems statement-only, from the version the library was opened at, and proves new theorems from them.

var lib = Library.open(path)
var lemma = session.import_theorem(lib, "hol_probability.martingale.martingale_convergence")

A name is taken as find takes it: a theorem name, a canonical name or a statement identity. The library declares the theorem's provider and the declarations its statement cites into the session's workspace, reading only section 2 of the partitions that hold them, each declaration's bytes checked against the identity the declaration index lists. A theorem comes in as an axiom stand-in. Its proof is not loaded or rechecked; the library's producer is then in the session's trusted base for that statement (ST9.8). The session must hold the library's profile (LIBRARY otherwise); the manifest's declaration index names what to import.

A theorem proved from imports exports with references to the library's declarations, by identity and version, so change().add publishes it back to that library or to a later version of it.

Importing from an article

An OpenTheory article file (version 6) is a source of theorems too. A file is untrusted, so Article.open checks every row of it with the converter and keeps the result in a private temporary library, removed with the Article value and on every failed open:

var art = Article.open("lemmas.art", profile="none", source="HOL Light|lemmas-1|lemmas|lemmas")
var t = session.import_theorem(art, "judgment.stmt.<sid>")

A plain article names no theorem: its theorems are found by statement identity or canonical name (art.theorems() lists them). The article's own axioms need their provenance (source); a theorem resting on one is labelled with it.

A theorem proved from an article's theorem cites the temporary library's declaration. Adding it to a change of a library is refused with MISSING_DEPENDENCY until the article is added to that library (change().add_article of the same file), which gives the same declaration identities.

Writing an article

Article.write writes session theorems as an OpenTheory article (version 6), for other provers or a later Article.open:

Article.write("lemmas.art", exports, budget)                    # theorems over the core
Article.write("more.art", exports, budget, library=path)        # theorems importing from a library

Each theorem's proof is replayed and checked, then written step by step: the sequent rules as OpenTheory's primitives of the same names, the declarations the proof cites (imported theorems, the profile's and the core's statements) as axioms, and each theorem as a thm. The same theorems give the same bytes.

The writer is not part of the trusted base. With verify=True, the default, the file is read back through the checking converter before it is written: it must prove each theorem with its statement identity, and its axioms must be exactly the statements the theorems import. A writer that dropped a step or added an assumption is refused, and no file is written.

Variables are written by name and type. The name of a variable or a type variable is written as one component of OpenTheory's namespace: a dot in it is escaped, as a double quote and a backslash are in every name, since reserved names such as ·judgment.derived.a have dots. An article variable whose own name begins with ·, which the converter stores with one more · in front, is written under its article name again. A proof that cites a polymorphic theorem, one with type variables such as a polymorphic theorem of the profile, is written too: the cited proof's theorem, then a subst that renames its type variables to the statement's.

Only statements over the core's and the profile's vocabulary are written: a statement that mentions a constant an import declares is re-declared by the read-back with another identity, and is refused by the pins. The sequent rules are written over either profile. Natural deduction is written over the classical profile: truth, hypothesis, the rules of ∧, ∨, ⇒, ∀ and ⊥, the equality rules (eq_refl, eq_sym, eq_trans, eq_apply, eq_abstract, eq_subst), export, transport and lift (ST5.1); their article forms and schemas are in the sequents page. The natural-deduction use, of_class and unconstrain, the sequent ofClass, a class, the witnesses of instances and class relations, a class predicate's definition, sorted type variables, names with a line break, row shapes with no article form, rows that need a schema over the profile none, and the Isabelle profile are refused with LIBRARY.

A pending change

change() starts a pending change over the version you opened. Nothing is written until publish:

var change = lib.change()                 # based on lib.version()
change.add_article("extra.art", "HOL Light|extra-1|extra|extra")
change.withdraw(key)                      # a statement identity or a name
var v = change.publish()                  # the new CURRENT
Call What it does
add_article(path, source) converts an OpenTheory article over the base's statements, as convert_dag --base does: what it cites from the library is a reference, and what it restates is left out (Rule L1)
add(export) adds a theorem proved in a session (TheoremExport): its proof rows are replayed and checked
replace(name, export) replaces a theorem's proof by a session theorem's: same statement, same declaration identity
withdraw(key) withdraws a theorem or an axiom of the base
publish() writes the change as the next version and makes it CURRENT
rebase() moves a pending change onto the current version after a conflict

A change adds articles or session theorems, not both. Withdrawals go with either. A change publishes once: after that, every call is refused with LIBRARY.

Adding a session theorem

A theorem proved in a proof session is exported with the closure of its proof, and the export carries no trust. The rows of the core prefix are cited by id, the profile's declarations by position, and imported library declarations by identity. add checks that the base holds every cited declaration (MISSING_DEPENDENCY otherwise). publish replays each proof row through the construction engine, which recomputes its conclusion from its rule and operands. The kernel then checks every row before anything is written, and again on every load. An export that does not replay, or a row the kernel refuses, is refused with REPLAY.

The theorem must be proved over the library's profile; otherwise publish refuses it with LIBRARY. A row that cites the core past its prefix, a local without a name, or a local fixed by two frames, is refused with REPLAY.

The theorem's name becomes an alias of its statement (section 4), so find takes it once the change is published. The name must be a theorem name (above), or the change refuses it with LIBRARY. A name that already names another statement in the version refuses the publication with CONFLICT, before anything is written. So does a name that is a provider's declaration name without an alias, since find would take the alias first. The same name for the same statement is kept once. A theorem whose statement the base already provides is left out (Rule L1), and only its alias is added. A later version keeps the aliases of the statements it still provides.

Withdrawing a statement

A statement is withdrawn only while nothing depends on it (Rule L1). withdraw refuses with LIBRARY in these cases:

  • a declaration of the version cites its provider, by its record or by its current proof (section 7, Definition L-4), unless the same change withdraws that declaration too. A declaration the same change adds counts as well, such as a type definition whose witness it is;
  • the statement is the profile's.

A section-3 reuse count can be positive for a statement that can be withdrawn, since it also counts the rows of replaced proofs.

Replacing a proof

replace(name, export) gives a theorem of the base a new proof, from a session theorem that proves the same statement. The theorem keeps its statement, its declaration identity and its name. Its old proof's rows stay in their partition but no longer count as citations, so a lemma that only the old proof used can be withdrawn by a later change.

publish refuses the replacement with LIBRARY when the export proves another statement, or when its proof cites the theorem itself or a declaration that depends on it (Definition L-4).

An unknown key is refused with MISSING_DEPENDENCY.

Publication and conflicts

publish holds the library's LOCK while it writes, and checks that the base is still CURRENT. If another writer published a version since you opened the library, the change is refused with CONFLICT. On any refusal CURRENT stays as it was; partitions already written are unreferenced files (old versions and space).

After a conflict, rebase() moves the change onto the current version. Its articles, theorems and withdrawals stay the same, and each withdrawal and each theorem's citations are checked again against the new base. Then publish again:

try:
    _ = change.publish()
except e:
    if e.kind == StoreErrorKind.CONFLICT:
        change.rebase()
        _ = change.publish()

Errors

Kind When
CONFLICT the base is no longer CURRENT; a session theorem's name names another statement or is a declaration's name; create over an existing library
LOCKED another writer holds LOCK
LIBRARY a refused withdrawal or replacement, a name that is not a theorem name, an empty change, articles mixed with session theorems, a session theorem over another profile, a second publish
MISSING_DEPENDENCY an unknown statement, or a session theorem citing a declaration the base does not hold
KERNEL an article's row refused by the checker
REPLAY a session theorem that does not replay, or one of its rows refused

A complete program

Mojo

change_library.mojo Download
"""Create a proof-DAG library, add theorems from articles, refuse a withdrawal that something depends on, and publish
a change again after a conflict."""
from std.tempfile import mkdtemp
from judgment_store import Library, StoreErrorKind

# An OpenTheory article: ⊢ p = p for a variable p : bool, by reflexivity.
comptime TYPES = String(
    "6\nversion\n",
    "\"bool\"\ntypeOp\nnil\nopType\n0\ndef\npop\n",
    "\"->\"\ntypeOp\n0\nref\n0\nref\nnil\ncons\ncons\nopType\n1\ndef\npop\n",
    "\"->\"\ntypeOp\n0\nref\n1\nref\nnil\ncons\ncons\nopType\n2\ndef\npop\n",
    "\"p\"\n0\nref\nvar\n3\ndef\npop\n3\nref\nvarTerm\n4\ndef\npop\n",
    "\"=\"\nconst\n2\nref\nconstTerm\n4\nref\nappTerm\n4\nref\nappTerm\n5\ndef\npop\n",
)
comptime REFL = String(TYPES, "4\nref\nrefl\nnil\n5\nref\nthm\n")
# ⊢ (p = p) = (p = p), from ⊢ p = p cited as an axiom: the library's theorem.
comptime TWICE = String(
    TYPES,
    "nil\n5\nref\naxiom\n6\ndef\npop\n6\nref\n6\nref\ndeductAntisym\n",
    "\"=\"\nconst\n2\nref\nconstTerm\n5\nref\nappTerm\n5\nref\nappTerm\n7\ndef\npop\nnil\n7\nref\nthm\n",
)


def article(dir: String, name: String, text: String) raises -> String:
    var path = String(dir, "/", name, ".art")
    with open(path, "w") as f:
        f.write(text)
    return path


def theorems(lib: Library) -> Int:
    var n = 0
    for t in lib.theorems():
        if t.kind == "theorem":
            n += 1
    return n


def main() raises:
    var dir = mkdtemp()
    var path = dir + "/lib"

    # A new library: its first version holds the profile's statements and nothing else.
    var lib = Library.create(path, "none")
    print("Created; theorems:", theorems(lib))

    # Each change is published as the next version, atomically.
    var change = lib.change()
    change.add_article(article(dir, "refl", REFL))
    var previous = change.publish()
    change = Library.open(path).change()
    change.add_article(article(dir, "twice", TWICE))
    _ = change.publish()
    lib = Library.open(path)
    print("After two changes; theorems:", theorems(lib), "| base is the previous version:", change.base() == previous)

    # p = p is cited by the second theorem's proof: withdrawing it is refused. Nothing cites the second theorem.
    for t in lib.theorems():
        if t.kind != "theorem":
            continue
        var withdraw = lib.change()
        try:
            withdraw.withdraw(String(t.sid))
            print("Withdrawing a theorem nothing cites: accepted")
        except e:
            print("Withdrawing a cited theorem:", e.kind)

    # Two writers open the same version. The second publishes after the first: it is refused, rebased onto the new
    # version, and published there.
    var first = Library.open(path).change()
    var second = Library.open(path).change()
    first.add_article(article(dir, "first", REFL))
    second.add_article(article(dir, "second", REFL))
    var by_first = first.publish()
    try:
        _ = second.publish()
    except e:
        print("The second writer:", e.kind)
    second.rebase()
    _ = second.publish()
    print("Published over the first writer's version:", second.base() == by_first)

Run from the repository root pixi run mojo run -I src docs/examples/store/change_library.mojo

Output

Created; theorems: 0
After two changes; theorems: 2 | base is the previous version: True
Withdrawing a theorem nothing cites: accepted
Withdrawing a cited theorem: LIBRARY
The second writer: CONFLICT
Published over the first writer's version: True

Python

change_library.py Download
"""Create a proof-DAG library, add theorems from articles, refuse a withdrawal that something depends on, and publish
a change again after a conflict."""
from pathlib import Path
from tempfile import TemporaryDirectory

from judgment import Library, StoreError

# An OpenTheory article: ⊢ p = p for a variable p : bool, by reflexivity.
TYPES = (
    "6\nversion\n"
    '"bool"\ntypeOp\nnil\nopType\n0\ndef\npop\n'
    '"->"\ntypeOp\n0\nref\n0\nref\nnil\ncons\ncons\nopType\n1\ndef\npop\n'
    '"->"\ntypeOp\n0\nref\n1\nref\nnil\ncons\ncons\nopType\n2\ndef\npop\n'
    '"p"\n0\nref\nvar\n3\ndef\npop\n3\nref\nvarTerm\n4\ndef\npop\n'
    '"="\nconst\n2\nref\nconstTerm\n4\nref\nappTerm\n4\nref\nappTerm\n5\ndef\npop\n'
)
REFL = TYPES + "4\nref\nrefl\nnil\n5\nref\nthm\n"
# ⊢ (p = p) = (p = p), from ⊢ p = p cited as an axiom: the library's theorem.
TWICE = (
    TYPES
    + "nil\n5\nref\naxiom\n6\ndef\npop\n6\nref\n6\nref\ndeductAntisym\n"
    + '"="\nconst\n2\nref\nconstTerm\n5\nref\nappTerm\n5\nref\nappTerm\n7\ndef\npop\nnil\n7\nref\nthm\n'
)


def article(directory: Path, name: str, text: str) -> str:
    path = directory / f"{name}.art"
    path.write_text(text)
    return str(path)


def theorems(lib: Library) -> int:
    return sum(1 for t in lib.theorems() if t.kind == "theorem")


def main():
    with TemporaryDirectory() as tmp:
        directory = Path(tmp)
        path = str(directory / "lib")

        # A new library: its first version holds the profile's statements and nothing else.
        lib = Library.create(path, "none")
        print("Created; theorems:", theorems(lib))

        # Each change is published as the next version, atomically.
        change = lib.change()
        change.add_article(article(directory, "refl", REFL))
        previous = change.publish()
        change = Library.open(path).change()
        change.add_article(article(directory, "twice", TWICE))
        change.publish()
        lib = Library.open(path)
        print("After two changes; theorems:", theorems(lib), "| base is the previous version:", change.base() == previous)

        # p = p is cited by the second theorem's proof: withdrawing it is refused. Nothing cites the second theorem.
        for t in lib.theorems():
            if t.kind != "theorem":
                continue
            withdraw = lib.change()
            try:
                withdraw.withdraw(str(t.sid))
                print("Withdrawing a theorem nothing cites: accepted")
            except StoreError as e:
                print("Withdrawing a cited theorem:", e.kind)

        # Two writers open the same version. The second publishes after the first: it is refused, rebased onto the new
        # version, and published there.
        first = Library.open(path).change()
        second = Library.open(path).change()
        first.add_article(article(directory, "first", REFL))
        second.add_article(article(directory, "second", REFL))
        by_first = first.publish()
        try:
            second.publish()
        except StoreError as e:
            print("The second writer:", e.kind)
        second.rebase()
        second.publish()
        print("Published over the first writer's version:", second.base() == by_first)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/store pixi run python docs/examples/python/store/change_library.py

Output

Created; theorems: 0
After two changes; theorems: 2 | base is the previous version: True
Withdrawing a theorem nothing cites: accepted
Withdrawing a cited theorem: LIBRARY
The second writer: CONFLICT
Published over the first writer's version: True

The API reference renders Library and LibraryChange.

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