Lean-42 — Arithmetic independence, certified: PA does not decide a 196-state machine

Lancer : Codespaces Colab

Navigation: Index | << Lean-21 Capstone MIMO | Version francaise

Lake: busybeaver_lean/ — pinned consumer of the PA196 package from jamesyc/BusyBeaver.

Source: the PA196 paper (MIT), archived in the bibliography store at BusyBeaver/PA196/paper/pa196.pdf. Series issue: #27477, milestone 2.

Plan

  1. The consumer lake: where the upstream package lives, at which commit, with which toolchain.
  2. The pin: read the manifest back and check that the revision holds.
  3. The build: build the witness and read what lake actually did.
  4. The axiom audit: #print axioms on the four central theorems, and the mechanical verdict.
  5. The paper’s numbers: states, table rows, steps — confronted with the upstream package’s transition table.
  6. Reading: what “independent of PA” means, and what it does not say.
  7. Exercises: three, to be written in the stub cells.

1. The consumer lake

The busybeaver_lean lake defines nothing: it pins the upstream PA196 package and imports its theorems. The clause in lakefile.lean is direct:

require «pa196» from git
  "https://github.com/jamesyc/BusyBeaver.git" @ "8419afeb…" / "PA196"

The / "PA196" form is Lake’s subdirectory syntax: Lake clones the repository and loads the package as published, without a fork or a copy. This is the strictest form of the repository’s CONSUMER_PINNED doctrine: no upstream module is vendored, adapted or copied.

The lake’s toolchain is v4.35.0, the upstream package’s, not the neighbouring formal_logic_lean lake’s (4.33.1). This is not an oversight: the PA196 corpus is sizeable and its vendor/Foundation is itself on 4.35.0. Bringing it back to 4.33.1 would mean porting the whole corpus; one lake per toolchain is the form Lake provides, and the two lakes live side by side.

The next cell locates the lake, computes the WSL path, and compares the SHA-256 fingerprints of the build files between the repository and the lake actually used: a successful build in that lake only stands for the repository if the fingerprints agree.

import hashlib
import os
import pathlib
import subprocess

NB_DIR = pathlib.Path.cwd()
REPO_LAKE = NB_DIR / "busybeaver_lean"
PIN_ATTENDU = "8419afeb6513c2ec5a14d4cbd0d2ade43d5553b0"


def wslpath(p):
    # Chemin Windows -> chemin WSL, calcule par WSL lui-meme.
    r = subprocess.run(["wsl", "-e", "wslpath", "-a", str(p).replace(chr(92), "/")],
                       capture_output=True, text=True, encoding="utf-8", errors="replace")
    return r.stdout.strip()


def wsl_sh(commande):
    # Execute une commande shell dans WSL et rend sa sortie standard.
    r = subprocess.run(["wsl", "-e", "bash", "-lc", commande],
                       capture_output=True, text=True, encoding="utf-8", errors="replace")
    return r.stdout


LAKE_OVERRIDE = os.environ.get("BUSYBEAVER_LAKE_WSL")
LAKE_DIR = LAKE_OVERRIDE or wslpath(REPO_LAKE)
LEAN_EXEC = wslpath(NB_DIR.parents[2] / "scripts" / "lean" / "lean_exec.py")


def lean_exec(commande, timeout=900):
    # Lance `commande` dans le lake via l'organe borne ; rend (code, sortie, journal).
    r = subprocess.run(
        ["wsl", "-e", "bash", "-lc",
         f"cd {LAKE_DIR} && python3 {LEAN_EXEC} run --timeout {timeout} -- {commande}"],
        capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout + 120)
    journal = [l for l in r.stderr.splitlines() if l.startswith("[lean_exec]")]
    return r.returncode, r.stdout, journal


FICHIERS_BUILD = ["lean-toolchain", "lakefile.lean", "lake-manifest.json", "BusyBeaver.lean"]

# Tout est accumule puis imprime en UNE fois : un seul flush stdout, donc une
# seule sortie commitee -- le jumeau EN ne peut pas decouper autrement.
lignes = ["lake utilise : " + ("copie (BUSYBEAVER_LAKE_WSL)" if LAKE_OVERRIDE
                               else "busybeaver_lean du depot")]
