Part 5 — Concurrency, libraries & integration

5.12 Manage memory limits, spill storage, and judgment_mathlib

Tutorial sequence · Previous: 5.11 Check a promised conclusion

Goal: cap a session's workspace memory and recover from LIMIT, spill verified DAG pages to disk, and open or recheck the external Isabelle/HOL judgment_mathlib library.

Workspace memory caps and out-of-core spill

Control Scope Use
set_memory_limit(bytes) / memory_used() / memory_limit() Caps live workspace chunk storage. Raising the cap allows retrying a refused operation. Bounding speculative search, untrusted inputs, or per-request work.
set_spill_directory(dir) + seal() + Session.open(snapshot) + spill() Evicts complete, verified DAG chunks and index runs in the shared snapshot bank to a private spill file while keeping them readable. Handling verified libraries or derivations exceeding available RAM.

Mojo

memory_and_spill.mojo Download
"""Cap workspace memory, recover after a limit refusal, and spill a sealed bank to disk."""
from std.os import listdir
from std.tempfile import mkdtemp
from std.testing import assert_equal, assert_true
from judgment import Session


def _long_name(i: Int) -> String:
    var name = String("sym_", i, "_")
    for _ in range(16384):
        name += "x"
    return name^


def main() raises:
    var s = Session(work=100_000_000)
    var t = s.declare_type("T")
    var c = s.symbol("c", t)

    # Cap workspace storage at its current usage; an allocation that needs a new chunk raises LIMIT.
    var used = s.memory_used()
    assert_true(used > 0)
    s.set_memory_limit(used)
    assert_equal(s.memory_limit(), used)

    var blocked = String()
    for i in range(16):
        var name = _long_name(i)
        try:
            _ = s.symbol(name, t)
        except e:
            assert_equal(String(e.kind), "LIMIT")
            blocked = name
            break
    assert_true(Bool(blocked))
    assert_equal(c.format(), "c")
    print("Memory cap enforced: LIMIT; earlier handle still valid")

    # Raise the cap and retry the refused declaration.
    s.set_memory_limit(s.memory_used() + (64 << 20))
    assert_equal(s.symbol(blocked, t).format(), blocked)
    print("After raising cap: declaration succeeded")

    # Configure spill storage, seal verified rows, reopen, and spill eligible pages to disk.
    var spill_dir = mkdtemp()
    s.set_spill_directory(spill_dir)
    assert_equal(len(listdir(spill_dir)), 0)
    for i in range(16, 96):
        _ = s.symbol(_long_name(i), t)
    var snapshot = s.seal()
    var reopened = Session.open(snapshot, work=100_000_000)
    var spilled = reopened.spill()
    assert_true(spilled > 0)
    assert_equal(len(listdir(spill_dir)), 1)
    assert_equal(reopened.import_symbol("c").format(), "c")
    assert_equal(reopened.import_symbol(_long_name(20)).format(), _long_name(20))
    print("Spilled verified pages to disk and read symbol back: True")

Run from the repository root pixi run core-run docs/examples/library/memory_and_spill.mojo

Output

Memory cap enforced: LIMIT; earlier handle still valid
After raising cap: declaration succeeded
Spilled verified pages to disk and read symbol back: True

Python

memory_and_spill.py Download
"""Cap workspace memory, recover after a limit refusal, and spill a sealed bank to disk."""
import os
from tempfile import TemporaryDirectory

from judgment import JudgmentError, LibErrorKind, Session


def _long_name(i: int) -> str:
    return f"sym_{i}_" + ("x" * 16384)


def main():
    s = Session(work=100_000_000)
    t = s.declare_type("T")
    c = s.symbol("c", t)

    # Cap workspace storage at its current usage; an allocation that needs a new chunk raises LIMIT.
    used = s.memory_used()
    assert used > 0
    s.set_memory_limit(used)
    assert s.memory_limit() == used

    blocked = ""
    for i in range(16):
        name = _long_name(i)
        try:
            s.symbol(name, t)
        except JudgmentError as e:
            assert e.kind == LibErrorKind.LIMIT
            blocked = name
            break
    assert blocked
    assert c.format() == "c"
    print("Memory cap enforced: LIMIT; earlier handle still valid")

    # Raise the cap and retry the refused declaration.
    s.set_memory_limit(s.memory_used() + (64 << 20))
    assert s.symbol(blocked, t).format() == blocked
    print("After raising cap: declaration succeeded")

    # Configure spill storage, seal verified rows, reopen, and spill eligible pages to disk.
    with TemporaryDirectory() as spill_dir:
        s.set_spill_directory(spill_dir)
        assert len(os.listdir(spill_dir)) == 0
        for i in range(16, 96):
            s.symbol(_long_name(i), t)
        snapshot = s.seal()
        reopened = Session.open(snapshot, work=100_000_000)
        spilled = reopened.spill()
        assert spilled > 0
        assert len(os.listdir(spill_dir)) == 1
        assert reopened.import_symbol("c").format() == "c"
        assert reopened.import_symbol(_long_name(20)).format() == _long_name(20)
        print("Spilled verified pages to disk and read symbol back: True")
        del reopened, snapshot, s


if __name__ == "__main__":
    main()

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

Output

Memory cap enforced: LIMIT; earlier handle still valid
After raising cap: declaration succeeded
Spilled verified pages to disk and read symbol back: True

Operational semantics:

  • Atomic refusal: hitting set_memory_limit raises LIMIT without invalidating prior handles (such as c); raising the cap allows retrying the same declaration.
  • Deferred spill file: set_spill_directory(dir) creates no file until spill() evicts verified chunks. The file is private and removed when the last bank owner is released.
  • Workspace vs. process RSS: set_memory_limit accounts for workspace chunk storage, excluding the shared snapshot bank's 64 MiB spill cache and allocator overhead. Pass UInt64.MAX (Mojo) or 2**64 - 1 (Python) to uncap. Configure limits and spill directories outside open transactions and with no active child forks.

Opening and rechecking judgment_mathlib

Scalar's HOL model and analytic theorems build on judgment_mathlib, a 591 MiB format-2.2 binary proof-DAG library containing 3,070 named theorems exported from Isabelle2025-2 (HOL, HOL-Library, HOL-Analysis, HOL-Computational_Algebra) with their complete proof closure.

Fetch the pinned external library:

pixi run fetch-judgment-mathlib

Open it through judgment_store's Library in either of the two modes from Lesson 5.4:

var library = Library.open(path, Optional(Identity.from_hex(VERSION)))

# Statement-only import over the Isabelle profile (records imported provenance):
var fast = Session.open(library.profile_snapshot(budget))
var facts = fast.import_theorems[Library](library, names)

# Parallel full recheck of all 118 partitions through judgment_core:
var checked = Session.open(library.snapshot(budget, workers))
  • Statement import loads the signature closure and records Isabelle provenance explicitly in dependency audits.
  • Full snapshot (library.snapshot(budget, workers)) rechecks every proof row in parallel through judgment_core, yielding rechecked theorems with no imported assumptions.

Exercise

In memory_and_spill, call s.set_memory_limit(used - 1) immediately after reading used = s.memory_used(). What happens?

Answer

The call fails with LIMIT and leaves s.memory_limit() unchanged; the cap cannot be set below bytes already allocated to the live workspace.


Further references: Writing proofs, Scalar workflows, Proof libraries & OpenTheory, and Using the API.

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