cote_wsl = wsl_sh(f"cd {LAKE_DIR} && sha256sum " + " ".join(FICHIERS_BUILD)).splitlines()
empreintes_wsl = {l.split()[1]: l.split()[0] for l in cote_wsl if l.strip()}
identiques = 0
for nom in FICHIERS_BUILD:
    h_depot = hashlib.sha256((REPO_LAKE / nom).read_bytes()).hexdigest()
    h_lake = empreintes_wsl.get(nom, "absent")
    identiques += h_depot == h_lake
    lignes.append(f"  {nom:22s} depot {h_depot[:12]}  lake {h_lake[:12]}  "
                  f"{'identique' if h_depot == h_lake else 'DIFFERENT'}")
lignes.append(f"{identiques}/{len(FICHIERS_BUILD)} fichiers identiques"
              + ("  (comparaison triviale : meme dossier)" if not LAKE_OVERRIDE else ""))

# Le manifeste peut annoncer un pin ; la tete du clone reellement construit le
# prouve. Les deux sont lus : le manifeste a la cellule suivante, la tete ici.
tete = wsl_sh(f"git -C {LAKE_DIR}/.lake/packages/pa196 rev-parse HEAD").strip()
lignes.append("tete du clone amont : " + tete)
lignes.append("pin tenu (clone)    : " + str(tete == PIN_ATTENDU))
lignes.append("toolchain           : " + (REPO_LAKE / "lean-toolchain").read_text().strip())
print("\n".join(lignes))
lake utilise : busybeaver_lean du depot
  lean-toolchain         depot ead308ab4fc7  lake ead308ab4fc7  identique
  lakefile.lean          depot e7e789afae0a  lake e7e789afae0a  identique
  lake-manifest.json     depot 0c2ef4f790b7  lake 0c2ef4f790b7  identique
  BusyBeaver.lean        depot d5b36af89c18  lake d5b36af89c18  identique
4/4 fichiers identiques  (comparaison triviale : meme dossier)
tete du clone amont : 8419afeb6513c2ec5a14d4cbd0d2ade43d5553b0
pin tenu (clone)    : True
toolchain           : leanprover/lean4:v4.35.0

Reading the setup

Four lines, one per build file: each shows the hash on the repository side and the hash on the lake side. All must read identique — otherwise the lake being built is a different object from the repository one (a forgotten copy, an intermediate state). In copy mode (BUSYBEAVER_LAKE_WSL) the comparison is real; on the repository lake it is trivially true, and the cell says so instead of letting the reader believe otherwise.

Two more lines close the manifest’s blind spot: git rev-parse HEAD on the upstream clone yields the revision actually checked out, and pin tenu (clone) must be True. A manifest can announce a pin the clone does not have; the clone head cannot. The toolchain printed is the one lake will use — v4.35.0.

2. The pin, read back from the manifest

lake update resolved the from git clause into a revision recorded in lake-manifest.json. That file is the contract: every later build starts from these revisions, not from the upstream branch.

The cell reads the manifest and looks up the pa196 package. The expected commit is 8419afeb… — the one on which upstream publishes its package, audit and paper. A manifest carrying another revision would be a silent drift: the build would succeed, but on different content.

# Le manifeste Lake fige le commit exact du paquet : c'est la preuve du pin.
import json

manifeste = json.loads((REPO_LAKE / "lake-manifest.json").read_text(encoding="utf-8"))
# PA196 est la dependance directe ; les autres paquets viennent de ses transitives.
paquet = next(p for p in manifeste["packages"] if p["name"] == "pa196")
print("paquet      :", paquet["name"])
print("rev         :", paquet["rev"])
print("url         :", paquet["url"])
print("pin tenu    :", paquet["rev"] == PIN_ATTENDU)
print("sous-dir lu :", paquet.get("subDir"))
print("dependances :", ", ".join(sorted(p["name"] for p in manifeste["packages"]
                                       if p["name"] != "pa196")))
paquet      : pa196
rev         : 8419afeb6513c2ec5a14d4cbd0d2ade43d5553b0
url         : https://github.com/jamesyc/BusyBeaver.git
pin tenu    : True
sous-dir lu : PA196
dependances : Cli, Foundation, LeanSearchClient, Qq, aesop, batteries, importGraph, mathlib, plausible, proofwidgets

Reading the pin

Four values are to be confronted: rev must equal the expected pin (pin tenu : True), url must point at jamesyc/BusyBeaver, sous-dir lu must read PA196, and the dependency list must be the one the upstream package declares. Those dependencies — Mathlib, the vendored Foundation, then aesop, batteries, Qq, Cli, plausible, proofwidgets, import-graph, LeanSearchClient — are resolved by the upstream package itself: this lake does not redeclare them, so it cannot make them drift.

3. The build

The cell runs lake build in the lake through the scripts/lean/lean_exec.py organ: machine-wide cap, process-tree confinement, measured budget. It is the same organ the other notebooks of the series use; no lake is launched by hand.

On a fresh lake, two commands come first: lake update (pin resolution and manifest) then lake exe cache get (Mathlib oleans for the upstream revision). Without the cache, Mathlib would be compiled from source — hours for content upstream already publishes. The notebook takes them as given: its subject is the witness build, not the lake’s preparation.

A first build then pays for the compilation of the upstream package — ProofSources and its vendored Foundation — and later builds are incremental. The time shown is therefore not a property of the result: it is the state of the cache.

# Build du temoin : incremental une fois les oleans en place.
code_retour, sortie, journal = lean_exec("lake build", timeout=5400)
utiles = [l for l in sortie.splitlines()
          if not l.startswith(("info:", "trace", "  ", "\u2139"))]
print("\n".join(utiles[-8:]))
# Le temps de build varie d'un run a l'autre : normalise, sinon le jumeau EN
# ne peut pas porter la meme sortie (garde twin-parity).
import re
print("\n".join(re.sub(r"duration=[0-9.]+s", "duration=mesuree", l) for l in journal))
print("code de retour :", code_retour)
 Quot.sound]
 Classical.choice,
 Quot.sound]
 Classical.choice,
 Quot.sound]
 Classical.choice,
 Quot.sound]
Build completed successfully (3195 jobs).
[lean_exec] ok exit=0 duration=mesuree orphans=0
[lean_exec] child_exit_code: 0
code de retour : 0

Reading the build

Three things are read here. The return code must be zero — a failing lake build returns a nonzero code and error lines. The organ journal carries the admission measurement and the “zero orphan descendant” postcondition. The useful output names the targets built: BusyBeaver, and behind it the upstream package libraries it imports (PA196, M6, M6PA, PA196Bridge).

An incremental build may print no task at all: that means the .olean files are up to date, not that nothing was checked. BusyBeaver.lean and its imports were then elaborated by an earlier build.

The upstream PA196.Audit module is a guarded audit: its #print axioms are wrapped in #guard_msgs that freeze the expected set. Building PA196 therefore runs those guards — an extra axiom, an admitted proof or a change in native trust makes compilation fail there, before this notebook’s own reprints.

4. The axiom audit

Lean can report, for each theorem, the list of axioms its proof depends on. That is the measurement separating a complete proof from one relying on sorry (sorryAx) or on native evaluation (Lean.ofReduceBool, via native_decide).

The BusyBeaver.lean module writes four #print axioms: PA196.machine_nonhalting, PA196.Arithmetic.nonhalting_unprovable, PA196.Arithmetic.halting_unprovable, PA196.Arithmetic.two_sided_independence. The cell re-elaborates the module with lake env lean — imports are resolved by the lake — and reads the axiom lines.

The verdict is then mechanical, not declarative: the next cell compares the cited set against the allowlist propext, Classical.choice, Quot.sound, and against the forbidden list sorryAx, Lean.ofReduceBool, Lean.trustCompiler.

# Audit d'axiomes : `lake env lean` re-elabore le module et imprime chaque
# ligne `#print axioms` ecrite dans BusyBeaver.lean.
code_retour, sortie, journal = lean_exec("lake env lean BusyBeaver.lean", timeout=1800)
lignes_axiomes = [l.strip() for l in sortie.splitlines() if "axioms" in l.lower()]
print("\n".join(lignes_axiomes))
print("code de retour :", code_retour)
'PA196.machine_nonhalting' depends on axioms: [propext, Classical.choice, Quot.sound]
'PA196.Arithmetic.nonhalting_unprovable' depends on axioms: [propext, Classical.choice, Quot.sound]
'PA196.Arithmetic.halting_unprovable' depends on axioms: [propext, Classical.choice, Quot.sound]
'PA196.Arithmetic.two_sided_independence' depends on axioms: [propext, Classical.choice, Quot.sound]
code de retour : 0
AUTORISES = {"propext", "Classical.choice", "Quot.sound"}
INTERDITS = {"sorryAx", "Lean.ofReduceBool", "Lean.trustCompiler"}


def axiomes_cites(lignes):
    # Extrait l'ensemble des axiomes cites par les lignes `#print axioms`.
    trouves = set()
    for ligne in lignes:
        if "depends on axioms:" in ligne:
            liste = ligne.split("depends on axioms:")[-1].strip().strip("[]")
            trouves |= {a.strip() for a in liste.split(",") if a.strip()}
        # « does not depend on any axioms » : ensemble vide, rien a ajouter.
    return trouves


cites = axiomes_cites(lignes_axiomes)
print("axiomes cites :", sorted(cites) if cites else "(aucun)")
print("hors liste blanche :", sorted(cites - AUTORISES) or "(aucun)")
print("interdits presents :", sorted(cites & INTERDITS) or "(aucun)")
print("audit concluant :", cites <= AUTORISES and not (cites & INTERDITS))
axiomes cites : ['Classical.choice', 'Quot.sound', 'propext']
hors liste blanche : (aucun)
interdits presents : (aucun)
audit concluant : True

Reading the audit

Each theorem must yield a depends on axioms: … line whose content is a subset of the allowlist, or does not depend on any axioms. The three allowed axioms are those of Lean’s and Mathlib’s kernel: propext (propositional extensionality), Classical.choice (classical choice), Quot.sound (quotients). None of them is a proof hole.

audit concluant : True is the only acceptable outcome. A sorryAx would signal a proof left empty upstream; a Lean.ofReduceBool would signal a call to native_decide, whose trust rests on the compiler rather than on the kernel.

This mechanical verdict doubles a guard upstream already carries: PA196.Audit wraps its #print axioms in #guard_msgs that freeze the expected set, so an extra axiom makes the package fail to compile — hence our build, before our own lines. The notebook measures the same thing in its own log, at the same revision.

5. The paper’s numbers

The result is a theorem, but its statement cites numbers: 196 states, a complete transition table, 58,154 steps to reach the register-program frame, and a reduction of 13 states over the previously published construction (209 states).

The cell reads the consumed package’s transition table (data/pa196.tm) and confronts its numbers — 2 × 196 = 392, 209 − 196 = 13 — then computes an order of magnitude. It re-proves nothing: the proof is upstream’s, consumed through the lake. Confronting a statement with its data is reading hygiene, not a claim of result.

# Les nombres du papier, verifies sur la donnee amont : la table de transition
# `data/pa196.tm` est lue ligne a ligne, pas recopiee depuis le texte.
chemin_table = f"{LAKE_DIR}/.lake/packages/pa196/PA196/data/pa196.tm"
lignes_table = [l for l in wsl_sh(f"cat {chemin_table}").splitlines() if l.strip()]
etats_lus = sorted({int(l.split()[0]) for l in lignes_table})
symboles_lus = sorted({l.split()[1] for l in lignes_table})
ETATS, ROWS, PAS_VERS_CADRE, ETATS_PRECEDENT = 196, 392, 58_154, 209

print("lignes de table lues      :", len(lignes_table), "| papier :", ROWS,
      "| concordance :", len(lignes_table) == ROWS)
print("etats distincts lus       :", len(etats_lus), "| papier :", ETATS,
      "| concordance :", etats_lus == list(range(ETATS)))
print("symboles lus              :", symboles_lus,
      "| alphabet binaire :", symboles_lus == ["0", "1"])
print("lignes attendues 2*196    :", 2 * ETATS, "| lues :", len(lignes_table),
      "| concordance :", 2 * ETATS == len(lignes_table))
print("reduction d'etats 209-196 :", ETATS_PRECEDENT - ETATS, "| papier : 13")
print("pas par etat (ordre de grandeur) :", round(PAS_VERS_CADRE / ETATS, 1))
lignes de table lues      : 392 | papier : 392 | concordance : True
etats distincts lus       : 196 | papier : 196 | concordance : True
symboles lus              : ['0', '1'] | alphabet binaire : True
lignes attendues 2*196    : 392 | lues : 392 | concordance : True
reduction d'etats 209-196 : 13 | papier : 13
pas par etat (ordre de grandeur) : 296.7

Reading the numbers

The concordances read True: the table read from data/pa196.tm yields 196 distinct states exactly 0…195, a binary alphabet, and 2 × 196 = 392. The table is not copied from the paper’s text: it is read from the consumed package, at the pinned revision. The order of magnitude of the machine’s cost (about three hundred steps per state) is a reading figure, not a theorem.

What is certified is not that quotient: it is the independence of the halting statement with respect to PA, and non-halting in the standard model.

6. Reading: what “independent of PA” means

Three statements answer each other in the audit, and they are worth separating:

Theorem What it establishes
machine_nonhalting the machine does not halt, in the standard model
halting_unprovable PA does not prove that the machine halts
nonhalting_unprovable PA does not prove that it does not halt
two_sided_independence both of the above, together: the halting sentence is independent of PA

The pivot is Gödel’s second incompleteness theorem: the machine searches for a refutation in PA, and PA proves that its non-halting implies its own consistency. If PA proved non-halting, it would prove its consistency — excluded if it is consistent. Soundness in the standard model excludes the other side.

What this does not say: neither the value of BB(196), nor a bound on the number of states needed. The result is a witness of independence, not a Busy Beaver record. This is exactly the formal side that Complexity-07b lacked: that notebook describes the large numbers, this one shows a machine-checked proof of an independence statement.

The neighbouring formal_logic_lean lake (Lean-03b, Lean-34b) carries provability logic and FairBot; busybeaver_lean carries arithmetic independence. Both consume pinned packages, at different toolchains, and do not duplicate each other.

Exercise 1 — The audit predicate

# Exercice 1 : ecrire le predicat d'audit qui refuserait un axiome interdit.
def audit_concluant(lignes):
    # TODO etudiant : renvoyer True si tous les axiomes cites sont dans AUTORISES.
    resultat = None  # TODO etudiant
    return resultat


print("Exercice a completer : audit_concluant(lignes_axiomes)")
Exercice a completer : audit_concluant(lignes_axiomes)

Exercise 2 — States and table rows

# Exercice 2 : generaliser la relation etats -> lignes d'une machine binaire.
def nombre_de_lignes(etats):
    # TODO etudiant : une machine a `etats` etats sur un alphabet binaire a
    # deux lignes par etat (une par symbole lu).
    resultat = None  # TODO etudiant
    return resultat


print("Exercice a completer : nombre_de_lignes(196)")
Exercice a completer : nombre_de_lignes(196)

Exercise 3 — Independence is not a BB value

# Exercice 3 : distinguer l'independance d'un enonce de la valeur BB(196).
def classe_du_resultat(non_halting_prouve, independant_de_pa):
    # TODO etudiant : renvoyer "valeur BB" si le resultat donne une borne sur
    # BB(196), "independance" s'il ne porte que sur la prouvabilite dans PA.
    resultat = None  # TODO etudiant
    return resultat


print("Exercice a completer : classe_du_resultat(True, True)")
Exercice a completer : classe_du_resultat(True, True)

7. Conclusion

  • The PA196 package is consumed as is, at the pinned commit, through the from git … / "PA196" clause: no fork, no copy, no adaptation.
  • The build passes under the bounded organ, and the axiom audit cites only propext, Classical.choice, Quot.sound — the upstream guarded audit (#guard_msgs) compiles in the same build: it could not have been otherwise without breaking compilation.
  • The result is a witness of independence: PA does not decide the halting of this 196-state machine, and that machine does not halt in the standard model.
  • The paper’s numbers are confronted with the upstream data: data/pa196.tm yields 196 states exactly 0…195 and a binary alphabet; the 58,154 steps and the reduction of 13 states remain reading values, without re-proof.

References

Retour au sommet