Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

fol: a solver's model becomes a certificate, while its refutation stays testimony

FABIOTESSa801c39600b2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 26f5be19..4ae89486 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -299,6 +299,11 @@ jobs:
# and proves the checker can also say no. OO_REQUIRE_FIXTURES=1 turns the
# "no lake installed" skip into a failure, so this job cannot pass by not
# running.
+ #
+ # The last three legs are the SAT/SMT family: a model finder proposes a
+ # finite structure and `oo-folmodel` disposes. They need z3 and mace4 as well
+ # as Lean, and the same environment variable turns a missing solver from a
+ # loud skip into a failure here, for the same reason.
lean:
timeout-minutes: 45
name: lean / certificate checker
@@ -341,6 +346,30 @@ jobs:
# fact, and it is the reason this job exists rather than being folded
# into the line above.
run: OO_REQUIRE_FIXTURES=1 cargo test --test lean_horn_certificate_test -- --nocapture
+ - name: Install the model finders
+ # Z3 reads SMT-LIB and is the only one of the two that can be asked the
+ # UNBOUNDED question, which is the only route to `unsatisfiable_oracle`.
+ # Mace4 ships in the LADR/Prover9 distribution: Prover9's refutations
+ # are uncheckable and by decision 0005 an oracle opinion for ever, but
+ # Mace4 is a FINITE MODEL FINDER and a finite model is exactly what
+ # this layer certifies. The dead toolchain has a live half.
+ run: sudo apt-get update && sudo apt-get install -y z3 prover9
+ - name: Check the first-order model certificates end to end
+ # `lake build` already compiles these proofs, because `Fol` and
+ # `oo-folmodel` are both in defaultTargets. What this leg adds is the
+ # ENGINE's own export going through a real solver and back into the
+ # verified checker, which is what decision 0006 recorded as missing.
+ run: OO_REQUIRE_FIXTURES=1 cargo test --test lean_fol_model_test -- --nocapture
+ - name: Check that an unchecked result never reports the certified word
+ # The laundering guard, and the reason this is its own leg rather than
+ # folded into the line above. A pipeline that fell back to
+ # `model_checked` when the checker was unavailable would print the
+ # certified word on every machine without Lean installed, and a run
+ # whose bounded search was exhausted must say `no_model_up_to_size_k`
+ # and never `unsatisfiable_oracle`. See docs/decisions/0006 item 4.
+ run: OO_REQUIRE_FIXTURES=1 cargo test --test fol_solver_verdict_test -- --nocapture
+ - name: Check the model ingestion, both front ends
+ run: OO_REQUIRE_FIXTURES=1 cargo test --test fol_model_ingest_test -- --nocapture
# The official W3C SHACL test suite, as a ratchet.
#
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3f01c7d..824c0676 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,64 @@ All notable changes to Open Ontologies are documented here.
## [Unreleased]
+### Added
+- **The SAT/SMT family, and the asymmetry that makes it worth building.** A
+ refutation cannot be replayed in core Lean, so decision 0005 rules a prover's
+ verdict an oracle opinion for ever. A MODEL is the opposite: a finite object,
+ decidable to check, and `lean/Fol/` holds a verified evaluator for it. So the
+ SATISFIABILITY direction is CERTIFIED while the refutation direction stays an
+ oracle, and the two never share a word.
+
+ `fol --format smtlib|ladr` are a third and fourth printer over the same
+ `FolProblem` the TPTP and CLIF printers walk, never a second translation;
+ every run also writes `problem.tsv`, the format `oo-folmodel` reads, with a
+ digest the Lean recomputes. `fol-model` (also `onto_fol_model` and batch
+ `fol-model`) drives the whole loop: export, run Z3 or Mace4, read the
+ structure back, hand it to the verified checker, and report five fields that
+ are never collapsed — `solver_verdict`, `encoding`, `checker_exit`, `verdict`
+ and `owl_reading`. Only `model_checked` rests on a theorem
+ (`Fol.satisfiable_of_check`), and it requires `checker_exit: 0`. An exhausted
+ BOUNDED search is `no_model_up_to_size_k` and is not unsatisfiability:
+ `∀x∃y (r(x,y) ∧ x≠y)` is unsat at carrier 1 and sat at carrier 2.
+ `unsatisfiable_oracle` may come only from a run with no cardinality
+ constraint. With a goal, a checked countermodel carries
+ `not_entailed_under_unproved_translation` — `Fol.not_entails_of_check`, the
+ sentence no prover can produce, weakened by the two things this layer does
+ not prove.
+
+ A solver answering `sat` whose model the checker REJECTS is a STOP_THE_LINE
+ disagreement with its own block, counted in the summary and exiting non-zero,
+ the way `tools/shacl_differential.py` treats a FALSE_CLEAN. It is never
+ `rejected` as though the ontology were at fault and never `model_checked`.
+
+ Mace4 is here because the dead toolchain has a live half: Prover9's
+ refutations are uncheckable, and Mace4 is a finite model finder whose output
+ is exactly what this layer certifies. Its symbols are MANGLED, because LADR
+ reads a name beginning with `u`, `v`, `w`, `x`, `y` or `z` as a VARIABLE —
+ measured on LADR 2009-11A, `p0(w0). -p0(k0).` is echoed as `p0(x).` and the
+ run reports `exit (exhausted)` with no error at all.
+
+### Fixed
+- **An assertion on a punned entity was dropped from the first-order export
+ SILENTLY, and the report said the axiom set was not weakened.** OWL 2 DL lets
+ one IRI be a class and an individual at once; `OwlLean/Syntax.lean` does not,
+ so the assertion is correctly outside the fragment — but
+ `count_out_of_fragment` knew six named OWL constructs and nothing about
+ punning, so `exports_a_weaker_axiom_set` was `false` over an export that was
+ weaker than the graph. Found by the new model-certificate pipeline, which
+ returned machine-checked countermodels for five of the nine triples the
+ OWL-RL reasoner derives on
+ `case-studies/blast-furnace-ironmaking/blast-furnace-ontology.ttl`, where
+ `bf:Hanging` is an `owl:Class` that also carries `bf:hasSeverity
+ bf:HighSeverity`. Now counted as `assertion on a punned entity` with its
+ reason; the reading itself is unchanged.
+- **A stop-the-line disagreement did not fail a `batch` run.** `src/batch.rs`
+ decided the exit code from the presence of an `"error"` key, and a
+ stop-the-line is not an error: the command ran and answered. Batch is the
+ mode every tool in `tools/` uses, so in the one place the gate has to bite it
+ did not. It now also reads the `stop_the_line` count, keyed on the field
+ rather than on the command name.
+
### Added
- **First-order export, over the translation a machine-checked adequacy theorem
is about.** `fol --out DIR --format tptp|clif` (also `onto_fol_export` and
diff --git a/CLAUDE.md b/CLAUDE.md
index 1bb6b96b..9d4e7046 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -105,7 +105,8 @@ Claude dynamically decides the next tool call based on what the previous tool re
| `onto_enforce_feedback` | To accept/dismiss an enforce violation — teaches enforce to suppress repeatedly dismissed violations |
| `onto_dl_explain` | To explain why a class is unsatisfiable using DL tableaux reasoning — returns clash trace |
| `onto_dl_check` | To check if one class is subsumed by another using DL tableaux reasoning |
-| `onto_fol_export` | To hand the ontology to the automated-theorem-proving ecosystem. Writes TPTP FOF (what E and Vampire read) or ISO/IEC 24707 CLIF (the standards-track interchange syntax, and what ISO/IEC 21838-2 publishes BFO in), restricted both to the first-order-equivalent fragment of Common Logic and to the subdialect ISO/IEC 24707 A.4.2 calls exactly semantically conformant, each checked by a test rather than asserted. Both are serialisers over ONE translation: the one `OwlLean.adequacy` in the sibling owl-lean project is machine-checked about, including the background axioms and the individual typing axioms that theorem requires. The correspondence between this emitter and that Lean is PINNED BY TESTS AND NOT PROVED, and the emitted file says so. Constructs outside the fragment are named with counts and reasons in `constructs_not_exported`, never dropped silently. CLIF sentences are emitted BARE with standalone `(cl:comment '...')` labels, because the two CLIF parsers that exist both return an EMPTY theory from the wrapped `(cl:comment '...' SENTENCE)` form that ISO/IEC 21838-2's own BFO files use; `clif_comments: "wrapped"` restores that form and loses the content. Pass `goals_file` to also write one problem per conjecture. A PROVER'S VERDICT ON THE OUTPUT IS AN ORACLE OPINION AND NEVER A CERTIFICATE: use tools/fol_differential.py, which reports disagreement between this engine and an ATP and does not adjudicate it. See docs/first-order-export.md and decision 0005 |
+| `onto_fol_export` | To hand the ontology to the automated-theorem-proving ecosystem. Writes TPTP FOF (what E and Vampire read), ISO/IEC 24707 CLIF (the standards-track interchange syntax, and what ISO/IEC 21838-2 publishes BFO in), restricted both to the first-order-equivalent fragment of Common Logic and to the subdialect ISO/IEC 24707 A.4.2 calls exactly semantically conformant, each checked by a test rather than asserted. Both are serialisers over ONE translation: the one `OwlLean.adequacy` in the sibling owl-lean project is machine-checked about, including the background axioms and the individual typing axioms that theorem requires. The correspondence between this emitter and that Lean is PINNED BY TESTS AND NOT PROVED, and the emitted file says so. Constructs outside the fragment are named with counts and reasons in `constructs_not_exported`, never dropped silently. CLIF sentences are emitted BARE with standalone `(cl:comment '...')` labels, because the two CLIF parsers that exist both return an EMPTY theory from the wrapped `(cl:comment '...' SENTENCE)` form that ISO/IEC 21838-2's own BFO files use; `clif_comments: "wrapped"` restores that form and loses the content. `smtlib` (SMT-LIB 2, what Z3 reads) and `ladr` (what Mace4 reads, every symbol MANGLED with the table in `symbols.tsv`, because LADR reads a name beginning with u, v, w, x, y or z as a VARIABLE) write the same translation for MODEL FINDERS, and assert the NEGATED goal because a countermodel to `G |= phi` is a model of `G + {not phi}`. Every run also writes `problem.tsv` with its digest, the format the verified checker reads. Pass `goals_file` to also write one problem per conjecture. A PROVER'S VERDICT ON THE OUTPUT IS AN ORACLE OPINION AND NEVER A CERTIFICATE: use tools/fol_differential.py, which reports disagreement between this engine and an ATP and does not adjudicate it. See docs/first-order-export.md and decision 0005 |
+| `onto_fol_model` | To find a FINITE MODEL of the loaded ontology and CHECK it, so the answer names what it rests on. The SAT/SMT family, and deliberately not symmetric: a refutation cannot be replayed in core Lean, so a solver's `unsat` is an ORACLE OPINION for ever, while a MODEL is a finite object and `Fol.satisfiable_of_check` in `lean/Fol/` turns an accepted structure into satisfiability of exactly the formulas it was checked against. With a goal, `Fol.not_entails_of_check` gives a machine-checked NON-ENTAILMENT, the one sentence no prover can produce. FIVE FIELDS THAT ARE NEVER COLLAPSED: `solver_verdict`, `encoding`, `checker_exit`, `verdict`, `owl_reading`. Five verdict words: `model_checked` is the ONLY certified one and requires `checker_exit: 0`; `no_model_up_to_size_k` is an exhausted BOUNDED search and IS NOT unsatisfiability; `unsatisfiable_oracle` may come only from a run with no cardinality constraint. A solver answering `sat` whose model the checker REJECTS is a STOP_THE_LINE disagreement, never `rejected` and never `model_checked`. Needs z3 or mace4 and `oo-folmodel` (`cd lean && lake build`); the absence of either is reported in `skipped`. See docs/decisions/0006 |
| `onto_embed` | After loading an ontology — generates text + Poincaré structural embeddings for all classes. The default local model is **multilingual** (`paraphrase-multilingual-MiniLM-L12-v2`), so labels in different natural languages embed into a shared space. Honours `[embeddings] provider = "local" \| "openai"` in `config.toml`; OpenAI-compatible gateways (Azure, Ollama, vLLM, LocalAI, …) are supported via `OPEN_ONTOLOGIES_EMBEDDINGS_*` env vars |
| `onto_search` | To find classes by natural language description — requires onto_embed first |
| `onto_similarity` | To compute embedding similarity between two specific IRIs |
diff --git a/README.md b/README.md
index eb4d21ca..98f91e46 100644
--- a/README.md
+++ b/README.md
@@ -1009,6 +1009,28 @@ was in the engine: `cls-svf1` derived the converse of a subclass axiom. Details
in [docs/lean-certificates.md](docs/lean-certificates.md) and
[decision 0002](docs/decisions/0002-an-inference-carries-a-certificate.md).
+### Certified satisfiability, and the asymmetry it rests on
+
+A theorem prover's refutation cannot be replayed in core Lean, so
+[decision 0005](docs/decisions/0005-a-prover-is-an-oracle-and-a-translation-is-a-theorem.md)
+rules its verdict an oracle opinion. A MODEL is the opposite: a finite object,
+decidable to check. `fol-model` (also `onto_fol_model`) exports the ontology as
+SMT-LIB 2 or LADR, runs Z3 or Mace4, reads the structure back and hands it to a
+checker whose soundness is a theorem — `Fol.satisfiable_of_check` — so one
+direction of the SAT/SMT family is CERTIFIED while the other stays an oracle,
+and the two never share a word. With a goal, a checked countermodel is a
+machine-checked NON-ENTAILMENT, the one sentence no prover can produce.
+
+The verdict says what it rests on. `model_checked` requires the checker to have
+accepted; an exhausted BOUNDED search is `no_model_up_to_size_k` and is not
+unsatisfiability; `unsatisfiable_oracle` can only come from a run with no
+cardinality constraint, and can never be more than an opinion. A solver that
+answers `sat` whose model the checker rejects is a stop-the-line disagreement
+that fails the command. Running it over this repository's own case studies
+found an export that was silently weaker than the graph. Details in
+[docs/lean-certificates.md](docs/lean-certificates.md) and
+[decision 0006](docs/decisions/0006-a-model-is-a-certificate-and-a-refutation-is-not.md).
+
### Studio
```mermaid
@@ -1094,6 +1116,7 @@ flowchart TD
| Schema Alignment | [docs/alignment.md](docs/alignment.md) |
| SHIQ Reasoning | [docs/reasoning.md](docs/reasoning.md) |
| Derivation certificates, Lean checker | [docs/lean-certificates.md](docs/lean-certificates.md) |
+| First-order export, and model certificates | [docs/first-order-export.md](docs/first-order-export.md) |
| Semantic Embeddings | [docs/embeddings.md](docs/embeddings.md) |
| Clinical Crosswalks | [docs/clinical.md](docs/clinical.md) |
| IES Ecosystem | [docs/ies-ecosystem.md](docs/ies-ecosystem.md) |
diff --git a/docs/decisions/0006-a-model-is-a-certificate-and-a-refutation-is-not.md b/docs/decisions/0006-a-model-is-a-certificate-and-a-refutation-is-not.md
new file mode 100644
index 00000000..438b2e41
--- /dev/null
+++ b/docs/decisions/0006-a-model-is-a-certificate-and-a-refutation-is-not.md
@@ -0,0 +1,301 @@
+# 0006 · A model is a certificate, and a refutation is not
+
+- **Status**: Implemented, both halves · `lean/Fol/` with `Fol.satisfiable_of_check`,
+ `Fol.check_complete` and `Fol.not_entails_of_check` machine-checked, no `sorry`, no
+ `native_decide`, no Mathlib · checker `oo-folmodel`, both targets in `defaultTargets` so the CI
+ job's bare `lake build` compiles them · Rust half in `src/tptp.rs` (`sym`, `smtlib`, `ladr`,
+ `checkfmt`), `src/fol_model.rs` (ingestion, two front ends) and `src/fol_solve.rs` (the
+ certifying pipeline), reachable as `fol --format smtlib|ladr`, `fol-model` and `onto_fol_model`,
+ with three CI legs over z3 and mace4
+- **Written**: 2026-09-14
+- **Related**: decision 0005 (a prover is an oracle, and a translation is a theorem), which this
+ decision is the mirror of; decision 0003 (a rule is data), whose verdict discipline and whose
+ sentence about digests are reused verbatim; decision 0002 (an inference carries a certificate)
+
+## The problem
+
+Five automated-reasoning families were the goal. Logic programming is `lean/OOCert/`, description
+logics are `lean/Dl/` and `src/tableaux.rs`, first-order theorem proving is `src/tptp.rs` and
+decision 0005. The SAT and SMT family was entirely absent: no SMT-LIB anywhere in the repository
+and no solver called.
+
+Decision 0005 settled the hard half of that family before it arrived. A superposition or CDCL(T)
+refutation cannot be replayed in core Lean, so an automated prover's verdict is an oracle opinion
+and never a certificate. Taken at face value that rules the whole family out, and taking it at face
+value would have been wrong.
+
+## The asymmetry, which is the whole reason this layer exists
+
+A refutation and a model are not two answers of the same kind.
+
+A refutation is a proof object in a calculus this repository does not implement. Checking one needs
+verified unification, a verified ordering, verified redundancy criteria and verified theory
+lemmas. That is a research project, and decision 0005 is right that nothing short of it earns the
+word "certified".
+
+A model is a finite object. Checking whether a formula holds in a finite structure is decidable,
+the decision procedure is a recursive `Bool`-valued function, and proving it agrees with the
+`Prop`-valued satisfaction relation is an induction over eleven constructors. `lean/Fol/Check.lean`
+is 130 lines of definitions and proof, and `Fol.eval_iff` is the whole of it.
+
+So one direction of the SAT/SMT family can be CERTIFIED while the other stays an ORACLE, and the
+same is true of every model finder. That includes a dead toolchain's live half: Prover9 is
+unmaintained and its refutations are uncheckable, but Mace4 ships in the same distribution, is a
+finite model finder, and prints exactly the kind of object this layer can certify.
+
+## Decisions
+
+1. **The satisfiability direction is certified, the refutation direction is not, and they never
+ share a word.** `Fol.satisfiable_of_check` turns an accepted structure into `Satisfiable Γ`.
+ Nothing in `lean/Fol/` says anything about unsatisfiability in any direction, and the driver's
+ own docstring says so in the negative space, in the shape `lean/DlMain.lean` uses.
+
+2. **The headline is a NON-ENTAILMENT, because that is the sentence no prover can produce.**
+ `Fol.not_entails_of_check` says that a checked model of `¬φ :: Γ` is a machine-checked proof of
+ `¬ Entails Γ φ`, under the same `Entails` that `OwlLean.adequacy` is stated about. A prover
+ answering "not a theorem" is guessing at worst and reporting a failed search at best. This is
+ the one place where the model direction is strictly STRONGER than what an ATP can offer, rather
+ than merely different, and it is why the layer is worth building at all.
+
+3. **The producer is untrusted by construction.** The checker re-evaluates the original formulas
+ against the structure and reads nothing else. It never trusts the solver's clausification, its
+ Skolemisation, its preprocessing or its choice of encoding. Mace4 clausifies and Skolemises, so
+ its models interpret symbols like `f1(_)` and `c1` that `Fol.FinModel` has no slot for; dropping
+ them on the way in is taking the reduct of its structure and needs no lemma here, because the
+ checker re-evaluates formulas that cannot mention a symbol the translation never emitted. The
+ driver reports the dropped names and their count so the reduct is visible rather than silent.
+
+4. **Four verdict words, and the fourth is the one nobody reaches for.** A report carries five
+ fields and they are never collapsed:
+
+ ```
+ "solver_verdict": "sat" | "unsat" | "unknown" what the oracle said
+ "encoding": "unbounded" | "finite(k)" what it was asked
+ "checker_exit": 0 | 1 | 2 | null null means never run
+ "verdict": "model_checked" CERTIFIED. names Fol.satisfiable_of_check
+ | "satisfiable_oracle" sat, no checkable model
+ | "no_model_up_to_size_k" bounded search exhausted. NOT unsatisfiability
+ | "unsatisfiable_oracle" unsat on the UNBOUNDED encoding. Never more
+ | "unknown_oracle" timeout, incomplete, gave up
+ "owl_reading": "not_entailed_under_unproved_translation" | null
+ ```
+
+ Three rules are mechanical. `model_checked` requires `checker_exit == 0`. `unsatisfiable_oracle`
+ may be produced ONLY by a run whose emitted problem carried no cardinality constraint of any
+ kind; any bounded run's `unsat` is `no_model_up_to_size_k`. `owl_reading` is non-null only when
+ the checker itself reported `goal_negated_present` AND the verdict is `model_checked`, computed
+ from what the checker read back rather than from the Rust side's intention.
+
+ `no_model_up_to_size_k` exists because the obvious wiring is wrong and takes ten minutes. A
+ finite-domain encoding that returns `unsat` has established that no model of that size exists,
+ which is not unsatisfiability and is often not even evidence of it. The formula
+ `∀x∃y (r(x,y) ∧ x≠y)` is `unsat` at carrier 1 and `sat` at carrier 2; a driver that mapped the
+ first to `unsatisfiable_oracle` would be reporting a falsehood from correct solver output.
+
+5. **A solver's `sat` whose model the checker REJECTS is not a statement about the ontology.**
+ Z3 can answer `sat` on quantified UF through model-based instantiation with a candidate model
+ that `get-value` reports incompletely. The verdict for that is `satisfiable_oracle` with
+ `checker_exit: 1` and a `model_not_confirmed` note. It is never `rejected` as though the
+ ontology were at fault, and it is never `model_checked`.
+
+6. **The coverage gate is about ATTRIBUTION and says so.** `Fol.covers` checks that every symbol
+ the problem uses is declared by the model file. Soundness holds without it: `FinModel`'s three
+ fields are total, an undeclared symbol is still interpreted, and `check` validates the resulting
+ structure from scratch. What the gate buys is that the structure certified is the structure the
+ solver described rather than the solver's completed with defaults. It is reported at exit 1 with
+ `"reason":"undeclared_symbol"` and `"gate":"attribution"`, it is kept out of `Satisfiable`, out
+ of every theorem, and out of the soundness statement. Dressing it up as soundness would be the
+ laundering move this repository keeps finding in other people's work and once in its own.
+
+7. **The digest binds the two files, and it identifies rather than commits.** `model.tsv` carries a
+ digest of the problem the solver was given and the Lean recomputes it from `problem.tsv`. It is
+ taken over the canonical re-serialisation of the PARSED formula list, not over the file bytes,
+ so labels and spacing cannot forge a match and a relabelled `goal_negated` cannot digest the
+ same. FNV-1a 64 is specified in `lean/Fol/Parse.lean` rather than taken from a library, because
+ `String.hash` is an opaque extern with no specification a Rust writer could target. It is not a
+ cryptographic hash; it exists so two implementations can be compared, not so one can be defended
+ against someone who controls the file. That is decision 0003 item 5, in the same words, for the
+ same reason.
+
+8. **An empty problem is exit 2.** Every structure satisfies the empty formula list, so a
+ certificate over one would report `model_checked` and say nothing. An exporter bug that dropped
+ every formula would otherwise produce a clean green run, which is the exact shape decision 0005
+ item 7 records happening inside this repository already, when the differential exported from a
+ reasoned store and every conjecture became trivially entailed.
+
+9. **The footprint is pinned at the MEASURED value, not at the habitual one.** Every result in
+ `lean/Fol/` is `[propext, Quot.sound]`, and several are `[propext]` or free of axioms entirely.
+ `Classical.choice` appears nowhere in the layer. Pinning the `[propext, Classical.choice,
+ Quot.sound]` triple that the older layers carry would be looser than the truth and would stop
+ catching anything. `lean/Dl/Check.lean` already pins `checkWF_iff` tighter than its neighbours,
+ so this is the house habit rather than a new one.
+
+## Why `Fol` does not reuse `Dl/Check.lean`
+
+This looks like duplication and it is not, so the reasons are written down here rather than left
+for someone to re-derive in six months and get wrong.
+
+1. `Dl.Sat : Interp → Concept → Name → Prop` evaluates at ONE free variable. First-order
+ satisfaction needs an environment `Nat → Dom`. Every clause of `Sat`, `sat` and `sat_iff`
+ changes signature.
+2. `Dl.Sat`'s `.ex r c` quantifies over `I.rext r x`, a successor LIST, not over the carrier.
+ Different quantification domain, different recursion, different well-formedness obligation.
+3. `Dl.Concept` has no equality constructor. `src/tptp.rs` emits `Form::Eq` for `SameAs`,
+ `DifferentFrom`, `OneOf` and `HasVal`.
+4. `Dl.Axiom` is a flat thirteen-constructor enumeration. `tptp::Form` is recursive with `Imp` and
+ arbitrary binder nesting, and `Translation::background()` emits shapes with no `Dl.Axiom` at all.
+5. **Copying `Dl.WellFormed` would be a defect rather than a shortcut.** `Dl` carries `cextInDom`
+ and `rextInDom` because `∃R.C` ENUMERATES `rext`, so an out-of-carrier successor would really be
+ evaluated. Here every quantifier ranges over the carrier TYPE and atoms are only tested, so
+ importing those clauses would make `Fol.check_complete` reject genuine models. The
+ well-formedness predicate is not shared; it is different mathematics.
+6. `Dl.holds_iff` is thirteen axiom cases. The first-order analogue is eleven formula cases with an
+ environment threaded through. No case transfers.
+
+Against that, `lean/Dl/Count.lean`, the 119-line hand-rolled pigeonhole that is the hardest file in
+that directory, has no first-order counterpart at all, because first-order logic has no counting
+constructor. The new library is smaller than the one it does not reuse. What IS reused is the
+shape: the `Interp`-style record, the hash-tables-behind-closures parser idiom, the driver's
+exit-code convention and its explicitly unverified diagnostic pass, the witness file's
+accept/reject/non-triviality triad including its short-bare-names trick, and the `#guard_msgs` plus
+`#print axioms` pinning. `lean/Dl/` is the template, not the library.
+
+## What this does not claim
+
+1. **Nothing about unsatisfiability, in any direction, ever.**
+2. **The absence of a finite model implies nothing.** SHIQ lacks the finite model property, so a
+ satisfiable ontology can have only infinite models and will never receive a certificate here.
+ That is a limitation of the method rather than a defect, and it is the honest counterweight to
+ the asymmetry the first section is built on. A bounded search that finds nothing has established
+ `no_model_up_to_size_k` and that is all.
+3. **The OWL-level reading rides on two things this layer does not prove.** `OwlLean.adequacy`
+ lives in the sibling project, and the Rust-to-Lean translation correspondence that decision 0005
+ item 2 states is pinned by tests and NOT proved. The certified verdict is about the formulas in
+ `problem.tsv`; the OWL sentence is strictly weaker and carries its own word,
+ `not_entailed_under_unproved_translation`, which must never be shortened to "not entailed".
+4. **That `Fol.Form`, `Fol.Struc` and `Fol.Entails` are `OwlLean.FOL`'s is a transcription, pinned
+ by tests.** It is a far smaller claim than `src/tptp.rs`'s, being about twenty lines of
+ inductive types and their semantics rather than a translation, and the two should not be allowed
+ to sound equally load-bearing.
+5. **The parser and the file formats are outside the theorem**, exactly as in `lean/Dl/Parse.lean`.
+ A parse error is exit 2 and never a verdict in either direction.
+6. **`source` and `cardinality_search` are untrusted.** They are what the file claims about its own
+ provenance, echoed for a report. Nothing checks them.
+
+## Two traps that are already measured, so that nobody has to find them twice
+
+**A LADR variable letter in the symbol table.** LADR's default convention is that a name beginning
+with `u`, `v`, `w`, `x`, `y` or `z` is a VARIABLE. A mangler that turns an IRI into `w0` therefore
+turns a constant into a universally quantified variable. Measured on this machine with
+LADR 2009-11A: the input `p0(w0). -p0(k0).` is echoed by Mace4 in its own `CLAUSES FOR SEARCH`
+block as
+
+```
+formulas(mace4_clauses).
+p0(x).
+-p0(k0).
+end_of_list.
+```
+
+and the search then runs until killed, because the mangled problem is unsatisfiable while the real
+one is not. A time limit would report `unknown`, so the failure is silent. The same file with `c0`
+in place of `w0` is echoed unchanged and returns a two-element model at once. The mangler must
+therefore never emit an initial letter in `{u,v,w,x,y,z}`: `p0…` for unary, `r0…` for binary,
+`c0…` for constants, and bound variables as `x0, x1, …` so that they still are variables under the
+same convention. The echoed clause block should be parsed and compared, not assumed.
+
+**Whitespace in a symbol.** `bare()` in `src/tptp.rs` strips the angle brackets before an IRI
+reaches `Term::Const` or `P1::Cls`, so the symbols are raw IRIs and the whitespace refusal in the
+checker-format writer is load-bearing rather than belt and braces. A symbol with a space in it
+re-parses as a different formula and one with a tab in it re-parses as a different set of fields.
+The 13 September 2026 audit found exactly this truncation class silently disabling any SHACL
+constraint that mentioned a typed literal. The writer must return an error rather than emit such a
+line, and the digest is the second line of defence: a file that splits differently on read-back
+canonicalises differently and the digest mismatches.
+
+## What the Lean half found while being built
+
+`free` was written with `List.erase` on the binder cases, copied from the design prototype.
+`List.erase` removes the FIRST occurrence only, so `free (∀x0. thing(x0) ∧ lit(x0))` came back as
+`[0]` and every formula using a bound variable twice was classified as open. Nothing became
+unsound, because a larger `free` only strengthens the hypothesis of `holds_congr`. What would have
+happened is that `check_complete_closed` would have stopped applying to essentially every real
+problem, and `oo-folmodel` would have reported `closed: false` and quoted the weaker rejection
+sentence for ever, with no test failing. It was caught by a `by decide` in `lean/Fol/Witness.lean`
+asserting that the witness problem is a set of sentences, and the fix is `filter` rather than
+`erase`.
+
+## What the Rust half found when it was first run end to end
+
+**A defect in this repository's own export reporting, of the exact shape this project exists to
+catch.** Running `fol-model --goals` over
+`case-studies/blast-furnace-ironmaking/blast-furnace-ontology.ttl` returned a MACHINE-CHECKED
+countermodel for five of the nine triples the OWL-RL reasoner derives there. `bf:Hanging` is
+declared `owl:Class` and also carries `bf:hasSeverity bf:HighSeverity`; `bf:hasSeverity` has domain
+`bf:ProcessState`; `rdfs2` fires and the engine derives `bf:Hanging rdf:type bf:ProcessState`. The
+exporter, reading `bf:Hanging` as a class, dropped the assertion — correctly, because
+`OwlLean/Syntax.lean` gives each entity kind its own type and `Sig.Ind` is disjoint from `Sig.Cls`,
+so the punning is outside the fragment. What was wrong is that it dropped it SILENTLY:
+`count_out_of_fragment` knew six named OWL constructs and nothing about punning, so the report said
+`exports_a_weaker_axiom_set: false` over an export that was weaker than the graph. Fixed by
+counting it as `assertion on a punned entity`, with the reason; the reading itself is unchanged, so
+no expected string in `fol_translation_correspondence_test.rs` moved. Five punned assertions
+reported, five certified non-entailments: the loop closes exactly.
+
+**And one in the ingestion, caught by the pipeline's own stop-the-line block on its first run.**
+Z3's `(define-fun NAME ((args)) SORT BODY)` has the RETURN SORT at index 3 and the body at 4. The
+first parser took index 3 for the body and every ingestion failed with `z3's model uses "Bool"`.
+Nothing was mis-certified, because the disagreement block is what fires when a model cannot be
+turned into a structure, and the verdict was `satisfiable_oracle` with nothing checked. It is
+recorded here because the fix added a sort check whose only job is to make that message name the
+symbol.
+
+**And a third, in the exit code.** `fol-model` exited non-zero on a stop-the-line only on the
+direct CLI path. `src/batch.rs` decided the exit code from the presence of an `"error"` key, and a
+stop-the-line is not an error — the command ran and answered — so `batch` exited 0 over it. Batch
+is the mode every tool in `tools/` uses, so in the one place the gate has to bite it did not. Fixed
+by reading the `stop_the_line` count as well, keyed on the field rather than on the command name so
+a later command reporting the same thing inherits it. Measured after the fix: the same ontology
+with a deliberately lying `z3` on `PATH` exits 1, and with the real `z3` exits 0.
+
+## Still not done
+
+- **The digest still identifies rather than commits.** FNV-1a is the right tool for comparing two
+ implementations and the wrong tool for defending against someone who controls the file. It is now
+ written twice, in `lean/Fol/Parse.lean` and in `tptp::checkfmt`, and the two agree on
+ `4403d8aaa0c422f7` by test on one side and `#guard` on the other. Neither is a commitment.
+- **The unbounded encoding's models are not ingested.** A `sat` on `declare-sort` is
+ `satisfiable_oracle` with `checker_exit: null`, because Z3 answers there through model-based
+ instantiation and prints a universe block rather than an enumeration. The bounded ladder is the
+ route to a certificate and the unbounded probe is the route to `unsatisfiable_oracle`; joining
+ them would need a reader for the universe form and a way to tell a complete model from a
+ candidate one.
+- **The ladder starts at 1 and stops at the first model, so the certificates are the SMALLEST
+ models.** Measured over the shipped case studies, every one of them is satisfied at carrier 1,
+ because none exports an axiom forcing two distinct elements. The certificate is real and the
+ property is weak. A `--min-domain` would produce more interesting structures and has not been
+ built.
+- **The emitted file asks for `(get-model)` unconditionally**, so an `unsat` run leaves
+ `(error "model is not available")` in the solver's captured output after the status line. It is
+ harmless — `read_sat` is line-oriented and finds `unsat` on its own line first, and the exit code
+ is not consulted for Z3 — but a reader of `z3_unbounded.out` sees an error next to a correct
+ answer. A second file without the `get-model` line, or `(set-option :produce-models false)` on
+ the probe, would remove it.
+- **Three things are quadratic or repeated and none of them matters yet.** `Fol.covers` is
+ O(|Γ| × |declarations|) in the Lean; the Rust `FolProblem::vocabulary()` is rebuilt on every call;
+ and `fol_model::mace4::parse_entries` materialises the remaining block as a `String` once per
+ entry, so reading a model with `e` entries copies O(e × block) characters. All three are fine at
+ the measured sizes — the largest shipped fixture is 2441 formulas and the whole pipeline runs in
+ 0.47 s — and all three would want fixing an order of magnitude up.
+- **`lean/Dl/Parse.lean` has an attribution bug of its own**, found while reading it for this work
+ and NOT fixed here. `Tables.toInterp` sets `ind := fun a => t.imap.getD a ""` and its docstring
+ claims the empty name "is in no domain". That is not guaranteed: `parseModel` accepts a `domain`
+ line with an empty element name, at which point `"" ∈ I.dom`, `indInDom` passes, and an
+ individual with no `ind` line silently denotes a real carrier element. It is a provenance defect
+ and not an unsoundness, since `Dl.Satisfiable` is existential over `Interp` and the interpretation
+ produced is a genuine one, so `satisfiable_of_checkModel` still holds. The fix is to refuse an
+ empty element name in `parseModel`, and it needs its own test.
+- **Decision 0002 references a "decision 0004" that does not exist** in `docs/decisions/`. The
+ description-logic model certificate it points at is `lean/Dl/` and is implemented; only the
+ record is missing. Not fixed here, because writing someone else's decision record is not this
+ agent's to do.
diff --git a/docs/first-order-export.md b/docs/first-order-export.md
index 5bc54d61..9c534cec 100644
--- a/docs/first-order-export.md
+++ b/docs/first-order-export.md
@@ -1,11 +1,15 @@
# First-order export, and what an ATP verdict is worth
-The engine can hand an ontology to the automated-theorem-proving ecosystem, in TPTP FOF and in
-ISO/IEC 24707 CLIF. The translation it emits is the one a machine-checked adequacy theorem is
-about, so a reader of the file can cite a kernel-checked result about what it means.
+The engine can hand an ontology to the automated-theorem-proving ecosystem, in TPTP FOF, in
+ISO/IEC 24707 CLIF, in SMT-LIB 2 and in LADR. The translation it emits is the one a machine-checked
+adequacy theorem is about, so a reader of the file can cite a kernel-checked result about what it
+means.
This page is the how-to. The design and its limits are in
-[decision 0005](decisions/0005-a-prover-is-an-oracle-and-a-translation-is-a-theorem.md).
+[decision 0005](decisions/0005-a-prover-is-an-oracle-and-a-translation-is-a-theorem.md) for the
+refutation direction and
+[decision 0006](decisions/0006-a-model-is-a-certificate-and-a-refutation-is-not.md) for the model
+direction.
**Read this first.** A prover's answer about an exported file is an ORACLE OPINION, not a
certificate. Decision 0002 lets this engine say an OWL-RL inference is *checked*, because `lean/`
@@ -14,6 +18,13 @@ way: it needs a verified first-order calculus with unification, which does not e
When E says `SZS status Theorem`, that carries exactly the weight of pyshacl agreeing with the
SHACL validator, and nothing here calls it a proof.
+**And read the asymmetry second.** A MODEL is the exact opposite of a refutation. It is a finite
+object, checking a formula against it is decidable, and `lean/Fol/` holds a verified evaluator for
+that, so the SATISFIABILITY direction CAN be certified. `fol --format smtlib` and
+`fol --format ladr` write the files a model finder reads, and `fol-model` drives the whole loop and
+hands the structure to the checker. See
+[lean-certificates.md](lean-certificates.md#first-order-model-certificates-oo-folmodel).
+
## Export
```bash
@@ -24,10 +35,31 @@ printf 'load ontology.ttl\nfol --out /tmp/fol --format tptp\n' \
# ISO/IEC 24707 CLIF. `iso` (default) writes cl:text; `colore` writes cl-text.
printf 'load ontology.ttl\nfol --out /tmp/fol --format clif --clif-dialect iso\n' \
| open-ontologies --no-connect --data-dir /tmp/store batch -
+
+# SMT-LIB 2, for Z3. Omit --smt-domain for the UNBOUNDED encoding, where `unsat`
+# really is unsatisfiability; give it k for an enumeration carrier of exactly k
+# elements, where a `sat` comes with a structure the verified checker can check.
+printf 'load ontology.ttl\nfol --out /tmp/fol --format smtlib --smt-domain 4\n' \
+ | open-ontologies --no-connect --data-dir /tmp/store batch -
+
+# LADR, for Mace4. Every symbol is MANGLED; the table lands in symbols.tsv.
+printf 'load ontology.ttl\nfol --out /tmp/fol --format ladr\n' \
+ | open-ontologies --no-connect --data-dir /tmp/store batch -
```
-Over MCP, `onto_fol_export` takes `out_dir`, `format`, `clif_dialect`, `goals_file` and
-`goals_skip_columns`.
+Over MCP, `onto_fol_export` takes `out_dir`, `format`, `smt_domain`, `clif_dialect`, `goals_file`
+and `goals_skip_columns`.
+
+Every run also writes `problem.tsv`, the format `oo-folmodel` reads, with its digest in the report.
+A solver result can therefore be handed to the verified checker without going back through the
+engine; `onto_fol_model` / `fol-model` does all of it in one call.
+
+**The two model-finding formats assert the NEGATED goal.** TPTP and CLIF carry a conjecture and the
+consumer negates it internally. A countermodel to `Γ ⊨ φ` is a model of `Γ ∪ {¬φ}`, so the SMT-LIB
+and LADR files carry `¬φ` as an assertion and nothing downstream negates again. A `sat` answer on
+one of those files therefore says the conjecture is NOT entailed. The negation happens once, in
+`FolProblem::checker_entries`, and `problem.tsv` is a fold over the same list, which is the
+mechanical reason the solver cannot be asked a different question from the one the checker checks.
`ontology.p` (or `ontology.clif`) lands in the directory. With `--goals FILE`, where FILE is a TSV
whose first three columns are a triple, one problem per goal lands under `goals/` with a
@@ -179,6 +211,16 @@ In the output, not in a comment. The report carries `exports_a_weaker_axiom_set`
}
```
+An ASSERTION whose subject is declared a class or a property is also outside the fragment and is
+counted as `assertion on a punned entity`. OWL 2 DL allows one IRI to be a class and an individual
+at once; `OwlLean/Syntax.lean` does not, because `Sig` gives each entity kind its own type. The
+subsumptions, domains and ranges on the same subject ARE exported, which is why this used to be
+invisible: the file looks complete. It was found by running the model-certificate pipeline over
+`case-studies/blast-furnace-ironmaking/`, where five of the nine triples the OWL-RL reasoner
+derives came back with a machine-checked countermodel, because `bf:Hanging` is an `owl:Class` that
+also carries `bf:hasSeverity bf:HighSeverity` and `rdfs2` is what the reasoner used. The export was
+genuinely weaker than the graph and the report said `exports_a_weaker_axiom_set: false`.
+
Outside the fragment: `owl:hasKey`, datatype facets (`owl:withRestrictions`, `owl:onDatatype`),
`owl:datatypeComplementOf`, `owl:NegativePropertyAssertion`, data cardinality restrictions,
data-property assertions (`Axiom` has `oPropAssert` and no `dPropAssert`), property characteristics
diff --git a/docs/lean-certificates.md b/docs/lean-certificates.md
index 63a03004..b983b3dc 100644
--- a/docs/lean-certificates.md
+++ b/docs/lean-certificates.md
@@ -176,6 +176,175 @@ The Rust reasoner does not yet evaluate a supplied rule table, so today this lay
certificates rather than producing them. See
[decision 0003](decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md).
+## First-order model certificates: `oo-folmodel`
+
+A solver's `sat` answer is worth nothing on its own and everything once the model comes with it.
+`lean/Fol/` holds a checker for a finite first-order structure, and `Fol.satisfiable_of_check` says
+that a structure it accepts really does satisfy every formula of the problem, so the problem is
+satisfiable. `Fol.not_entails_of_check` is the sharper form: a checked model of `¬φ` together with
+`Γ` is a machine-checked proof that `Γ` does **not** entail `φ`.
+
+```bash
+cd lean
+lake build # builds the checker AND checks the proofs
+lake exe oo-folmodel PROBLEM.tsv MODEL.tsv
+```
+
+```json
+{"verdict":"model_checked","formulas":5,"domain":2,"closed":true,
+ "goal_negated_present":true,"source":"z3","cardinality_search":"1,2",
+ "problem_digest":"4403d8aaa0c422f7","theorem":"Fol.satisfiable_of_check",
+ "non_entailment_theorem":"Fol.not_entails_of_check"}
+```
+
+The two file formats, with a worked example whose digest is pinned by the build, are documented in
+`lean/Fol/Syntax.lean`. Runnable copies of every case below are in `tests/fixtures/folmodel/`.
+
+**Exit codes, and the fixture that demonstrates each.**
+
+| exit | verdict | reason | fixture |
+|---|---|---|---|
+| 0 | `model_checked` | | `problem.tsv` + `model.tsv` |
+| 1 | `rejected` | the checker rejected the structure | `model_no_edge.tsv` |
+| 1 | `rejected` | `problem_digest_mismatch` | `model_wrong_digest.tsv`, `problem_other.tsv` |
+| 1 | `rejected` | `undeclared_symbol` | `model_undeclared.tsv` |
+| 2 | `unreadable` | the carrier is empty | `model_empty_domain.tsv` |
+| 2 | `unreadable` | a row contradicts a declared arity | `model_bad_arity.tsv` |
+| 2 | `unreadable` | an index is outside the carrier | `model_index_out_of_range.tsv` |
+| 2 | `unreadable` | a declared symbol has no row | `model_missing_row.tsv` |
+| 2 | `unreadable` | the problem carries no formulas | `problem_empty.tsv` |
+
+**The verdict tells you what it is relative to, and you must read it.** These four are the SOLVER
+level, and a driver that collapses any two of them is reporting a falsehood from correct solver
+output.
+
+| solver said | encoding | verdict | theorem | means |
+|---|---|---|---|---|
+| `sat`, with a model the checker accepted | either | `model_checked` | `Fol.satisfiable_of_check` | the problem has a model, exhibited |
+| `sat`, no checkable model | either | `satisfiable_oracle` | none | trust the solver |
+| `unsat` | `finite(k)` | `no_model_up_to_size_k` | none | **not** unsatisfiability |
+| `unsat` | `unbounded` | `unsatisfiable_oracle` | none | trust the solver, and never more |
+
+`no_model_up_to_size_k` is the one people get wrong. `∀x∃y (r(x,y) ∧ x≠y)` is `unsat` at carrier 1
+and `sat` at carrier 2, so a bounded `unsat` is frequently not evidence of anything. A solver that
+answers `sat` whose model the checker then REJECTS is `satisfiable_oracle` with `checker_exit: 1`,
+never `rejected` as though the ontology were at fault.
+
+**Two gates that are not soundness gates, and are labelled so.**
+
+- `undeclared_symbol` is an ATTRIBUTION gate. `Fol.FinModel`'s three fields are total, so an
+ undeclared symbol is still interpreted and the theorem holds without the gate. What it buys is
+ that the structure certified is the structure the solver described rather than that structure
+ completed with defaults. The JSON carries `"gate":"attribution"` so a report cannot quietly
+ promote it.
+- `problem_digest_mismatch` binds `model.tsv` to `problem.tsv`. The digest is FNV-1a 64 over the
+ canonical re-serialisation of the parsed formula list, specified in `lean/Fol/Parse.lean` so a
+ Rust writer can reproduce it. It identifies; it does not commit.
+
+**Cost, measured on this machine** (Apple silicon, compiled `oo-folmodel`, 2000 formulas at
+quantifier depth 3, so `carrier^3` evaluation points per formula):
+
+| carrier | evaluation points | user time |
+|---|---|---|
+| 8 | 1.0M | 0.14 s |
+| 16 | 8.2M | 0.92 s |
+| 24 | 27.6M | 2.93 s |
+| 32 | 65.5M | 6.80 s |
+
+About 9M points per second, cubic in the carrier at this depth. Solvers return carriers in the
+single digits on real ontologies, so this is a cap to state rather than a problem to solve:
+`--max-domain` defaults to 16 and the flag goes higher with the cost documented.
+
+### Driving all of it in one command: `fol-model`
+
+`oo-folmodel` checks a model somebody already has. `open-ontologies fol-model` produces one: it
+exports the ontology, runs Z3 or Mace4, reads the structure back, runs the checker, and reports the
+verdict with the five fields above.
+
+```bash
+cd lean && lake build && cd .. # the checker, and its proofs
+printf 'load case-studies/blast-furnace-ironmaking/blast-furnace-ontology.ttl\n\
+fol-model --out /tmp/solve --solver z3 --max-domain 8\n' \
+ | open-ontologies --no-connect --data-dir /tmp/store batch -
+```
+
+```json
+{"verdict":"model_checked","solver_verdict":"sat","encoding":"finite(1)","checker_exit":0,
+ "owl_reading":null,"theorem":"Fol.satisfiable_of_check","formulas":45,
+ "problem_digest":"27751aa61e9de6fd","cardinality_search":[1],
+ "bounded_search":"a model was reported at carrier 1","dropped_symbols":[],"seconds":0.084}
+```
+
+Every intermediate file lands in `--out`, so a run is reproducible by hand from what it leaves
+behind: `problem.tsv` and its digest, `problem_k1.smt2` (or `problem.in` plus `symbols.tsv` for
+Mace4), the solver's raw output, `model.tsv`, and `checker.json`.
+
+Pass `--goals` a TSV of triples — `derivations.tsv` from `reason --certificate` is the intended
+input, with `--goals-skip-columns 1` — and each becomes its own run asking whether the ontology
+FAILS to entail it. A `model_checked` there carries `owl_reading:
+"not_entailed_under_unproved_translation"`, which is `Fol.not_entails_of_check` plus two things
+this layer does not prove: `OwlLean.adequacy` lives in a sibling project, and the Rust-to-Lean
+translation correspondence is pinned by tests and not proved. Never shorten it to "not entailed".
+
+**A rejected model stops the line.** If a solver answers `sat` and the checker rejects the
+structure, the verdict stays `satisfiable_oracle` — it is not a fact about the ontology — but the
+report carries a `disagreement` block with `severity: STOP_THE_LINE`, the run summary counts it,
+and the command exits non-zero. That is the treatment `tools/shacl_differential.py` gives a
+FALSE_CLEAN, for the same reason: a disagreement between a checker and the thing it is checking is
+the one result that must fail a pipeline.
+
+**The two finders differ in what they can be asked, and the verdict rules read the difference.**
+
+| | Z3 | Mace4 |
+|---|---|---|
+| format | SMT-LIB 2 (`fol --format smtlib`) | LADR (`fol --format ladr`) |
+| smallest carrier | 1 | 2 — `mace4 -n 1` is a FATAL error, measured |
+| unbounded question | yes, so `unsatisfiable_oracle` is reachable | no, it is a finite model finder |
+| symbols | quoted with vertical bars | MANGLED to `p0`/`r0`/`c0`, table in `symbols.tsv` |
+| reduct | auxiliary functions | Skolem functions and constants |
+
+Mangling is not a style choice. LADR reads a name whose first letter is in `{u,v,w,x,y,z}` as a
+VARIABLE, so an IRI beginning with one of those becomes universally quantified and Mace4 silently
+searches a different problem. Measured on LADR 2009-11A: `p0(w0). -p0(k0).` is echoed in Mace4's
+own `CLAUSES FOR SEARCH` block as `p0(x).` and `-p0(k0).`, and the run reports `exit (exhausted)`
+with no error at all.
+
+## What is proved, and what is not, on this layer
+
+Every result in `lean/Fol/` has axiom footprint `[propext, Quot.sound]` or smaller, pinned by
+`#guard_msgs` in the source. `Classical.choice` appears nowhere in the layer, which is tighter than
+the triple the older layers carry.
+
+| theorem | says |
+|---|---|
+| `Fol.eval_iff` | the Boolean evaluator and the `Prop` satisfaction relation agree, at every formula and environment |
+| `Fol.satisfiable_of_check` | an accepted structure is an existence proof: the problem is satisfiable |
+| `Fol.check_complete` | the gate can fail: a rejection is about the structure, not the checker's patience |
+| `Fol.check_complete_closed` | for a problem of sentences, a rejected structure is not a model under **any** assignment |
+| `Fol.not_entails_of_check` | a checked model of `¬φ :: Γ` proves `Γ` does not entail `φ` |
+
+`lean/Fol/Witness.lean` closes the vacuity question by construction: `employment_is_satisfiable`
+accepts a real structure, `the_model_does_not_satisfy_everything` shows that same structure refuses
+a formula, `not_everything_is_satisfiable` shows `Satisfiable` is not the trivial predicate, and
+five named forgeries are each rejected on their own through `check_complete`, so it is the
+checker's own rejection that is certified rather than an independent argument.
+
+Not proved, and named next to the verdict rather than in a footnote:
+
+- **Nothing about unsatisfiability, in any direction, ever.**
+- **The absence of a finite model implies nothing.** SHIQ lacks the finite model property, so a
+ satisfiable ontology can have only infinite models and will never receive a certificate.
+- **The OWL-level reading** rides on `OwlLean.adequacy` in the sibling project *and* on the
+ Rust-to-Lean translation correspondence, which decision 0005 states is pinned by tests and not
+ proved. It carries its own word, `not_entailed_under_unproved_translation`, which must never be
+ shortened to "not entailed".
+- **The parser and the file formats** (`lean/Fol/Parse.lean`, `lean/FolMain.lean`). A parse error
+ is exit 2 and never a verdict in either direction.
+
+Nothing in `src/` writes either file yet, so today this layer checks certificates rather than
+producing them. See
+[decision 0006](decisions/0006-a-model-is-a-certificate-and-a-refutation-is-not.md).
+
## Known limitations
Stated rather than discovered later.
diff --git a/lean/Fol.lean b/lean/Fol.lean
new file mode 100644
index 00000000..62e0a62a
--- /dev/null
+++ b/lean/Fol.lean
@@ -0,0 +1,2 @@
+import Fol.All
+import Fol.Witness
diff --git a/lean/Fol/All.lean b/lean/Fol/All.lean
new file mode 100644
index 00000000..c441e01e
--- /dev/null
+++ b/lean/Fol/All.lean
@@ -0,0 +1,29 @@
+import Fol.Syntax
+import Fol.Semantics
+import Fol.Check
+import Fol.Free
+import Fol.Witness
+import Fol.Parse
+
+/-!
+# `Fol`: a model certificate for an external SAT/SMT solver or finite model finder
+
+The root module. Importing this builds every proof in the directory, including the axiom pins and
+the format `#guard`s, so a `sorry`, a changed axiom footprint or a drifted digest anywhere fails
+`lake build`.
+
+* `Fol/Syntax.lean` the fragment, the monomorphisation and its one obligation, both file formats,
+ a worked example with a measured digest, and a list of what is deliberately not covered.
+* `Fol/Semantics.lean` structures, satisfaction, `Satisfiable` and `Entails`, transcribed from
+ `OwlLean/FOL/Basic.lean`. Nothing here computes.
+* `Fol/Check.lean` the decision procedure, `Fol.eval_iff`, `Fol.satisfiable_of_check`,
+ `Fol.check_complete`, `Fol.not_entails_of_check`, and the coverage gate.
+* `Fol/Free.lean` the coincidence lemma, and the upgrade that makes a rejection a statement about
+ every assignment rather than the one the checker used.
+* `Fol/Witness.lean` an accepted structure, a formula it refuses, five rejected forgeries and an
+ unsatisfiable problem, so that neither the checker nor `Satisfiable` is trivial.
+* `Fol/Parse.lean` the two file readers, the canonical printer and the digest. Outside the theorem.
+
+The verdict vocabulary this layer plugs into, and the four solver verdicts that must never be
+collapsed, are in `docs/decisions/0006-a-model-is-a-certificate-and-a-refutation-is-not.md`.
+-/
diff --git a/lean/Fol/Check.lean b/lean/Fol/Check.lean
new file mode 100644
index 00000000..3b0940de
--- /dev/null
+++ b/lean/Fol/Check.lean
@@ -0,0 +1,228 @@
+import Fol.Semantics
+
+/-!
+# The decision procedure, and the theorems about it
+
+`check M Γ` decides whether the finite structure `M` satisfies every formula of `Γ`.
+`Fol.satisfiable_of_check` is what a solver's `sat` answer buys once a model comes with it: an
+accepted structure is an existence proof, so the problem really is satisfiable.
+
+`Fol.check_complete` is the other half and is what stops the layer being decoration. The checker
+agrees with `Form.holds` in BOTH directions, so it rejects exactly the structures that fail some
+formula. A checker that accepted everything would satisfy the soundness theorem just as well; this
+one cannot.
+
+`Fol.not_entails_of_check` is the result this layer exists for and is the exact dual of decision
+0005. A refutation cannot be replayed in core Lean and stays an oracle opinion. A COUNTERMODEL is
+a finite object, so a checked model of `¬φ :: Γ` is a machine-checked proof that `Γ` does not
+entail `φ`, under the same `Entails` that `OwlLean.adequacy` is stated about.
+
+## The carrier
+
+`FinModel n` interprets everything over `Fin n`, and `toStruc` is only defined at `n = m + 1`, so
+the carrier is a TYPE and it is non-empty by construction. Three consequences, all of which are
+why this shape was chosen over a carrier given as a list of names:
+
+* there is nothing outside the carrier, so this layer needs no well-formedness predicate and no
+ domain-membership hypothesis anywhere;
+* `const : Sym → Fin n` is total INTO the carrier, so "the constant denotes something outside the
+ domain" is unrepresentable rather than merely excluded by a check that a bug could drop;
+* `Env M.toStruc` unifies with `Nat → Fin (n+1)` definitionally, which is what lets the quantifier
+ cases of `eval_iff` close in six lines each.
+
+Everything here is `Bool`-valued and runs. No `native_decide`, no `Classical` case split on an
+undecidable proposition, no Mathlib.
+-/
+namespace Fol
+
+/-- A finite structure over `Fin n`.
+
+All three fields are TOTAL, so a symbol the model file never mentioned still has an
+interpretation: `false` everywhere, and element `0`. That is sound, because a defaulted structure
+is still a structure and `check` validates it from scratch rather than trusting where it came
+from. It is not free, because the object certified is then not the object the solver produced,
+which is what `covers` and the strict parser are for.
+
+The `false` default is not arbitrary and the reason is not soundness. It is chosen because its
+FAILURE MODE IS REJECTION. Under a `true` default the all-true structure models any purely
+positive theory, every certificate would check green, and the layer would be worthless while
+staying sound. A reader who assumes the default was picked for soundness will feel free to change
+it, so the argument is written here rather than left to be reconstructed. -/
+structure FinModel (n : Nat) where
+ p1 : Sym → Fin n → Bool
+ p2 : Sym → Fin n → Fin n → Bool
+ const : Sym → Fin n
+
+/-- The finite structure read as a `Struc`.
+
+`@[reducible]` is LOAD-BEARING. Without it `Env M.toStruc` will not unify with `Nat → Fin (n+1)`
+and the quantifier cases of `eval_iff` fail with an application type mismatch on `update`. -/
+@[reducible] def FinModel.toStruc {n : Nat} (M : FinModel (n+1)) : Struc where
+ Dom := Fin (n+1)
+ nonempty := ⟨0⟩
+ p1 := fun p x => M.p1 p x = true
+ p2 := fun p x y => M.p2 p x y = true
+ c := M.const
+
+/-- The computable counterpart of `update`. -/
+def upd {n : Nat} (e : Nat → Fin n) (k : Nat) (d : Fin n) : Nat → Fin n :=
+ fun m => if m = k then d else e m
+
+/-- The computable counterpart of `Term.eval`. -/
+def evalT {n : Nat} (M : FinModel n) (e : Nat → Fin n) : Term → Fin n
+ | .var k => e k
+ | .const c => M.const c
+
+/-- The computable counterpart of `Form.holds`.
+
+Structural recursion on `Form`, the LAST argument, with the environment varying. The recursive
+call sits under a lambda handed to `List.all`, which Lean accepts because the decreasing argument
+does not depend on that binder. No `termination_by`, no `decreasing_by`, the same shape as
+`Dl.sat`. -/
+def eval {n : Nat} (M : FinModel n) : (Nat → Fin n) → Form → Bool
+ | e, .app1 p t => M.p1 p (evalT M e t)
+ | e, .app2 p t u => M.p2 p (evalT M e t) (evalT M e u)
+ | e, .eq t u => evalT M e t == evalT M e u
+ | _, .tru => true
+ | _, .fls => false
+ | e, .neg f => !eval M e f
+ | e, .and f g => eval M e f && eval M e g
+ | e, .or f g => eval M e f || eval M e g
+ | e, .imp f g => !eval M e f || eval M e g
+ | e, .all k f => (List.finRange n).all (fun d => eval M (upd e k d) f)
+ | e, .ex k f => (List.finRange n).any (fun d => eval M (upd e k d) f)
+
+theorem evalT_eq {n : Nat} (M : FinModel (n+1)) (e : Nat → Fin (n+1)) (t : Term) :
+ evalT M e t = Term.eval M.toStruc e t := by
+ cases t <;> rfl
+
+theorem upd_eq {n : Nat} (M : FinModel (n+1)) (e : Nat → Fin (n+1)) (k : Nat) (d : Fin (n+1)) :
+ upd e k d = update (M := M.toStruc) e k d := rfl
+
+/-- **The bridge.** The Boolean evaluator and the `Prop`-valued satisfaction relation agree, at
+every formula and every environment.
+
+`intro f` then `induction f`, leaving `e` in the goal: the environment MUST be generalised or the
+quantifier cases have no usable induction hypothesis. -/
+theorem eval_iff {n : Nat} (M : FinModel (n+1)) :
+ ∀ (f : Form) (e : Nat → Fin (n+1)), eval M e f = true ↔ Form.holds M.toStruc e f := by
+ intro f
+ induction f with
+ | app1 p t => intro e; simp [eval, Form.holds, FinModel.toStruc, evalT_eq]
+ | app2 p t u => intro e; simp [eval, Form.holds, FinModel.toStruc, evalT_eq]
+ | eq t u => intro e; simp [eval, Form.holds, evalT_eq, beq_iff_eq]
+ | tru => intro e; simp [eval, Form.holds]
+ | fls => intro e; simp [eval, Form.holds]
+ | neg f ih => intro e; simp [eval, Form.holds, ← ih]
+ | and f g ihf ihg => intro e; simp [eval, Form.holds, ihf, ihg]
+ | or f g ihf ihg => intro e; simp [eval, Form.holds, ihf, ihg]
+ | imp f g ihf ihg =>
+ intro e
+ simp only [eval, Form.holds, Bool.or_eq_true, Bool.not_eq_true']
+ rw [← ihf, ← ihg]
+ cases h : eval M e f <;> simp
+ | all k f ih =>
+ intro e
+ simp only [eval, Form.holds, List.all_eq_true]
+ constructor
+ · intro h d
+ rw [← ih]
+ exact h d (List.mem_finRange d)
+ · intro h d _
+ rw [ih]
+ exact h d
+ | ex k f ih =>
+ intro e
+ simp only [eval, Form.holds, List.any_eq_true]
+ constructor
+ · rintro ⟨d, _, hd⟩
+ exact ⟨d, (ih _).1 hd⟩
+ · rintro ⟨d, hd⟩
+ exact ⟨d, List.mem_finRange d, (ih _).2 hd⟩
+
+/-- The whole check: every formula of the problem true in the structure, at the constant
+assignment. Acceptance does not depend on that choice of assignment, because `Satisfiable` binds
+the environment existentially; rejection does, and `Fol/Free.lean` is what removes the dependence
+for a problem of sentences. -/
+def check {n : Nat} (M : FinModel (n+1)) (Γ : List Form) : Bool :=
+ Γ.all (fun g => eval M (fun _ => 0) g)
+
+theorem check_iff {n : Nat} (M : FinModel (n+1)) (Γ : List Form) :
+ check M Γ = true ↔ ∀ g ∈ Γ, Form.holds M.toStruc (fun _ => (0 : Fin (n+1))) g := by
+ simp only [check, List.all_eq_true]
+ exact ⟨fun h g hg => (eval_iff M g _).1 (h g hg),
+ fun h g hg => (eval_iff M g _).2 (h g hg)⟩
+
+/-- **Soundness.** An accepted finite structure is an existence proof: the problem really is
+satisfiable, and the conclusion no longer mentions the structure the solver happened to build. -/
+theorem satisfiable_of_check {n : Nat} {M : FinModel (n+1)} {Γ : List Form}
+ (h : check M Γ = true) : Satisfiable Γ :=
+ ⟨M.toStruc, (fun _ => (0 : Fin (n+1))), (check_iff M Γ).1 h⟩
+
+/-- **Completeness, finite case.** The gate can fail, so a rejection is a statement about the
+structure and not about the checker's patience: the checker accepts every structure that satisfies
+the problem at the checked assignment. -/
+theorem check_complete {n : Nat} {M : FinModel (n+1)} {Γ : List Form}
+ (h : check M Γ = false) :
+ ¬ (∀ g ∈ Γ, Form.holds M.toStruc (fun _ => (0 : Fin (n+1))) g) := by
+ intro hm
+ rw [(check_iff M Γ).2 hm] at h
+ exact Bool.noConfusion h
+
+/-- **The result this layer exists for.** A checked model of `¬φ :: Γ` is a machine-checked proof
+that `Γ` does NOT entail `φ`, under the same `Entails` that `OwlLean.adequacy` is stated about.
+
+This is the exact dual of decision 0005: a refutation cannot be replayed in core Lean and stays an
+oracle opinion, while a countermodel is a finite object and is certified here. -/
+theorem not_entails_of_check {n : Nat} {M : FinModel (n+1)} {Γ : List Form} {φ : Form}
+ (h : check M (Form.neg φ :: Γ) = true) : ¬ Entails Γ φ := by
+ intro hE
+ have hall := (check_iff M _).1 h
+ have hneg := hall (Form.neg φ) (by simp)
+ exact hneg (hE M.toStruc _ (fun g hg => hall g (by simp [hg])))
+
+/-- **Signature coverage: an attribution gate, NOT a soundness gate.**
+
+Every symbol the problem uses is declared by the model file. Soundness holds WITHOUT this: a
+symbol the file never declared is still interpreted, by the totality of `FinModel`'s fields, and
+`check` validates the resulting structure from scratch. What the gate buys is that the structure
+certified is the structure the solver described, rather than the solver's structure silently
+completed with defaults.
+
+Dressing this up as part of the soundness statement would be the laundering move, so it is kept
+out of `Satisfiable`, out of `Models`, out of every theorem above, and reported at its own exit
+code with its own reason string. -/
+def covers (d1 d2 dc : List Sym) (Γ : List Form) : Bool :=
+ (Γ.flatMap p1Syms).all (fun p => d1.contains p)
+ && (Γ.flatMap p2Syms).all (fun p => d2.contains p)
+ && (Γ.flatMap constSyms).all (fun c => dc.contains c)
+
+/-! ## Axioms, pinned
+
+`[propext, Quot.sound]`, and NOT the `[propext, Classical.choice, Quot.sound]` triple the rest of
+this repository carries. That is a measurement rather than a preference: nothing in this file
+needs choice, and pinning the habitual triple here would be looser than the truth and would stop
+catching anything. `lean/Dl/Check.lean` already does the same for `checkWF_iff`. A `sorry` or a
+`native_decide` anywhere above changes one of these lines and the build fails. -/
+
+/-- info: 'Fol.eval_iff' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms eval_iff
+
+/-- info: 'Fol.check_iff' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms check_iff
+
+/-- info: 'Fol.satisfiable_of_check' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms satisfiable_of_check
+
+/-- info: 'Fol.check_complete' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms check_complete
+
+/-- info: 'Fol.not_entails_of_check' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms not_entails_of_check
+
+end Fol
diff --git a/lean/Fol/Free.lean b/lean/Fol/Free.lean
new file mode 100644
index 00000000..76df1eb3
--- /dev/null
+++ b/lean/Fol/Free.lean
@@ -0,0 +1,156 @@
+import Fol.Check
+
+/-!
+# What a rejection says when the problem is a set of sentences
+
+`check` evaluates at the single assignment `fun _ => 0`. For ACCEPTANCE that costs nothing:
+`Satisfiable` binds the environment existentially, so `satisfiable_of_check` is already the
+strongest statement available. For REJECTION it costs something real. `check_complete` says only
+that the structure fails some formula UNDER THAT ONE ASSIGNMENT, and for a problem with a free
+variable in it that is genuinely weaker than "this is not a model".
+
+The export in `src/tptp.rs` emits sentences, so the gap is normally empty. It is closed here
+rather than assumed away, because "normally" is not a proof and because the driver has to report
+which of the two sentences it is entitled to.
+
+`holds_congr` is the coincidence lemma: satisfaction depends only on the free variables. The two
+consequences are what the driver quotes. `check_complete_closed` upgrades a rejection from "not a
+model under the checked assignment" to "not a model under ANY assignment".
+`holds_everywhere_of_check` does the same for acceptance, which matters to nothing in the theorem
+but makes the accepted verdict quotable without a footnote.
+
+Every result here is `[propext, Quot.sound]`, the same as the rest of the layer and strictly
+cleaner than the `[propext, Classical.choice, Quot.sound]` triple the older layers carry. That is a
+measurement, not a preference: the binder cases discharge their side conditions with an explicit
+`simp only [free, List.mem_filter, bne_iff_ne, ne_eq]` rather than a general `simpa`, and the
+general one was what pulled choice in. Pinning the habitual triple here would be looser than the
+truth and would stop catching anything.
+-/
+namespace Fol
+
+theorem Term.eval_congr (M : Struc) (e e' : Env M) (t : Term)
+ (h : ∀ k ∈ t.free, e k = e' k) : t.eval M e = t.eval M e' := by
+ cases t with
+ | var k => exact h k (by simp [Term.free])
+ | const c => rfl
+
+/-- **The coincidence lemma.** Two assignments agreeing on the free variables of `f` agree on
+whether `f` holds. -/
+theorem holds_congr (M : Struc) : ∀ (f : Form) (e e' : Env M),
+ (∀ k ∈ free f, e k = e' k) → (Form.holds M e f ↔ Form.holds M e' f) := by
+ intro f
+ induction f with
+ | app1 p t => intro e e' h; simp [Form.holds, Term.eval_congr M e e' t h]
+ | app2 p t u =>
+ intro e e' h
+ simp only [Form.holds]
+ rw [Term.eval_congr M e e' t (fun k hk => h k (by simp [free, hk])),
+ Term.eval_congr M e e' u (fun k hk => h k (by simp [free, hk]))]
+ | eq t u =>
+ intro e e' h
+ simp only [Form.holds]
+ rw [Term.eval_congr M e e' t (fun k hk => h k (by simp [free, hk])),
+ Term.eval_congr M e e' u (fun k hk => h k (by simp [free, hk]))]
+ | tru => intro e e' h; rfl
+ | fls => intro e e' h; rfl
+ | neg f ih => intro e e' h; simp only [Form.holds]; rw [ih e e' h]
+ | and f g ihf ihg =>
+ intro e e' h
+ simp only [Form.holds]
+ rw [ihf e e' (fun k hk => h k (by simp [free, hk])),
+ ihg e e' (fun k hk => h k (by simp [free, hk]))]
+ | or f g ihf ihg =>
+ intro e e' h
+ simp only [Form.holds]
+ rw [ihf e e' (fun k hk => h k (by simp [free, hk])),
+ ihg e e' (fun k hk => h k (by simp [free, hk]))]
+ | imp f g ihf ihg =>
+ intro e e' h
+ simp only [Form.holds]
+ rw [ihf e e' (fun k hk => h k (by simp [free, hk])),
+ ihg e e' (fun k hk => h k (by simp [free, hk]))]
+ | all n f ih =>
+ intro e e' h
+ simp only [Form.holds]
+ constructor
+ · intro hA d
+ refine (ih (update e n d) (update e' n d) ?_).1 (hA d)
+ intro k hk
+ by_cases hkn : k = n
+ · subst hkn; simp [update]
+ · simp only [update, if_neg hkn]
+ refine h k ?_
+ simp only [free, List.mem_filter, bne_iff_ne, ne_eq]
+ exact ⟨hk, hkn⟩
+ · intro hA d
+ refine (ih (update e n d) (update e' n d) ?_).2 (hA d)
+ intro k hk
+ by_cases hkn : k = n
+ · subst hkn; simp [update]
+ · simp only [update, if_neg hkn]
+ refine h k ?_
+ simp only [free, List.mem_filter, bne_iff_ne, ne_eq]
+ exact ⟨hk, hkn⟩
+ | ex n f ih =>
+ intro e e' h
+ simp only [Form.holds]
+ constructor
+ · rintro ⟨d, hd⟩
+ refine ⟨d, (ih (update e n d) (update e' n d) ?_).1 hd⟩
+ intro k hk
+ by_cases hkn : k = n
+ · subst hkn; simp [update]
+ · simp only [update, if_neg hkn]
+ refine h k ?_
+ simp only [free, List.mem_filter, bne_iff_ne, ne_eq]
+ exact ⟨hk, hkn⟩
+ · rintro ⟨d, hd⟩
+ refine ⟨d, (ih (update e n d) (update e' n d) ?_).2 hd⟩
+ intro k hk
+ by_cases hkn : k = n
+ · subst hkn; simp [update]
+ · simp only [update, if_neg hkn]
+ refine h k ?_
+ simp only [free, List.mem_filter, bne_iff_ne, ne_eq]
+ exact ⟨hk, hkn⟩
+
+/-- A sentence's truth does not depend on the assignment at all. -/
+theorem holds_closed (M : Struc) (f : Form) (hf : free f = []) (e e' : Env M) :
+ Form.holds M e f ↔ Form.holds M e' f :=
+ holds_congr M f e e' (fun k hk => absurd (hf ▸ hk) (by simp))
+
+/-- **The rejection, strengthened.** For a problem of sentences, a rejected structure is not a
+model under ANY assignment. This is the sentence the driver prints when it reports `closed: true`;
+with a free variable anywhere in the problem it reports `closed: false` and the weaker
+`check_complete` is what covers the verdict. -/
+theorem check_complete_closed {n : Nat} {M : FinModel (n+1)} {Γ : List Form}
+ (hc : ∀ g ∈ Γ, free g = []) (h : check M Γ = false) :
+ ∀ e : Nat → Fin (n+1), ¬ (∀ g ∈ Γ, Form.holds M.toStruc e g) := by
+ intro e hm
+ refine check_complete h ?_
+ intro g hg
+ exact (holds_closed M.toStruc g (hc g hg) e (fun _ => 0)).1 (hm g hg)
+
+/-- And the same upgrade for acceptance: a checked structure satisfies the sentences under EVERY
+assignment, not only the one the checker used. -/
+theorem holds_everywhere_of_check {n : Nat} {M : FinModel (n+1)} {Γ : List Form}
+ (hc : ∀ g ∈ Γ, free g = []) (h : check M Γ = true) :
+ ∀ (e : Nat → Fin (n+1)), ∀ g ∈ Γ, Form.holds M.toStruc e g := by
+ intro e g hg
+ exact (holds_closed M.toStruc g (hc g hg) (fun _ => 0) e).1 ((check_iff M Γ).1 h g hg)
+
+/-! ## Axioms, pinned -/
+
+/-- info: 'Fol.holds_congr' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms holds_congr
+
+/-- info: 'Fol.check_complete_closed' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms check_complete_closed
+
+/-- info: 'Fol.holds_everywhere_of_check' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms holds_everywhere_of_check
+
+end Fol
diff --git a/lean/Fol/Parse.lean b/lean/Fol/Parse.lean
new file mode 100644
index 00000000..543132fa
--- /dev/null
+++ b/lean/Fol/Parse.lean
@@ -0,0 +1,367 @@
+import Fol.Witness
+import Std.Data.HashMap
+
+/-!
+# Reading the two files, and binding them to each other
+
+`Fol/Syntax.lean` documents the formats. This module turns the bytes into the `Form` list and the
+`FinModel` the checker is proved about, and recomputes the digest that ties the second file to the
+first.
+
+It is NOT part of the theorem. A parse error is exit 2, never an accepted certificate and never a
+rejected one either: "I could not read the file" and "this is not a model" are different answers
+and the exit codes keep them apart. The same rule as `lean/Dl/Parse.lean`, for the same reason.
+
+## Why the parser is stricter than soundness needs
+
+`FinModel`'s three fields are total, so every symbol has an interpretation whether the file
+mentioned it or not, and `check` validates whatever structure comes out from scratch. Soundness
+therefore survives any amount of silent defaulting. Attribution does not. A model file missing a
+row certifies a DIFFERENT OBJECT from the one the solver produced, and a report that says "the
+solver's model was checked" would then be false while the theorem stayed true. That is the
+mis-attribution shape this project exists to catch, so every route to it is closed here:
+
+* a declared symbol with no row is exit 2, so the defaults are never exercised through this
+ parser at all;
+* a row for a symbol that was never declared is exit 2, so the `decl` lines really are the
+ signature of the model rather than a hint;
+* a second row for the same slot is exit 2, rather than one of the two silently winning;
+* a symbol declared at two arities is exit 2, which is the file-level half of G3.3;
+* a row whose length is not the declared carrier size, and an index outside it, are exit 2. The
+ `Fin` bound is checked HERE, at the boundary, with `if h : i < n + 1 then .ok ⟨i, h⟩`, so nothing
+ downstream can hold an out-of-range element.
+
+## The digest
+
+`problemDigest` is computed over the CANONICAL RE-SERIALISATION of the parsed problem, not over
+the file bytes: the lines `ROLE <TAB> showForm f` in file order, joined with newlines, hashed with
+FNV-1a 64 and printed as 16 lowercase hex digits. Labels are excluded because they are diagnostic.
+Spacing is normalised because `showForm` writes single spaces whatever the input had. The role is
+included because it is what a report reads to decide whether a non-entailment was even asked
+about, and a file whose `goal_negated` had been relabelled `axiom` would otherwise digest the
+same.
+
+There is exactly ONE printer, and the driver's diagnostic line uses it too, so the digest and the
+error message cannot disagree about what a formula says.
+
+**It identifies, it does not commit.** FNV-1a is not a cryptographic hash and the algorithm is
+written out so that two independent implementations can agree, not so that one can be defended
+against someone who controls the file. The mismatch message prints the digest the checker
+computed, which gives away nothing that was not already computable from `problem.tsv` by anyone
+holding it. Anyone needing a commitment should hash the file with something built for that. This
+is decision 0003 item 5, in the same words, for the same reason.
+-/
+namespace Fol.Parse
+
+/-! ## The canonical printer -/
+
+def showTerm : Term → String
+ | .var k => "var " ++ toString k
+ | .const c => "const " ++ c
+
+def showForm : Form → String
+ | .app1 p t => "app1 " ++ p ++ " " ++ showTerm t
+ | .app2 p t u => "app2 " ++ p ++ " " ++ showTerm t ++ " " ++ showTerm u
+ | .eq t u => "eq " ++ showTerm t ++ " " ++ showTerm u
+ | .tru => "tru"
+ | .fls => "fls"
+ | .neg f => "neg " ++ showForm f
+ | .and f g => "and " ++ showForm f ++ " " ++ showForm g
+ | .or f g => "or " ++ showForm f ++ " " ++ showForm g
+ | .imp f g => "imp " ++ showForm f ++ " " ++ showForm g
+ | .all k f => "all " ++ toString k ++ " " ++ showForm f
+ | .ex k f => "ex " ++ toString k ++ " " ++ showForm f
+
+/-! ## The digest -/
+
+/-- FNV-1a, 64 bit, over the UTF-8 bytes. Offset basis 14695981039346656037, prime
+1099511628211, `UInt64` arithmetic wrapping at 2^64. Written out rather than taken from a library
+so that the Rust writer can reproduce it exactly; `String.hash` would not do, being an opaque
+extern with no specification a second implementation could target. -/
+def fnv1a64 (s : String) : UInt64 :=
+ s.toUTF8.foldl (fun h b => (h ^^^ b.toUInt64) * 1099511628211) 14695981039346656037
+
+private def hexDigit (n : Nat) : Char :=
+ if n < 10 then Char.ofNat (48 + n) else Char.ofNat (87 + n)
+
+/-- Sixteen lowercase hex digits, most significant first, zero padded. -/
+def hex16 (x : UInt64) : String :=
+ let n := x.toNat
+ (List.range 16).foldl (fun acc i => acc.push (hexDigit ((n / (16 ^ (15 - i))) % 16))) ""
+
+/-! ## `problem.tsv` -/
+
+/-- One line of `problem.tsv`. `label` is diagnostic and is not digested. -/
+structure Entry where
+ role : String
+ label : String
+ form : Form
+deriving Repr, Inhabited
+
+def canonical (es : List Entry) : String :=
+ String.intercalate "\n" (es.map (fun e => e.role ++ "\t" ++ showForm e.form))
+
+def problemDigest (es : List Entry) : String := hex16 (fnv1a64 (canonical es))
+
+/-- Split on spaces, dropping empties. A symbol contains no space, because the writer in
+`src/tptp.rs` refuses to emit one that does, so this is exact for the token streams it writes. A
+symbol that slipped through with a space in it would split here into two tokens and either fail to
+parse or parse into a DIFFERENT formula, and the digest is what catches the second case. -/
+def tokens (s : String) : List String :=
+ (s.splitOn " ").filter (fun t => !t.isEmpty)
+
+def term? : List String → Option (Term × List String)
+ | "var" :: n :: ts => (n.toNat?).map (fun k => (Term.var k, ts))
+ | "const" :: c :: ts => some (.const c, ts)
+ | _ => none
+
+/-- Prefix parser for a formula. Every constructor has a fixed arity, so no parentheses are needed
+and the grammar is unambiguous. The fuel is the token count, which strictly bounds the recursion
+because each step consumes at least one token. -/
+def form? : Nat → List String → Option (Form × List String)
+ | 0, _ => none
+ | _ + 1, [] => none
+ | fuel + 1, t :: ts =>
+ match t with
+ | "tru" => some (.tru, ts)
+ | "fls" => some (.fls, ts)
+ | "app1" => match ts with
+ | p :: ts' => do
+ let (a, ts2) ← term? ts'
+ some (.app1 p a, ts2)
+ | [] => none
+ | "app2" => match ts with
+ | p :: ts' => do
+ let (a, ts1) ← term? ts'
+ let (b, ts2) ← term? ts1
+ some (.app2 p a b, ts2)
+ | [] => none
+ | "eq" => do
+ let (a, ts1) ← term? ts
+ let (b, ts2) ← term? ts1
+ some (.eq a b, ts2)
+ | "neg" => (form? fuel ts).map (fun p => (.neg p.1, p.2))
+ | "and" => do
+ let (f, ts1) ← form? fuel ts
+ let (g, ts2) ← form? fuel ts1
+ some (.and f g, ts2)
+ | "or" => do
+ let (f, ts1) ← form? fuel ts
+ let (g, ts2) ← form? fuel ts1
+ some (.or f g, ts2)
+ | "imp" => do
+ let (f, ts1) ← form? fuel ts
+ let (g, ts2) ← form? fuel ts1
+ some (.imp f g, ts2)
+ | "all" => match ts with
+ | n :: ts' => do
+ let k ← n.toNat?
+ let (f, ts2) ← form? fuel ts'
+ some (.all k f, ts2)
+ | [] => none
+ | "ex" => match ts with
+ | n :: ts' => do
+ let k ← n.toNat?
+ let (f, ts2) ← form? fuel ts'
+ some (.ex k f, ts2)
+ | [] => none
+ | _ => none
+
+/-- A whole field must be exactly one formula, with nothing left over. -/
+def parseForm (s : String) : Option Form :=
+ let ts := tokens s
+ match form? (ts.length + 1) ts with
+ | some (f, []) => some f
+ | _ => none
+
+/-- Read `problem.tsv`.
+
+An EMPTY formula list is refused. Every structure satisfies the empty list, so a certificate over
+one would report `model_checked` and say nothing at all; an exporter bug that dropped every
+formula would otherwise produce a clean green run, which is precisely the assurance-laundering
+shape decision 0005 section 7 records happening inside this repository already. -/
+def parseProblem (content : String) : Except String (List Entry) := do
+ let mut out : Array Entry := #[]
+ let mut n := 0
+ for line in (content.replace "\r\n" "\n").splitOn "\n" do
+ n := n + 1
+ if line.isEmpty then continue
+ match line.splitOn "\t" with
+ | [role, label, f] =>
+ if role != "axiom" && role != "goal_negated" then
+ throw s!"problem line {n}: the role must be axiom or goal_negated, not {role}"
+ match parseForm f with
+ | some form => out := out.push { role := role, label := label, form := form }
+ | none => throw s!"problem line {n}: not a well-formed formula"
+ | _ => throw s!"problem line {n}: expected three tab-separated fields"
+ if out.isEmpty then
+ throw "the problem carries no formulas; every structure satisfies an empty problem, so a certificate over one would say nothing"
+ return out.toList
+
+/-! ## `model.tsv` -/
+
+/-- The header of a model file: everything that is not a table row. -/
+structure Header where
+ d1 : Array Sym := #[]
+ d2 : Array Sym := #[]
+ dc : Array Sym := #[]
+ card : Option Nat := none
+ digest : Option String := none
+ source : String := "hand"
+ search : String := ""
+deriving Inhabited
+
+/-- Pass one. Reads the declarations, so row order and declaration order are both irrelevant. -/
+def readHeader (lines : List String) : Except String Header := do
+ let mut h : Header := {}
+ let mut n := 0
+ for line in lines do
+ n := n + 1
+ if line.isEmpty then continue
+ match line.splitOn "\t" with
+ | ["domain", k] =>
+ if h.card.isSome then throw s!"model line {n}: a second domain line"
+ match k.toNat? with
+ | none => throw s!"model line {n}: {k} is not a carrier size"
+ | some c => h := { h with card := some c }
+ | ["problem", d] =>
+ if h.digest.isSome then throw s!"model line {n}: a second problem digest"
+ h := { h with digest := some d }
+ | ["source", s] => h := { h with source := s }
+ | ["cardinality_search", s] => h := { h with search := s }
+ | ["decl1", s] =>
+ if h.d1.contains s then throw s!"model line {n}: {s} is declared unary twice"
+ if h.d2.contains s then throw s!"model line {n}: {s} is declared at two arities"
+ h := { h with d1 := h.d1.push s }
+ | ["decl2", s] =>
+ if h.d2.contains s then throw s!"model line {n}: {s} is declared binary twice"
+ if h.d1.contains s then throw s!"model line {n}: {s} is declared at two arities"
+ h := { h with d2 := h.d2.push s }
+ | ["declc", s] =>
+ if h.dc.contains s then throw s!"model line {n}: {s} is declared a constant twice"
+ h := { h with dc := h.dc.push s }
+ | ["p1", _, _] => pure ()
+ | ["p2", _, _, _] => pure ()
+ | ["const", _, _] => pure ()
+ | _ => throw s!"model line {n}: not a well-formed model line"
+ return h
+
+/-- The lookup tables a `FinModel` closes over. Hash tables rather than association lists, so a
+symbol lookup costs one hash rather than a scan of the file; that is a representation choice
+inside the parser and `Fol/Semantics.lean` only ever sees the functions. -/
+structure Tables (n : Nat) where
+ u : Std.HashMap Sym (Array Bool) := ∅
+ b : Std.HashMap (Sym × Nat) (Array Bool) := ∅
+ k : Std.HashMap Sym (Fin n) := ∅
+
+def Tables.toModel {n : Nat} (t : Tables (n+1)) : FinModel (n+1) where
+ p1 := fun p x => (t.u.getD p #[]).getD x.val false
+ p2 := fun r x y => (t.b.getD (r, x.val) #[]).getD y.val false
+ const := fun c => t.k.getD c 0
+
+/-- A bit row of exactly `n` characters, each `0` or `1`. -/
+def bits (n : Nat) (s : String) : Except String (Array Bool) := do
+ let cs := s.toList
+ if cs.length != n then
+ throw s!"a table row has {cs.length} bits, the declared carrier is {n}"
+ let mut out : Array Bool := #[]
+ for c in cs do
+ if c == '1' then out := out.push true
+ else if c == '0' then out := out.push false
+ else throw s!"a table row contains {c}, which is neither 0 nor 1"
+ return out
+
+/-- An index inside the declared carrier. -/
+def idx (n : Nat) (s : String) : Except String (Fin (n+1)) :=
+ match s.toNat? with
+ | none => throw s!"{s} is not a carrier index"
+ | some i =>
+ if h : i < n + 1 then .ok ⟨i, h⟩
+ else throw s!"index {i} is outside the declared carrier of {n+1}"
+
+/-- The result of reading `model.tsv`. The carrier size is DATA, so the boundary carries it. -/
+structure ParsedModel where
+ n : Nat
+ model : FinModel (n+1)
+ decl1 : List Sym
+ decl2 : List Sym
+ declc : List Sym
+ digest : String
+ source : String
+ search : String
+
+def parseModel (content : String) : Except String ParsedModel := do
+ let lines := (content.replace "\r\n" "\n").splitOn "\n"
+ let h ← readHeader lines
+ let digest ← match h.digest with
+ | none => throw "the model carries no problem digest, so nothing binds it to a problem"
+ | some d => pure d
+ match h.card with
+ | none => throw "the model declares no carrier size"
+ | some 0 =>
+ throw "the model declares an empty carrier; a first-order structure cannot have one"
+ | some (n+1) =>
+ let mut t : Tables (n+1) := {}
+ let mut ln := 0
+ for line in lines do
+ ln := ln + 1
+ if line.isEmpty then continue
+ match line.splitOn "\t" with
+ | ["p1", s, row] =>
+ if !h.d1.contains s then
+ throw s!"model line {ln}: a unary row for {s}, which is not declared unary"
+ if t.u.contains s then throw s!"model line {ln}: a second unary row for {s}"
+ t := { t with u := t.u.insert s (← bits (n+1) row) }
+ | ["p2", s, i, row] =>
+ if !h.d2.contains s then
+ throw s!"model line {ln}: a binary row for {s}, which is not declared binary"
+ let j ← idx n i
+ if t.b.contains (s, j.val) then
+ throw s!"model line {ln}: a second binary row for {s} at {j.val}"
+ t := { t with b := t.b.insert (s, j.val) (← bits (n+1) row) }
+ | ["const", s, i] =>
+ if !h.dc.contains s then
+ throw s!"model line {ln}: a denotation for {s}, which is not declared a constant"
+ if t.k.contains s then throw s!"model line {ln}: a second denotation for {s}"
+ let j ← idx n i
+ t := { t with k := t.k.insert s j }
+ | _ => pure ()
+ -- Completeness. Without these the totality of `FinModel` would quietly fill the gaps and the
+ -- object certified would not be the object the file describes.
+ for s in h.d1 do
+ if !t.u.contains s then throw s!"{s} is declared unary and has no row"
+ for s in h.d2 do
+ for i in [0:n+1] do
+ if !t.b.contains (s, i) then throw s!"{s} is declared binary and has no row {i}"
+ for s in h.dc do
+ if !t.k.contains s then throw s!"{s} is declared a constant and has no denotation"
+ return { n := n, model := t.toModel, decl1 := h.d1.toList, decl2 := h.d2.toList,
+ declc := h.dc.toList, digest := digest, source := h.source, search := h.search }
+
+/-! ## The worked example, pinned
+
+`Fol/Syntax.lean` documents the format with a worked example and quotes its digest. That digest is
+the value measured below, so a change to `showForm`, to `canonical` or to the hash fails the build
+here rather than drifting silently away from the format the Rust writer has to target.
+
+`#guard` evaluates at elaboration time and proves nothing: this is boundary machinery, outside the
+theorem, exactly like the rest of this file. What it buys is that the documented format and the
+implemented one cannot come apart without somebody noticing. -/
+
+private def workedProblem : String :=
+ "axiom\tbackground_1\tall 0 neg and app1 thing var 0 app1 lit var 0\n" ++
+ "axiom\tind_typing_1\tapp1 thing const i:a\n" ++
+ "axiom\towl_1_subClassOf\tall 0 imp app1 c:Person var 0 ex 1 and app2 op:worksFor var 0 var 1 app1 c:Company var 1\n" ++
+ "axiom\towl_2_classAssertion\tapp1 c:Person const i:a\n" ++
+ "goal_negated\tgoal_classAssertion\tneg app1 c:Company const i:a\n"
+
+#guard (parseProblem workedProblem).toOption.map problemDigest == some "4403d8aaa0c422f7"
+
+/-! And the round trip: the canonical printer and the parser agree, so a problem file written by
+the Rust `checkfmt` printer and read back here is the same formula list. Whitespace in the input
+is normalised away by `showForm`, which is why the digest is taken over this rather than over the
+bytes. -/
+#guard ((parseProblem workedProblem).toOption.map (fun es =>
+ es.all (fun e => parseForm (showForm e.form) == some e.form))) == some true
+
+end Fol.Parse
diff --git a/lean/Fol/Semantics.lean b/lean/Fol/Semantics.lean
new file mode 100644
index 00000000..497b809c
--- /dev/null
+++ b/lean/Fol/Semantics.lean
@@ -0,0 +1,90 @@
+import Fol.Syntax
+
+/-!
+# Satisfaction
+
+The standard Tarskian semantics of the fragment, transcribed from `OwlLean/FOL/Basic.lean` in the
+sibling project `owl-lean` clause for clause and monomorphised at `Sym`. Nothing in this file
+computes; `Fol/Check.lean` carries the decision procedure and the proof that it agrees with what
+is written here.
+
+Two points a reader should check rather than take on trust.
+
+**Why there is no well-formedness predicate.** `lean/Dl/Semantics.lean` carries `WellFormed` with
+four clauses and every theorem there carries it as a hypothesis, because a `Dl.Interp` has a
+carrier given as a LIST and extension maps that are total on `String`, so an extension can place
+elements outside the carrier and `∃R.C` enumerates a successor list rather than the carrier. None
+of that happens here. `Struc.Dom` is a TYPE, every quantifier ranges over that type, and atoms are
+only ever tested, never enumerated. There is nothing outside the carrier to check. Copying
+`Dl.WellFormed` into this layer would not be a shortcut, it would be a defect: `check_complete`
+would then reject structures that are genuine models. This is the same observation from the other
+side as `Dl/Syntax.lean`'s own docstring, which says that without `WellFormed` its statement
+"would be much weaker than it looks".
+
+**Non-emptiness is load-bearing and is carried in the structure.** `Struc.nonempty` is a field, not
+a hypothesis, because a first-order structure with an empty carrier is not a structure: with one,
+`∀x.⊥` would be true and "satisfiable" would mean nothing. `Fol/Witness.lean` proves
+`all_false_is_unsatisfiable` from that field, which is how the layer demonstrates the field is
+doing work rather than decorating.
+
+**A deviation here is the one edit that silently unhooks the layer from `OwlLean.adequacy`.** The
+OWL-level reading of a certified non-entailment rides on `Entails` below being the `Entails` that
+theorem is stated about. That transcription is pinned by tests and is NOT proved; it is about
+twenty lines of inductive types and their semantics rather than a translation, so it is a far
+smaller claim than `src/tptp.rs`'s, and `docs/decisions/0006` says so rather than letting the two
+sound equally load-bearing.
+-/
+namespace Fol
+
+/-- A first-order structure: a non-empty carrier, an interpretation for each unary predicate
+symbol, each binary predicate symbol, and each constant.
+
+`c : Sym → Dom` is TOTAL into the carrier. That is not a convenience. In a design where a
+constant's denotation is a lookup with a default, the default has to live somewhere, and a default
+OUTSIDE the carrier makes `{∀x. P(x), ¬P(c)}` check green. Here that state is not representable. -/
+structure Struc where
+ Dom : Type
+ nonempty : Nonempty Dom
+ p1 : Sym → Dom → Prop
+ p2 : Sym → Dom → Dom → Prop
+ c : Sym → Dom
+
+/-- A variable assignment. -/
+abbrev Env (M : Struc) := Nat → M.Dom
+
+/-- `e` with `n` rebound to `d`. -/
+def update {M : Struc} (e : Env M) (n : Nat) (d : M.Dom) : Env M :=
+ fun m => if m = n then d else e m
+
+/-- What a term denotes. -/
+def Term.eval (M : Struc) (e : Env M) : Term → M.Dom
+ | .var n => e n
+ | .const k => M.c k
+
+/-- Satisfaction. -/
+def Form.holds (M : Struc) : Env M → Form → Prop
+ | e, .app1 p t => M.p1 p (t.eval M e)
+ | e, .app2 p t u => M.p2 p (t.eval M e) (u.eval M e)
+ | e, .eq t u => t.eval M e = u.eval M e
+ | _, .tru => True
+ | _, .fls => False
+ | e, .neg f => ¬ f.holds M e
+ | e, .and f g => f.holds M e ∧ g.holds M e
+ | e, .or f g => f.holds M e ∨ g.holds M e
+ | e, .imp f g => f.holds M e → g.holds M e
+ | e, .all n f => ∀ d, f.holds M (update e n d)
+ | e, .ex n f => ∃ d, f.holds M (update e n d)
+
+/-- `Γ` has a model. This is the conclusion a certificate buys: not "the solver returned sat", but
+the existence of a structure, exhibited. -/
+def Satisfiable (Γ : List Form) : Prop :=
+ ∃ (M : Struc) (e : Env M), ∀ g ∈ Γ, Form.holds M e g
+
+/-- `Γ` entails `f`: true in every structure and every assignment satisfying `Γ`.
+
+This is the relation `OwlLean.adequacy` is stated about, and the relation a certified countermodel
+refutes. -/
+def Entails (Γ : List Form) (f : Form) : Prop :=
+ ∀ (M : Struc) (e : Env M), (∀ g ∈ Γ, Form.holds M e g) → Form.holds M e f
+
+end Fol
diff --git a/lean/Fol/Syntax.lean b/lean/Fol/Syntax.lean
new file mode 100644
index 00000000..7bf07bcf
--- /dev/null
+++ b/lean/Fol/Syntax.lean
@@ -0,0 +1,310 @@
+/-!
+# The fragment, the finite model, and the two file formats
+
+This development certifies the SATISFIABILITY answers of an external SAT/SMT solver or finite
+model finder run over the first-order export in `src/tptp.rs`. When Z3 or Mace4 says a problem
+is satisfiable and hands back the finite structure it built, `Fol/Check.lean` decides whether
+that structure really satisfies every formula of the problem, and `Fol.satisfiable_of_check`
+turns an accepted structure into `∃ M e, ∀ g ∈ Γ, holds M e g`.
+
+The UNSATISFIABILITY answer is not certified and cannot be. Checking a superposition or CDCL(T)
+refutation needs a verified calculus with unification and theory lemmas, which does not exist in
+core Lean; decision 0005 rules that an automated prover's verdict is an oracle opinion and this
+layer does not disturb that ruling. What it adds is the observation that the two directions are
+not symmetric. A refutation is a proof object nobody here can replay. A MODEL is a finite object,
+checking a closed formula against a finite structure is decidable, and a verified evaluator for
+that is the few hundred lines in `Fol/Check.lean`. So one half of the SAT/SMT family can be
+certified while the other half stays an oracle, and the vocabulary in `docs/decisions/0006` keeps
+the two apart in every report.
+
+## The monomorphisation, and the one obligation it carries
+
+`OwlLean.FOL.Form` in the sibling project `owl-lean` is parameterised by a signature `FSig` with
+three sorts of symbol: `P1` unary predicates, `P2` binary predicates and `Const` constants. The
+OWL instance sets `P1 := OwlP1`, a four-arm disjoint sum (`Cls`, `Dt`, `Thing`, `Lit`), and
+`P2 := OwlP2`, a two-arm sum (`Op`, `Dp`). Here all of that is monomorphised at `Sym := String`,
+because a checker has to read symbols off a file and a file carries strings.
+
+That flattening is sound only if the string map is INJECTIVE on those arms. If a class IRI and a
+datatype IRI with the same spelling both mapped to the bare IRI, they would become one predicate
+and a model could satisfy a problem the ontology does not. The injectivity is supplied by the
+prefixes `src/tptp.rs` already writes, and it is the reason the checker format keeps them:
+
+```
+OwlP1.Thing -> thing OwlP2.Op r -> op:r
+OwlP1.Lit -> lit OwlP2.Dp d -> dp:d
+OwlP1.Cls a -> c:a FSig.Const a -> i:a
+OwlP1.Dt d -> d:d
+```
+
+`thing` and `lit` carry no colon and every other arm carries its own prefix, so the seven images
+are pairwise disjoint whatever the IRIs are. The unary and binary symbol spaces are separate
+fields of `FinModel`, so `c:X` as a unary predicate and `op:X` as a binary one could not collide
+even without the prefixes; the prefixes are what stop `c:X` colliding with `d:X`.
+
+## What is in the fragment
+
+Everything `OwlLean.FOL.Form` has: unary and binary atoms, equality, the two truth constants,
+negation, conjunction, disjunction, implication, and both quantifiers with an explicit `Nat`
+binder. Nothing is normalised on the way in. `owl-lean` uses NAMED variables rather than de Bruijn
+indices precisely so that freshness is a proof obligation rather than a silent convention, and a
+checker that renumbered would be checking a different formula from the one the adequacy theorem is
+about.
+
+## What is NOT in the fragment, and is therefore never read
+
+* Function symbols of arity above zero. The translation emits none, and the certificate format has
+ no syntax for one. Mace4 clausifies and Skolemises, so its models DO interpret symbols like
+ `f1(_)` and `c1`; those are dropped on the way in, which is taking the reduct of its structure.
+ That needs no lemma here, because the checker re-evaluates the original formulas and they cannot
+ mention a symbol the translation never emitted.
+* Predicates of arity three or above, and sorts. `FSig` has exactly `P1` and `P2`.
+* Anything about UNSATISFIABILITY, in any direction. See the top of this file.
+
+## `problem.tsv`
+
+One formula per line, three tab-separated fields.
+
+```
+ROLE <TAB> LABEL <TAB> FORMULA
+```
+
+`ROLE` is `axiom` or `goal_negated` and nothing else. `goal_negated` marks the NEGATION of the
+conjecture: a countermodel to `Γ ⊨ φ` is a model of `Γ ∪ {¬φ}`, so the file carries `¬φ` and the
+checker never negates anything itself. `LABEL` is the emitter's own label (`background_1`,
+`ind_typing_3`, `owl_7_subClassOf`, `goal_classAssertion`) and is DIAGNOSTIC ONLY: it is not part
+of the digest and nothing in the theorem looks at it. `FORMULA` is a space-separated prefix token
+stream with no parentheses, unambiguous because every constructor has a fixed arity:
+
+```
+F ::= tru | fls | app1 SYM T | app2 SYM T T | eq T T
+ | neg F | and F F | or F F | imp F F | all N F | ex N F
+T ::= var N | const SYM
+```
+
+`N` is a decimal natural. `SYM` is one of the seven images above and must contain no space, tab,
+carriage return or newline: the writer in `src/tptp.rs` returns an error rather than emit one that
+does, because a symbol with a space in it re-parses as a DIFFERENT formula and a symbol with a tab
+in it re-parses as a different set of fields. The digest below is the second line of defence
+against exactly that.
+
+## `model.tsv`
+
+Dense rows, so a carrier of 20 with 300 symbols is a few hundred lines rather than 120,000.
+
+```
+domain <TAB> N N >= 1. N = 0 is exit 2, not exit 1
+problem <TAB> HEX 16 lowercase hex digits, see below
+source <TAB> z3|mace4|hand provenance. UNTRUSTED, reporting only
+decl1 <TAB> SYM SYM is interpreted as a unary predicate
+decl2 <TAB> SYM SYM is interpreted as a binary predicate
+declc <TAB> SYM SYM is interpreted as a constant
+p1 <TAB> SYM <TAB> BITS |BITS| = N. BITS[i] = '1' iff SYM holds of i
+p2 <TAB> SYM <TAB> i <TAB> BITS row i of the binary table
+const <TAB> SYM <TAB> i 0 <= i < N
+cardinality_search <TAB> k1,k2,... sizes tried. reporting only
+```
+
+Carrier elements are the integers `0 .. N-1`, which is what Mace4 prints and what `Fin N` is, so
+ingesting a Mace4 `interpretation(N, ...)` block renames nothing. Row order is irrelevant: the
+parser reads the declarations in one pass and the tables in a second.
+
+`domain` and `problem` are REQUIRED, and a second line of either is exit 2. `source` defaults to
+`hand` and `cardinality_search` to the empty string; both are echoed into the report and nothing
+checks them. A binary symbol needs all `N` of its `p2` rows, one per source element, in any order.
+Declaring a symbol the problem never mentions is allowed and harmless: the coverage gate checks
+that the problem's symbols are all declared, not the reverse, so a writer may emit the solver's
+whole signature without pruning it.
+
+The parser is STRICT, and deliberately stricter than soundness requires. A declared symbol with no
+row is exit 2, a row for an undeclared symbol is exit 2, a second row for the same slot is exit 2,
+a symbol declared at two arities is exit 2, a row whose length is not `N` is exit 2, and an index
+outside `0 .. N-1` is exit 2. `FinModel`'s three fields are TOTAL, so a missing row would default
+rather than fail, and a defaulted structure is still a structure: soundness would survive it. What
+would not survive is the attribution, because the object certified would not be the object the
+solver produced. The strictness is there for that, and `Fol/Check.lean` states plainly which of
+the two it is defending.
+
+## The digest, and what it is not
+
+`model.tsv`'s `problem` line carries a digest of the problem the solver was actually given, and
+`Fol/Parse.lean` recomputes it from `problem.tsv` and refuses on a mismatch. It is computed over
+the CANONICAL RE-SERIALISATION of the parsed formula list rather than over the file bytes: the
+lines `ROLE <TAB> showForm f`, in file order, joined with newlines, then FNV-1a 64 over the UTF-8
+of that, printed as 16 lowercase hex digits. Labels are excluded, spacing is normalised, and the
+role is included because it is what a report reads to decide whether a non-entailment was even
+asked about.
+
+It identifies, it does not commit. FNV-1a is not a cryptographic hash and the algorithm is written
+out here so that two independent implementations can agree, not so that one can be defended
+against someone who controls the file. Anyone needing that should hash the file with something
+that is built for it. This is decision 0003 item 5, in the same words, for the same reason.
+
+## A worked example
+
+The problem: nothing is both a thing and a literal, `a` is a thing, every `Person` works for some
+`Company`, and `a` is a `Person`. The goal `Company(a)`, negated, so that a model of the whole file
+is a countermodel to the entailment.
+
+`problem.tsv`, with a literal tab between each pair of fields
+
+```
+axiom background_1 all 0 neg and app1 thing var 0 app1 lit var 0
+axiom ind_typing_1 app1 thing const i:a
+axiom owl_1_subClassOf all 0 imp app1 c:Person var 0 ex 1 and app2 op:worksFor var 0 var 1 app1 c:Company var 1
+axiom owl_2_classAssertion app1 c:Person const i:a
+goal_negated goal_classAssertion neg app1 c:Company const i:a
+```
+
+`model.tsv`, a two-element carrier with `a` at 0 and its employer at 1
+
+```
+domain 2
+problem 4403d8aaa0c422f7
+source z3
+decl1 thing
+decl1 lit
+decl1 c:Person
+decl1 c:Company
+decl2 op:worksFor
+declc i:a
+p1 thing 11
+p1 lit 00
+p1 c:Person 10
+p1 c:Company 01
+p2 op:worksFor 0 01
+p2 op:worksFor 1 00
+const i:a 0
+cardinality_search 1,2
+```
+
+`oo-folmodel problem.tsv model.tsv` on those two files, measured:
+
+```
+{"verdict":"model_checked","formulas":5,"domain":2,"closed":true,
+ "goal_negated_present":true,"source":"z3","cardinality_search":"1,2",
+ "problem_digest":"4403d8aaa0c422f7","theorem":"Fol.satisfiable_of_check",
+ "non_entailment_theorem":"Fol.not_entails_of_check"}
+```
+
+(printed on one line; wrapped here to fit). Exit code 0. Delete the `op:worksFor` edge from row 0
+and the same command prints
+
+```
+{"verdict":"rejected", ... ,"theorem":"Fol.check_complete_closed","first_rejected":2,
+ "label":"owl_1_subClassOf","role":"axiom","formula":"all 0 imp app1 c:Person var 0 ex 1 and
+ app2 op:worksFor var 0 var 1 app1 c:Company var 1"}
+```
+
+with exit code 1.
+
+The digest `4403d8aaa0c422f7` is the measured value for that exact five-line `problem.tsv`, and
+`Fol/Parse.lean` pins it with a `#guard`, so a change to `showForm` or to the hash fails the build
+rather than drifting away from the format the Rust writer targets.
+
+## The verdict vocabulary this file does NOT own
+
+`oo-folmodel` answers one question: does this structure satisfy this problem. The five fields a
+report carries, and the four solver verdicts that must never be collapsed into each other, are in
+`docs/decisions/0006`. Two of them matter enough to repeat here. `unsatisfiable_oracle` may be
+produced ONLY by a run whose emitted problem carried no cardinality constraint of any kind; a
+bounded run's `unsat` is `no_model_up_to_size_k` and is not unsatisfiability. And a solver that
+answers `sat` whose model this checker then REJECTS is `satisfiable_oracle` with a
+`model_not_confirmed` note, never `rejected` as though the ontology were at fault.
+-/
+namespace Fol
+
+/-- A predicate or constant symbol, already prefixed by `src/tptp.rs` so that the four arms of
+`OwlLean.OwlP1`, the two of `OwlLean.OwlP2` and the individual names stay disjoint. The checker
+never looks inside one: two symbols are the same when the strings are the same. -/
+abbrev Sym := String
+
+/-- A first-order term. Mirrors `OwlLean.FOL.Term`: a `Nat`-indexed variable or a constant.
+There are no function symbols of positive arity, here or in the translation. -/
+inductive Term where
+ | var : Nat → Term
+ | const : Sym → Term
+deriving DecidableEq, Repr, Inhabited
+
+/-- A first-order formula. Mirrors `OwlLean.FOL.Form` constructor for constructor, including the
+explicit `Nat` on each binder. -/
+inductive Form where
+ | app1 : Sym → Term → Form
+ | app2 : Sym → Term → Term → Form
+ | eq : Term → Term → Form
+ | tru : Form
+ | fls : Form
+ | neg : Form → Form
+ | and : Form → Form → Form
+ | or : Form → Form → Form
+ | imp : Form → Form → Form
+ | all : Nat → Form → Form
+ | ex : Nat → Form → Form
+deriving DecidableEq, Repr, Inhabited
+
+/-! ## The vocabulary a problem mentions
+
+These four functions collect the symbols a formula uses. They exist for the COVERAGE gate in
+`Fol/Check.lean`, which is an attribution gate and not a soundness gate: `FinModel`'s fields are
+total, so a structure interprets every symbol whether the file mentioned it or not, and the
+soundness theorem needs none of this. What the gate buys is that the object certified is the
+object the solver described. -/
+
+/-- The constants occurring in a term. -/
+def Term.consts : Term → List Sym
+ | .var _ => []
+ | .const c => [c]
+
+/-- The unary predicate symbols occurring in a formula. -/
+def p1Syms : Form → List Sym
+ | .app1 p _ => [p]
+ | .app2 .. | .eq .. | .tru | .fls => []
+ | .neg f | .all _ f | .ex _ f => p1Syms f
+ | .and f g | .or f g | .imp f g => p1Syms f ++ p1Syms g
+
+/-- The binary predicate symbols occurring in a formula. -/
+def p2Syms : Form → List Sym
+ | .app2 p _ _ => [p]
+ | .app1 .. | .eq .. | .tru | .fls => []
+ | .neg f | .all _ f | .ex _ f => p2Syms f
+ | .and f g | .or f g | .imp f g => p2Syms f ++ p2Syms g
+
+/-- The constant symbols occurring in a formula. -/
+def constSyms : Form → List Sym
+ | .app1 _ t => t.consts
+ | .app2 _ t u | .eq t u => t.consts ++ u.consts
+ | .tru | .fls => []
+ | .neg f | .all _ f | .ex _ f => constSyms f
+ | .and f g | .or f g | .imp f g => constSyms f ++ constSyms g
+
+/-! ## Free variables
+
+`Fol/Check.lean` evaluates at the constant environment `fun _ => 0`. For ACCEPTANCE that costs
+nothing, because `Satisfiable` binds the environment existentially. For REJECTION it would cost
+something: without the results in `Fol/Free.lean` a rejection would only say "not a model under
+this one assignment". These two functions are what those results are stated with, and the driver
+reports whether the problem is closed so a reader knows which of the two sentences applies. -/
+
+/-- The variables occurring in a term. -/
+def Term.free : Term → List Nat
+ | .var k => [k]
+ | .const _ => []
+
+/-- The variables occurring FREE in a formula.
+
+The binder cases FILTER rather than `erase`, and the difference is not cosmetic. `List.erase`
+removes the first occurrence only, so `free (∀x0. P(x0) ∧ Q(x0))` would come back as `[0]` and
+every formula with a bound variable used twice would be classified as open. Nothing would become
+unsound, because a larger `free` only strengthens the hypothesis of `holds_congr`; what would
+happen is that `check_complete_closed` would stop applying to essentially every real problem and
+the driver would silently print the weaker rejection sentence for ever. The `by decide` in
+`Fol/Witness.lean` that the problem there is a set of sentences is what holds this honest. -/
+def free : Form → List Nat
+ | .app1 _ t => t.free
+ | .app2 _ t u | .eq t u => t.free ++ u.free
+ | .tru | .fls => []
+ | .neg f => free f
+ | .and f g | .or f g | .imp f g => free f ++ free g
+ | .all k f | .ex k f => (free f).filter (fun j => j != k)
+
+end Fol
diff --git a/lean/Fol/Witness.lean b/lean/Fol/Witness.lean
new file mode 100644
index 00000000..fcc486e9
--- /dev/null
+++ b/lean/Fol/Witness.lean
@@ -0,0 +1,272 @@
+import Fol.Free
+
+/-!
+# Witnesses: the checker accepts something, rejects each forgery on its own, and the semantics is
+not trivial
+
+`satisfiable_of_check` would be worth nothing if `check` accepted everything, and `check_complete`
+would be worth nothing if it accepted nothing. This file closes both by construction rather than
+by argument, and closes a third gap as well: that `Satisfiable` is not a predicate that happens to
+hold of every problem.
+
+Every rejection below goes through `check_complete`, so it is the CHECKER'S OWN rejection that is
+being certified rather than an independent argument about the same structure. A file that proved
+these forgeries by hand would be proving something about the mathematics and nothing about the
+gate the driver runs.
+
+The five forgeries are the five ways of lying this format admits.
+
+1. `forged_missing_edge_is_rejected`. A structure that omits what an axiom requires: the
+ `worksFor` edge every `Person` needs is deleted and nothing else is touched.
+2. `all_false_is_rejected` and `all_false_is_unsatisfiable`. The empty carrier. It is
+ UNREPRESENTABLE here, because `FinModel.toStruc` is defined only at `n+1`, so the forgery has
+ no Lean-level form at all; what is proved instead is that non-emptiness is load-bearing, since
+ `∀x.⊥` is rejected by every structure and really has no model. The file-level half is the
+ parser, which refuses `domain 0` with exit 2, demonstrated in `Fol/Parse.lean`.
+3. `forged_arity_is_rejected`. A predicate interpreted at the wrong arity. In `FinModel` the arity
+ is in the TYPE, so arity confusion cannot be a Lean-level error; it is a table-level fault and
+ it is caught twice over. Here `worksFor` is supplied as a unary table, which leaves the binary
+ slot empty and the `false` default rejects. In the parser a `p2` row for a symbol declared
+ unary is exit 2. That double catch is the cleanest argument for the `false` default: its
+ failure mode is rejection.
+4. `an_undeclared_symbol_is_caught`, with `a_full_declaration_passes` so the gate is not a
+ constant. A symbol the problem uses that the model file never declares. This is the ATTRIBUTION
+ gate, not a soundness gate, and `Fol/Check.lean` says so at the definition.
+5. `a_model_of_another_problem_is_rejected`. A perfectly good structure, checked against a problem
+ it was not built for. The file-level half is the digest in `Fol/Parse.lean`.
+
+`employment_does_not_entail_company` is the headline: a machine-checked NON-ENTAILMENT, which is
+the sentence no automated theorem prover in decision 0005 can ever produce.
+
+The names here are short bare strings rather than the prefixed `c:IRI` spellings the emitter
+writes. The checker never looks inside a symbol, so nothing depends on the difference, and short
+names keep the kernel's evaluation of these `decide` calls quick. `Fol/Parse.lean` carries the
+digest pin over the real prefixed spellings, so the two conventions are both exercised.
+-/
+namespace Fol
+
+/-! ## An ontology about employment -/
+
+private def v (k : Nat) : Term := .var k
+private def a : Term := .const "a"
+
+/-- Nothing is both a thing and a literal, something is a thing, `a` is a thing, every `Person`
+works for some `Company`, and `a` is a `Person`. The first three lines are the shape
+`OwlLean.background` and `OwlLean.indAxioms` emit; the last two are a translated `subClassOf` with
+a nested existential and a class assertion. -/
+def employment : List Form :=
+ [ .all 0 (.neg (.and (.app1 "thing" (v 0)) (.app1 "lit" (v 0)))),
+ .ex 0 (.app1 "thing" (v 0)),
+ .app1 "thing" a,
+ .all 0 (.imp (.app1 "Person" (v 0))
+ (.ex 1 (.and (.app2 "worksFor" (v 0) (v 1)) (.app1 "Company" (v 1))))),
+ .app1 "Person" a ]
+
+/-- Two elements: `a` at 0 is the person, 1 is the company, and there is one employment edge. -/
+def employmentModel : FinModel 2 where
+ p1 := fun p x =>
+ if p = "thing" then true
+ else if p = "Person" then x == 0
+ else if p = "Company" then x == 1
+ else false
+ p2 := fun r x y => r == "worksFor" && x == 0 && y == 1
+ const := fun _ => 0
+
+/-- **G2, acceptance.** The checker accepts a real structure for a five-formula problem with a
+nested existential under a universal. -/
+theorem employment_is_accepted : check employmentModel employment = true := by decide
+
+/-- **G2, the existence result read off it.** -/
+theorem employment_is_satisfiable : Satisfiable employment :=
+ satisfiable_of_check employment_is_accepted
+
+/-- **G2, non-triviality of the semantics.** The same accepted structure does NOT satisfy
+`Company(a)`. Without this the acceptance above would be consistent with a `holds` that is true of
+everything. -/
+theorem the_model_does_not_satisfy_everything :
+ ¬ Form.holds employmentModel.toStruc (fun _ => (0 : Fin 2)) (.app1 "Company" a) := by
+ intro h
+ exact absurd ((eval_iff employmentModel (.app1 "Company" a) (fun _ => 0)).2 h) (by decide)
+
+/-- A carrier of ONE is legal and is checked, so the layer does not quietly need two elements. -/
+def singleton : FinModel 1 where
+ p1 := fun p _ => p == "thing"
+ p2 := fun _ _ _ => false
+ const := fun _ => 0
+
+theorem a_one_element_model_is_accepted :
+ check singleton [.app1 "thing" a, .ex 0 (.app1 "thing" (v 0))] = true := by decide
+
+theorem a_one_element_model_is_satisfiable :
+ Satisfiable [.app1 "thing" a, .ex 0 (.app1 "thing" (v 0))] :=
+ satisfiable_of_check a_one_element_model_is_accepted
+
+/-! ## G3.1 A structure that omits what an axiom requires -/
+
+/-- The same structure with the employment edge deleted. Everything else is untouched, so the only
+formula it can break is the one that needs the edge. -/
+def forgedNoEdge : FinModel 2 := { employmentModel with p2 := fun _ _ _ => false }
+
+theorem forged_missing_edge_is_rejected :
+ ¬ (∀ g ∈ employment, Form.holds forgedNoEdge.toStruc (fun _ => (0 : Fin 2)) g) :=
+ check_complete (by decide)
+
+/-- And the stronger sentence, because `employment` is a set of SENTENCES: the forgery is not a
+model under ANY assignment, not merely under the one the checker used. -/
+theorem forged_missing_edge_is_rejected_everywhere :
+ ∀ e : Nat → Fin 2, ¬ (∀ g ∈ employment, Form.holds forgedNoEdge.toStruc e g) :=
+ check_complete_closed (by decide) (by decide)
+
+/-! ## G3.2 The empty carrier, and why non-emptiness is load-bearing -/
+
+/-- No finite structure of this layer satisfies `∀x.⊥`, whatever its carrier and whatever it
+interprets. An empty carrier would satisfy it, which is exactly why `FinModel.toStruc` is defined
+only at `n+1` and why `Struc` carries `nonempty` as a field. -/
+theorem all_false_is_rejected (n : Nat) (M : FinModel (n+1)) :
+ check M [.all 0 .fls] = false := by
+ simp [check, eval, List.finRange_succ]
+
+/-- And the semantic fact behind it: `∀x.⊥` has no model at all. The proof is not a `decide`,
+because "no structure whatsoever" is not a finite check. It is the one-line argument, and it uses
+`Struc.nonempty`, which is what makes that field do work rather than decorate. -/
+theorem all_false_is_unsatisfiable : ¬ Satisfiable [Form.all 0 .fls] := by
+ rintro ⟨M, e, h⟩
+ have hall := h (.all 0 .fls) (by simp)
+ obtain ⟨d⟩ := M.nonempty
+ exact hall d
+
+/-- `Satisfiable` is not the trivial predicate. -/
+theorem not_everything_is_satisfiable : ¬ Satisfiable [Form.fls] := by
+ rintro ⟨M, e, h⟩
+ exact h .fls (by simp)
+
+/-! ## G3.3 A predicate interpreted at the wrong arity -/
+
+/-- `worksFor` supplied as a UNARY table. The binary slot is then empty, the `false` default makes
+the atom false wherever the problem uses it as a binary predicate, and the structure is rejected.
+The parser refuses this file shape outright, so the fault is caught at both levels. -/
+def forgedArity : FinModel 2 where
+ p1 := fun p x =>
+ if p = "thing" then true
+ else if p = "Person" then x == 0
+ else if p = "Company" then x == 1
+ else if p = "worksFor" then x == 0
+ else false
+ p2 := fun _ _ _ => false
+ const := fun _ => 0
+
+theorem forged_arity_is_rejected :
+ ¬ (∀ g ∈ employment, Form.holds forgedArity.toStruc (fun _ => (0 : Fin 2)) g) :=
+ check_complete (by decide)
+
+/-! ## G3.4 A symbol the problem uses that the model never declares
+
+The coverage gate, which is about ATTRIBUTION and not about soundness. `Company` is missing from
+the declared unary symbols, so the gate fails; adding it makes the gate pass, so the gate is not a
+constant. -/
+
+theorem an_undeclared_symbol_is_caught :
+ covers ["thing", "lit", "Person"] ["worksFor"] ["a"] employment = false := by decide
+
+theorem a_full_declaration_passes :
+ covers ["thing", "lit", "Person", "Company"] ["worksFor"] ["a"] employment = true := by decide
+
+/-! ## G3.5 A structure checked against a problem it was not built for -/
+
+/-- A different problem entirely, and an inconsistent one. `employmentModel` is a perfectly good
+structure and it is rejected here, because being a model is a relation between a structure and a
+problem rather than a property of the structure. The file-level defence is the digest. -/
+def otherProblem : List Form := [.app1 "Person" a, .neg (.app1 "Person" a)]
+
+theorem a_model_of_another_problem_is_rejected :
+ ¬ (∀ g ∈ otherProblem, Form.holds employmentModel.toStruc (fun _ => (0 : Fin 2)) g) :=
+ check_complete (by decide)
+
+/-! ## The headline: a machine-checked non-entailment -/
+
+/-- **The sentence this layer exists to be able to say.** The employment theory does not entail
+`Company(a)`, and the proof is a finite structure that was checked rather than a prover's opinion
+that was believed.
+
+Decision 0005 rules that an automated theorem prover's `SZS status Theorem` is an oracle opinion,
+because a superposition refutation cannot be replayed in core Lean. This is the other direction,
+and it is certified. -/
+theorem employment_does_not_entail_company :
+ ¬ Entails employment (.app1 "Company" a) :=
+ not_entails_of_check (M := employmentModel) (by decide)
+
+/-! ## Scale
+
+The kernel's `decide`, not `native_decide`, which would add `Lean.ofReduceBool` to the footprint
+and fail the audit. A carrier of 8 at quantifier depth 3 is 512 evaluation points per formula and
+compiles in well under a second. If a witness ever gets slow, shrink the witness rather than
+change the tactic. -/
+
+def big : FinModel 8 where
+ p1 := fun p x => p == "thing" || (p == "P" && x.val % 2 == 0)
+ p2 := fun r x y => r == "r" && (x.val + 1) % 8 == y.val
+ const := fun _ => 0
+
+theorem big_is_accepted :
+ check big [.all 0 (.all 1 (.ex 2 (.or (.app2 "r" (.var 0) (.var 2))
+ (.app2 "r" (.var 1) (.var 2)))))] = true := by decide
+
+/-! ## Axioms, pinned -/
+
+/-- info: 'Fol.employment_is_satisfiable' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms employment_is_satisfiable
+
+/-- info: 'Fol.the_model_does_not_satisfy_everything' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms the_model_does_not_satisfy_everything
+
+/-- info: 'Fol.a_one_element_model_is_satisfiable' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms a_one_element_model_is_satisfiable
+
+/-- info: 'Fol.forged_missing_edge_is_rejected' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms forged_missing_edge_is_rejected
+
+/-- info: 'Fol.forged_missing_edge_is_rejected_everywhere' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms forged_missing_edge_is_rejected_everywhere
+
+/-- info: 'Fol.all_false_is_rejected' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms all_false_is_rejected
+
+/-- info: 'Fol.all_false_is_unsatisfiable' depends on axioms: [propext] -/
+#guard_msgs in
+#print axioms all_false_is_unsatisfiable
+
+/-- info: 'Fol.not_everything_is_satisfiable' depends on axioms: [propext] -/
+#guard_msgs in
+#print axioms not_everything_is_satisfiable
+
+/-- info: 'Fol.forged_arity_is_rejected' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms forged_arity_is_rejected
+
+/-- info: 'Fol.an_undeclared_symbol_is_caught' does not depend on any axioms -/
+#guard_msgs in
+#print axioms an_undeclared_symbol_is_caught
+
+/-- info: 'Fol.a_full_declaration_passes' does not depend on any axioms -/
+#guard_msgs in
+#print axioms a_full_declaration_passes
+
+/-- info: 'Fol.a_model_of_another_problem_is_rejected' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms a_model_of_another_problem_is_rejected
+
+/-- info: 'Fol.employment_does_not_entail_company' depends on axioms: [propext, Quot.sound] -/
+#guard_msgs in
+#print axioms employment_does_not_entail_company
+
+/-- info: 'Fol.big_is_accepted' depends on axioms: [propext] -/
+#guard_msgs in
+#print axioms big_is_accepted
+
+end Fol
diff --git a/lean/FolMain.lean b/lean/FolMain.lean
new file mode 100644
index 00000000..6dcd6747
--- /dev/null
+++ b/lean/FolMain.lean
@@ -0,0 +1,165 @@
+import Fol.All
+
+/-!
+`oo-folmodel PROBLEM.tsv MODEL.tsv`
+
+Reads a first-order problem and a finite structure, runs the verified checker, and prints one JSON
+object. The formats are documented in `lean/Fol/Syntax.lean`.
+
+Exit codes, matching the convention `oo-cert` and `oo-dlmodel` use:
+
+* `0` the structure satisfies every formula of the problem. The problem is satisfiable, and the
+ statement covering that is `Fol.satisfiable_of_check`. When the problem carries a `goal_negated`
+ line the same run also covers `Fol.not_entails_of_check`, and the report says which.
+* `1` the certificate is rejected. Three reasons, and they are not the same sentence:
+ `problem_digest_mismatch` means the structure was built for a different problem;
+ `undeclared_symbol` means the model file does not interpret something the problem uses, which is
+ an ATTRIBUTION failure and not a soundness one; otherwise the verified checker rejected the
+ structure, and by `Fol.check_complete` that is a statement about the structure rather than about
+ the checker giving up.
+* `2` a file could not be read or parsed, or the problem carried no formulas. No verdict either
+ way.
+
+What exit 0 does NOT say, and what a reader must not infer from it:
+
+* it says nothing about UNSATISFIABILITY, in any direction. When a solver answers `unsat` no
+ certificate exists and none is checked here. That answer is still "trust the solver". Certifying
+ it needs a verified first-order calculus with unification, which does not exist in core Lean,
+ and decision 0005 rules it an oracle opinion. This layer does not disturb that ruling; it
+ observes that the other direction is not symmetric;
+* it says nothing about a BOUNDED search that found nothing. A solver asked for a model of size at
+ most `k` and answering `unsat` has established `no_model_up_to_size_k`, which is not
+ unsatisfiability and must never be reported with that word. Nothing here produces either verdict;
+* it says nothing about whether `PROBLEM.tsv` is the ontology. The OWL reader and the translation
+ in `src/tptp.rs` are outside the theorem, exactly as the N-Triples parser is outside
+ `Shacl.validate_spec`. What is certified is a relation between the two files. The OWL-level
+ reading rides additionally on `OwlLean.adequacy` and on the Rust-to-Lean correspondence, which
+ decision 0005 item 2 states is pinned by tests and NOT proved, and it carries its own word;
+* the absence of a finite model implies NOTHING. SHIQ lacks the finite model property, so a
+ satisfiable ontology can have only infinite models and will never receive a certificate here.
+ That is a limitation of the method rather than a defect, and it is the honest counterweight to
+ the asymmetry this layer is built on;
+* `source` and `cardinality_search` are copied out of the model file and are UNTRUSTED. They are
+ what the file claims about its own provenance, echoed for a report, and nothing checks them.
+
+The diagnostic pass that names the first failing formula, and the one that names the first
+undeclared symbol, are separate and unverified. They run only after the verified checker or the
+verified coverage gate has already said no.
+-/
+open Fol
+open Fol.Parse
+
+def jsonStr (s : String) : String :=
+ let escaped := s.foldl (fun acc c =>
+ match c with
+ | '"' => acc ++ "\\\""
+ | '\\' => acc ++ "\\\\"
+ | '\n' => acc ++ "\\n"
+ | '\t' => acc ++ "\\t"
+ | c => acc.push c) ""
+ "\"" ++ escaped ++ "\""
+
+def jsonBool (b : Bool) : String := if b then "true" else "false"
+
+/-- Which symbol the model file failed to declare. Unverified, and it runs only after `covers` has
+already returned false. -/
+def firstUndeclared (d1 d2 dc : List Sym) (Γ : List Form) : Option (String × String) :=
+ match (Γ.flatMap p1Syms).find? (fun p => !d1.contains p) with
+ | some p => some ("unary", p)
+ | none =>
+ match (Γ.flatMap p2Syms).find? (fun p => !d2.contains p) with
+ | some p => some ("binary", p)
+ | none =>
+ match (Γ.flatMap constSyms).find? (fun c => !dc.contains c) with
+ | some c => some ("constant", c)
+ | none => none
+
+/-- Which formula the structure failed. Unverified, and it runs only after `check` has already
+returned false. -/
+def firstFailure {n : Nat} (M : FinModel (n+1)) (es : List Entry) : Option (Nat × Entry) := Id.run do
+ let mut i := 0
+ for e in es do
+ if !eval M (fun _ => 0) e.form then
+ return some (i, e)
+ i := i + 1
+ return none
+
+def readOrFail (path : String) : IO (Except UInt32 String) := do
+ try
+ return .ok (← IO.FS.readFile path)
+ catch e =>
+ IO.eprintln s!"cannot read {path}: {e}"
+ return .error 2
+
+def unreadable (reason : String) : IO UInt32 := do
+ IO.println ("{\"verdict\":\"unreadable\",\"reason\":" ++ jsonStr reason ++ "}")
+ IO.eprintln reason
+ return 2
+
+def run (pPath mPath : String) : IO UInt32 := do
+ let pTxt ← match ← readOrFail pPath with
+ | .ok s => pure s
+ | .error _ => return ← unreadable s!"cannot read {pPath}"
+ let mTxt ← match ← readOrFail mPath with
+ | .ok s => pure s
+ | .error _ => return ← unreadable s!"cannot read {mPath}"
+ match parseProblem pTxt with
+ | .error e => unreadable e
+ | .ok entries =>
+ match parseModel mTxt with
+ | .error e => unreadable e
+ | .ok pm =>
+ let forms := entries.map (fun e => e.form)
+ let nf := entries.length
+ let card := pm.n + 1
+ let closed := forms.all (fun g => (free g).isEmpty)
+ let goal := entries.any (fun e => e.role == "goal_negated")
+ let common :=
+ "\"formulas\":" ++ toString nf ++
+ ",\"domain\":" ++ toString card ++
+ ",\"closed\":" ++ jsonBool closed ++
+ ",\"goal_negated_present\":" ++ jsonBool goal ++
+ ",\"source\":" ++ jsonStr pm.source ++
+ ",\"cardinality_search\":" ++ jsonStr pm.search
+ let expected := problemDigest entries
+ if pm.digest != expected then
+ IO.println ("{\"verdict\":\"rejected\",\"reason\":\"problem_digest_mismatch\"," ++
+ common ++ ",\"expected\":" ++ jsonStr expected ++
+ ",\"found\":" ++ jsonStr pm.digest ++ "}")
+ return 1
+ if !covers pm.decl1 pm.decl2 pm.declc forms then
+ let (kind, sym) := (firstUndeclared pm.decl1 pm.decl2 pm.declc forms).getD ("unknown", "")
+ IO.println ("{\"verdict\":\"rejected\",\"reason\":\"undeclared_symbol\"," ++
+ "\"gate\":\"attribution\"," ++ common ++
+ ",\"symbol\":" ++ jsonStr sym ++ ",\"arity\":" ++ jsonStr kind ++ "}")
+ return 1
+ if check pm.model forms then
+ IO.println ("{\"verdict\":\"model_checked\"," ++ common ++
+ ",\"problem_digest\":" ++ jsonStr expected ++
+ ",\"theorem\":\"Fol.satisfiable_of_check\"" ++
+ (if goal then ",\"non_entailment_theorem\":\"Fol.not_entails_of_check\"" else "") ++
+ "}")
+ return 0
+ else
+ let thm := if closed then "Fol.check_complete_closed" else "Fol.check_complete"
+ match firstFailure pm.model entries with
+ | some (i, e) =>
+ IO.println ("{\"verdict\":\"rejected\"," ++ common ++
+ ",\"theorem\":" ++ jsonStr thm ++
+ ",\"first_rejected\":" ++ toString i ++
+ ",\"label\":" ++ jsonStr e.label ++
+ ",\"role\":" ++ jsonStr e.role ++
+ ",\"formula\":" ++ jsonStr (showForm e.form) ++ "}")
+ | none =>
+ IO.println ("{\"verdict\":\"rejected\"," ++ common ++
+ ",\"theorem\":" ++ jsonStr thm ++
+ ",\"error\":\"the verified checker rejected the structure and the diagnostic pass " ++
+ "could not name a formula\"}")
+ return 1
+
+def main (args : List String) : IO UInt32 := do
+ match args with
+ | [p, m] => run p m
+ | _ =>
+ IO.eprintln "usage: oo-folmodel PROBLEM.tsv MODEL.tsv"
+ return 2
diff --git a/lean/lakefile.toml b/lean/lakefile.toml
index f0e8a54e..c1f2fe5f 100644
--- a/lean/lakefile.toml
+++ b/lean/lakefile.toml
@@ -1,6 +1,6 @@
name = "oocert"
version = "0.1.0"
-defaultTargets = ["OOCert", "oo-cert", "oo-horn", "Shacl", "oo-shacl", "oo-refute", "Dl", "oo-dlmodel"]
+defaultTargets = ["OOCert", "oo-cert", "oo-horn", "Shacl", "oo-shacl", "oo-refute", "Dl", "oo-dlmodel", "Fol", "oo-folmodel"]
# Every library and executable here is in defaultTargets on purpose. A target
# left out of the default set is not built by a bare `lake build`, which is what
@@ -50,3 +50,17 @@ name = "Dl"
[[lean_exe]]
name = "oo-dlmodel"
root = "DlMain"
+
+# The first-order model certificate. A solver's `sat` answer plus the finite
+# structure it built, checked against the problem it was given. Separate from
+# `Dl` on purpose and NOT built on it: `Dl.Sat` evaluates at one free variable
+# over a carrier given as a list of names, `Fol.eval` threads an environment
+# over a carrier that is a type, and `Dl.WellFormed` would make `Fol` REJECT
+# genuine models. The six reasons are in decision 0006 so that nobody
+# re-litigates the split in six months.
+[[lean_lib]]
+name = "Fol"
+
+[[lean_exe]]
+name = "oo-folmodel"
+root = "FolMain"
diff --git a/src/batch.rs b/src/batch.rs
index afee4117..e6eb459c 100644
--- a/src/batch.rs
+++ b/src/batch.rs
@@ -64,13 +64,27 @@ impl BatchRunner {
for (seq, cmd) in commands.iter().enumerate() {
let result = self.execute(cmd).await;
let has_error = result.get("error").is_some();
+ // A STOP-THE-LINE disagreement is not an `error`: the command ran
+ // and answered. It must still fail the run, because it means a
+ // verified checker and the thing it was checking disagree, and a
+ // pipeline that treated that as a normal result would be a
+ // pipeline in which the check never has to pass. This is the same
+ // rule `tools/shacl_differential.py` applies to a FALSE_CLEAN,
+ // which exits 1 while every other verdict exits 0. Keyed on the
+ // field rather than on the command name so that a later command
+ // reporting the same thing inherits it. See decision 0006.
+ let stopped = result
+ .get("stop_the_line")
+ .and_then(Value::as_u64)
+ .unwrap_or(0)
+ > 0;
on_result(&json!({
"seq": seq,
"command": cmd.name,
"result": result,
}));
- if has_error {
+ if has_error || stopped {
exit_code = 1;
if bail {
break;
@@ -99,6 +113,7 @@ impl BatchRunner {
"lint" => self.exec_lint(&cmd.args),
"reason" => self.exec_reason(&cmd.args),
"fol" => self.exec_fol(&cmd.args),
+ "fol-model" | "fol_model" => self.exec_fol_model(&cmd.args),
"shacl" => self.exec_shacl(&cmd.args),
// The CLI subcommand is spelled with a hyphen and this arm accepted
// only the underscore, so every documented invocation was rejected
@@ -285,8 +300,13 @@ impl BatchRunner {
let format = Self::flag_value(args, "--format").unwrap_or("tptp".to_string());
let dialect = Self::flag_value(args, "--clif-dialect");
let comments = Self::flag_value(args, "--clif-comments");
- let syntax =
- match crate::tptp::Syntax::parse(&format, dialect.as_deref(), comments.as_deref()) {
+ let domain = Self::flag_value(args, "--smt-domain").and_then(|v| v.parse::<u32>().ok());
+ let syntax = match crate::tptp::Syntax::parse(
+ &format,
+ dialect.as_deref(),
+ comments.as_deref(),
+ domain,
+ ) {
Ok(s) => s,
Err(e) => return json!({"error": e.to_string()}),
};
@@ -305,6 +325,47 @@ impl BatchRunner {
serde_json::from_str(&result).unwrap_or(json!({"raw": result}))
}
+ /// The certifying pipeline. In-process for the same reason `fol` is: the
+ /// store is per process, so loading and solving have to happen in one run.
+ fn exec_fol_model(&self, args: &[String]) -> Value {
+ use crate::fol_solve::{SolveOptions, Solver, solve_export};
+ let Some(out) = Self::flag_value(args, "--out") else {
+ return json!({"error": "fol-model requires --out DIR"});
+ };
+ let solver = match Solver::parse(
+ &Self::flag_value(args, "--solver").unwrap_or("z3".to_string()),
+ ) {
+ Ok(s) => s,
+ Err(e) => return json!({"error": e.to_string()}),
+ };
+ let opts = SolveOptions {
+ solver,
+ max_domain: Self::flag_value(args, "--max-domain")
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(16),
+ timeout_secs: Self::flag_value(args, "--timeout-secs")
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(30),
+ unbounded_probe: Self::flag_value(args, "--unbounded-probe")
+ .map(|v| v != "false")
+ .unwrap_or(true),
+ checker: Self::flag_value(args, "--checker").map(std::path::PathBuf::from),
+ };
+ let goals = Self::flag_value(args, "--goals");
+ let skip: usize = Self::flag_value(args, "--goals-skip-columns")
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(0);
+ let result = solve_export(
+ &self.graph,
+ std::path::Path::new(&out),
+ &opts,
+ goals.as_deref().map(std::path::Path::new),
+ skip,
+ )
+ .unwrap_or_else(|e| json!({"error": e.to_string()}).to_string());
+ serde_json::from_str(&result).unwrap_or(json!({"raw": result}))
+ }
+
fn exec_shacl(&self, args: &[String]) -> Value {
use crate::shacl::ShaclValidator;
let shapes_path = match args.first() {
diff --git a/src/fol_model.rs b/src/fol_model.rs
new file mode 100644
index 00000000..2ea73449
--- /dev/null
+++ b/src/fol_model.rs
@@ -0,0 +1,1128 @@
+//! Reading a finite structure back out of a solver, and writing it in the form
+//! the verified checker reads.
+//!
+//! # Where this sits
+//!
+//! `src/tptp.rs` writes the question, in SMT-LIB 2 for Z3 and in LADR for
+//! Mace4. `lean/Fol/` checks the answer, and `Fol.satisfiable_of_check` is why
+//! that check is worth anything. This module is the join: it turns whatever
+//! the solver printed into a [`FiniteModel`], and a [`FiniteModel`] into the
+//! `model.tsv` the checker parses.
+//!
+//! **One structure, two front ends.** The two printed formats have nothing in
+//! common — Z3 prints SMT-LIB `define-fun` bodies that have to be EVALUATED,
+//! Mace4 prints dense integer tables that have to be INDEXED — and the whole
+//! reason for the shape of this module is that a third finder should cost only
+//! a third `parse_model`. Everything after the front end is shared.
+//!
+//! # Nothing here is trusted, and that is not a slogan
+//!
+//! A bug in this module cannot produce a false certificate. The checker
+//! re-evaluates the ORIGINAL formulas against whatever structure comes out, so
+//! a misread table yields a structure that fails `Fol.check` and the pipeline
+//! reports a stop-the-line disagreement. The failure mode of a parser bug here
+//! is a false alarm, never a false clean. That asymmetry is worth stating
+//! because it is the reason the ingestion can be a plain Rust parser at all
+//! while the checker has to be Lean.
+//!
+//! What a bug here CAN do is break attribution: silently substituting a
+//! different structure for the solver's would leave a run reporting that "the
+//! solver's model was checked" when it checked something else. So every
+//! failure is loud. There is no defaulting, no `unwrap_or(false)`, no skipped
+//! row: a symbol the solver did not interpret is an error naming the symbol,
+//! a construct the evaluator does not know is an error naming the construct,
+//! and a table of the wrong length is an error giving both lengths.
+//!
+//! # The reduct
+//!
+//! Both solvers interpret symbols the translation never emitted. Z3 invents
+//! auxiliary functions; Mace4 clausifies and Skolemises, so its models carry
+//! `f1(_)` and constants it chose itself. Those are DROPPED, which is taking
+//! the reduct of the solver's structure, and it needs no lemma because the
+//! checker re-evaluates formulas that cannot mention a symbol the translation
+//! never emitted. The dropped names are reported rather than passed over, so
+//! the reduct is visible.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::fmt::Write as _;
+
+use crate::tptp::ladr::{SymKind, SymbolTable};
+use crate::tptp::Vocabulary;
+
+/// A finite first-order structure over the carrier `0 .. domain-1`.
+///
+/// The carrier is the integers because that is what Mace4 prints and what
+/// `Fin N` is, so a Mace4 `interpretation(N, …)` block ingests with no
+/// renaming at all.
+#[derive(Clone, Debug)]
+pub struct FiniteModel {
+ pub domain: usize,
+ /// `unary[s][i]` is true iff `s` holds of element `i`. Length `domain`.
+ pub unary: BTreeMap<String, Vec<bool>>,
+ /// `binary[s][i][j]` is true iff `s` relates `i` to `j`. `domain` rows of
+ /// `domain`.
+ pub binary: BTreeMap<String, Vec<Vec<bool>>>,
+ pub consts: BTreeMap<String, usize>,
+ /// Which solver said this. UNTRUSTED: echoed into the report and into
+ /// `model.tsv`'s `source` line, and nothing checks it.
+ pub source: &'static str,
+ /// Symbols the solver interpreted that the translation never emitted, so
+ /// this structure is a reduct of the solver's. Reported, not hidden.
+ pub dropped: Vec<String>,
+}
+
+/// A model that could not be read. Every arm names what was being read and
+/// what was wrong with it; none of them is recoverable by defaulting.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum IngestError {
+ /// The solver's output held no model at all where one was expected.
+ NoModel { solver: &'static str, saw: String },
+ /// The S-expression or the LADR block did not parse.
+ Syntax { solver: &'static str, at: String, why: String },
+ /// A symbol the PROBLEM uses has no interpretation in the model. This is
+ /// the attribution failure `Fol.covers` would catch one step later; it is
+ /// caught here so the message can name the solver.
+ Uninterpreted { solver: &'static str, symbol: String, arity: &'static str },
+ /// The model evaluator met a construct it does not know. Named rather than
+ /// approximated, because an approximated model is a different model.
+ Unsupported { solver: &'static str, construct: String, context: String },
+ /// A carrier index the solver printed is outside the carrier it declared.
+ OutOfRange { solver: &'static str, symbol: String, index: usize, domain: usize },
+ /// A table whose length is not what the declared carrier requires.
+ BadWidth { solver: &'static str, symbol: String, want: usize, got: usize },
+ /// A carrier of zero elements. A first-order structure cannot have one,
+ /// and `Fol.FinModel` is defined only at `n+1`.
+ EmptyDomain { solver: &'static str },
+}
+
+impl std::fmt::Display for IngestError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ IngestError::NoModel { solver, saw } => write!(
+ f,
+ "{solver} printed no model where one was expected; it said: {saw}"
+ ),
+ IngestError::Syntax { solver, at, why } => {
+ write!(f, "could not parse {solver}'s model near {at:?}: {why}")
+ }
+ IngestError::Uninterpreted { solver, symbol, arity } => write!(
+ f,
+ "{solver} returned no interpretation for the {arity} symbol {symbol:?}, which \
+ the problem uses. A missing row would DEFAULT in the checker rather than fail, \
+ and a defaulted structure is not the one the solver described, so this is an \
+ error here"
+ ),
+ IngestError::Unsupported { solver, construct, context } => write!(
+ f,
+ "{solver}'s model uses {construct:?}, which this evaluator does not know, in \
+ {context}. Approximating it would certify a DIFFERENT structure from the one \
+ the solver built"
+ ),
+ IngestError::OutOfRange { solver, symbol, index, domain } => write!(
+ f,
+ "{solver} interpreted {symbol:?} at carrier element {index}, outside the \
+ declared carrier of {domain}"
+ ),
+ IngestError::BadWidth { solver, symbol, want, got } => write!(
+ f,
+ "{solver}'s table for {symbol:?} has {got} entries where the declared carrier \
+ requires {want}"
+ ),
+ IngestError::EmptyDomain { solver } => write!(
+ f,
+ "{solver} reported a carrier of zero elements; a first-order structure cannot \
+ have one"
+ ),
+ }
+ }
+}
+
+impl std::error::Error for IngestError {}
+
+impl FiniteModel {
+ /// `model.tsv`, the file `oo-folmodel` reads.
+ ///
+ /// `digest` binds it to a `problem.tsv`; the Lean recomputes that digest
+ /// from the problem and refuses on a mismatch, so a model pasted next to
+ /// the wrong problem is exit 1 with `problem_digest_mismatch` rather than
+ /// a silently meaningless run.
+ pub fn to_model_tsv(&self, digest: &str, search: &[u32]) -> String {
+ let mut s = String::new();
+ let _ = writeln!(s, "domain\t{}", self.domain);
+ let _ = writeln!(s, "problem\t{digest}");
+ let _ = writeln!(s, "source\t{}", self.source);
+ for k in self.unary.keys() {
+ let _ = writeln!(s, "decl1\t{k}");
+ }
+ for k in self.binary.keys() {
+ let _ = writeln!(s, "decl2\t{k}");
+ }
+ for k in self.consts.keys() {
+ let _ = writeln!(s, "declc\t{k}");
+ }
+ for (k, row) in &self.unary {
+ let _ = writeln!(s, "p1\t{k}\t{}", bits(row));
+ }
+ for (k, rows) in &self.binary {
+ for (i, row) in rows.iter().enumerate() {
+ let _ = writeln!(s, "p2\t{k}\t{i}\t{}", bits(row));
+ }
+ }
+ for (k, i) in &self.consts {
+ let _ = writeln!(s, "const\t{k}\t{i}");
+ }
+ if !search.is_empty() {
+ let strs: Vec<String> = search.iter().map(|k| k.to_string()).collect();
+ let _ = writeln!(s, "cardinality_search\t{}", strs.join(","));
+ }
+ s
+ }
+
+ /// Check the shape before writing it out: every table the declared carrier
+ /// size, every constant inside it.
+ ///
+ /// The Lean parser checks all of this again and exits 2 on any of it. Doing
+ /// it here as well is not redundancy for its own sake: an exit 2 is
+ /// "unreadable", which is not a verdict in either direction, so a writer
+ /// bug that produced one would show up as a mysterious unreadable file
+ /// rather than as a named defect in this module.
+ pub fn self_check(&self, solver: &'static str) -> Result<(), IngestError> {
+ if self.domain == 0 {
+ return Err(IngestError::EmptyDomain { solver });
+ }
+ for (k, row) in &self.unary {
+ if row.len() != self.domain {
+ return Err(IngestError::BadWidth {
+ solver,
+ symbol: k.clone(),
+ want: self.domain,
+ got: row.len(),
+ });
+ }
+ }
+ for (k, rows) in &self.binary {
+ if rows.len() != self.domain {
+ return Err(IngestError::BadWidth {
+ solver,
+ symbol: k.clone(),
+ want: self.domain,
+ got: rows.len(),
+ });
+ }
+ for row in rows {
+ if row.len() != self.domain {
+ return Err(IngestError::BadWidth {
+ solver,
+ symbol: k.clone(),
+ want: self.domain,
+ got: row.len(),
+ });
+ }
+ }
+ }
+ for (k, i) in &self.consts {
+ if *i >= self.domain {
+ return Err(IngestError::OutOfRange {
+ solver,
+ symbol: k.clone(),
+ index: *i,
+ domain: self.domain,
+ });
+ }
+ }
+ Ok(())
+ }
+
+ /// Every symbol the problem uses is interpreted here. The checker's
+ /// `Fol.covers` gate asks the same question one step later; asking it here
+ /// too is what lets the error name the solver that omitted the symbol.
+ pub fn covers(&self, v: &Vocabulary, solver: &'static str) -> Result<(), IngestError> {
+ for s in &v.unary {
+ if !self.unary.contains_key(s) {
+ return Err(IngestError::Uninterpreted {
+ solver,
+ symbol: s.clone(),
+ arity: "unary",
+ });
+ }
+ }
+ for s in &v.binary {
+ if !self.binary.contains_key(s) {
+ return Err(IngestError::Uninterpreted {
+ solver,
+ symbol: s.clone(),
+ arity: "binary",
+ });
+ }
+ }
+ for s in &v.consts {
+ if !self.consts.contains_key(s) {
+ return Err(IngestError::Uninterpreted {
+ solver,
+ symbol: s.clone(),
+ arity: "constant",
+ });
+ }
+ }
+ Ok(())
+ }
+}
+
+fn bits(row: &[bool]) -> String {
+ row.iter().map(|b| if *b { '1' } else { '0' }).collect()
+}
+
+// ── Front end 1: Z3, an SMT-LIB model ───────────────────────────────────────
+
+/// Reading `(get-model)` back from an SMT solver over the finite encoding.
+///
+/// Z3 prints a list of `define-fun`s whose bodies are TERMS, not tables, so
+/// the reading is an evaluation: the body of `p` is applied at every carrier
+/// element and the resulting bit vector is the row. Measured shapes on
+/// Z3 4.16.0 over an enumeration sort, all four of which appear in practice:
+///
+/// ```text
+/// (define-fun |c:Person| ((x!0 U)) Bool true)
+/// (define-fun |c:Company| ((x!0 U)) Bool (ite (= x!0 e1) true false))
+/// (define-fun p ((x!0 U)) Bool (and (not (= x!0 e1)) (not (= x!0 e3))))
+/// (define-fun r ((x!0 U) (x!1 U)) Bool
+/// (or (and (= x!0 e1) (= x!1 e0)) (and (not (= x!0 e1)) (= x!1 e1))))
+/// ```
+///
+/// The evaluator therefore has to know `ite`, `=`, `and`, `or`, `not` and the
+/// two truth constants, and it also knows `=>`, `xor`, `distinct` and `let`
+/// because they are cheap and Z3 emits them on larger models. A head it does
+/// NOT know is [`IngestError::Unsupported`] naming the head, never an
+/// approximation: a structure guessed at is a different structure, and
+/// certifying it would say something true about the wrong object.
+pub mod z3 {
+ use super::*;
+
+ const SOLVER: &str = "z3";
+
+ /// A minimal S-expression.
+ #[derive(Debug, Clone, PartialEq, Eq)]
+ pub enum Sexp {
+ Atom(String),
+ List(Vec<Sexp>),
+ }
+
+ impl Sexp {
+ fn atom(&self) -> Option<&str> {
+ match self {
+ Sexp::Atom(a) => Some(a),
+ Sexp::List(_) => None,
+ }
+ }
+ fn list(&self) -> Option<&[Sexp]> {
+ match self {
+ Sexp::List(l) => Some(l),
+ Sexp::Atom(_) => None,
+ }
+ }
+ }
+
+ /// Parse every top-level S-expression in `text`.
+ ///
+ /// Handles `|quoted symbols|`, `"strings"` and `;` line comments, because
+ /// Z3's model output contains all three: the symbols this repository emits
+ /// are `|…|` and Z3 annotates the unbounded encoding's universe with `;;`
+ /// comment lines.
+ pub fn parse_sexps(text: &str) -> Result<Vec<Sexp>, IngestError> {
+ let b: Vec<char> = text.chars().collect();
+ let mut i = 0usize;
+ let mut out = Vec::new();
+ loop {
+ skip_ws(&b, &mut i);
+ if i >= b.len() {
+ return Ok(out);
+ }
+ out.push(parse_one(&b, &mut i)?);
+ }
+ }
+
+ fn skip_ws(b: &[char], i: &mut usize) {
+ loop {
+ while *i < b.len() && b[*i].is_whitespace() {
+ *i += 1;
+ }
+ if *i < b.len() && b[*i] == ';' {
+ while *i < b.len() && b[*i] != '\n' {
+ *i += 1;
+ }
+ continue;
+ }
+ return;
+ }
+ }
+
+ fn parse_one(b: &[char], i: &mut usize) -> Result<Sexp, IngestError> {
+ skip_ws(b, i);
+ if *i >= b.len() {
+ return Err(IngestError::Syntax {
+ solver: SOLVER,
+ at: "end of output".into(),
+ why: "the expression ended in the middle of a form".into(),
+ });
+ }
+ if b[*i] == '(' {
+ *i += 1;
+ let mut items = Vec::new();
+ loop {
+ skip_ws(b, i);
+ if *i >= b.len() {
+ return Err(IngestError::Syntax {
+ solver: SOLVER,
+ at: "end of output".into(),
+ why: "unclosed (".into(),
+ });
+ }
+ if b[*i] == ')' {
+ *i += 1;
+ return Ok(Sexp::List(items));
+ }
+ items.push(parse_one(b, i)?);
+ }
+ }
+ if b[*i] == ')' {
+ return Err(IngestError::Syntax {
+ solver: SOLVER,
+ at: ")".into(),
+ why: "a closing bracket with nothing open".into(),
+ });
+ }
+ // A `|quoted symbol|` runs to the matching bar and admits everything
+ // except `|` and `\`, so there is no escape to honour inside it.
+ if b[*i] == '|' {
+ *i += 1;
+ let start = *i;
+ while *i < b.len() && b[*i] != '|' {
+ *i += 1;
+ }
+ if *i >= b.len() {
+ return Err(IngestError::Syntax {
+ solver: SOLVER,
+ at: b[start..].iter().take(40).collect::<String>(),
+ why: "unterminated |quoted symbol|".into(),
+ });
+ }
+ let s: String = b[start..*i].iter().collect();
+ *i += 1;
+ return Ok(Sexp::Atom(s));
+ }
+ if b[*i] == '"' {
+ *i += 1;
+ let start = *i;
+ while *i < b.len() && b[*i] != '"' {
+ *i += 1;
+ }
+ let s: String = b[start..*i.min(&mut b.len().clone())].iter().collect();
+ if *i < b.len() {
+ *i += 1;
+ }
+ return Ok(Sexp::Atom(s));
+ }
+ let start = *i;
+ while *i < b.len() && !b[*i].is_whitespace() && b[*i] != '(' && b[*i] != ')' {
+ *i += 1;
+ }
+ Ok(Sexp::Atom(b[start..*i].iter().collect()))
+ }
+
+ /// A value in a model body: a truth value or a carrier element.
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ enum Val {
+ B(bool),
+ E(usize),
+ }
+
+ struct Defn<'a> {
+ args: Vec<String>,
+ /// The declared return sort, `Bool` or `U`. Kept because it is the
+ /// cheapest guard against reading a `define-fun` off by one: the first
+ /// version of this parser took `l[3]` for the body, which is the SORT,
+ /// and every ingestion failed with `z3's model uses "Bool"`. The
+ /// checker would have caught the resulting structure, but the message
+ /// is better here.
+ sort: String,
+ body: &'a Sexp,
+ }
+
+ /// `e17` → 17. The enumeration constructors the finite encoding declares.
+ fn element(a: &str, domain: usize) -> Option<usize> {
+ let n: usize = a.strip_prefix('e')?.parse().ok()?;
+ if n < domain { Some(n) } else { None }
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn eval(
+ e: &Sexp,
+ env: &BTreeMap<String, Val>,
+ defs: &BTreeMap<String, Defn<'_>>,
+ domain: usize,
+ depth: usize,
+ context: &str,
+ ) -> Result<Val, IngestError> {
+ if depth == 0 {
+ return Err(IngestError::Unsupported {
+ solver: SOLVER,
+ construct: "a definition chain deeper than 64".into(),
+ context: context.to_string(),
+ });
+ }
+ match e {
+ Sexp::Atom(a) => {
+ if a == "true" {
+ return Ok(Val::B(true));
+ }
+ if a == "false" {
+ return Ok(Val::B(false));
+ }
+ if let Some(v) = env.get(a) {
+ return Ok(*v);
+ }
+ if let Some(n) = element(a, domain) {
+ return Ok(Val::E(n));
+ }
+ if let Some(d) = defs.get(a)
+ && d.args.is_empty()
+ {
+ return eval(d.body, &BTreeMap::new(), defs, domain, depth - 1, context);
+ }
+ Err(IngestError::Unsupported {
+ solver: SOLVER,
+ construct: a.clone(),
+ context: context.to_string(),
+ })
+ }
+ Sexp::List(items) => {
+ let (head, args) = items.split_first().ok_or(IngestError::Syntax {
+ solver: SOLVER,
+ at: "()".into(),
+ why: "an empty application".into(),
+ })?;
+ let h = head.atom().ok_or_else(|| IngestError::Unsupported {
+ solver: SOLVER,
+ construct: "an application whose head is itself a list".into(),
+ context: context.to_string(),
+ })?;
+ let ev = |x: &Sexp| eval(x, env, defs, domain, depth - 1, context);
+ match h {
+ "not" => match ev(&args[0])? {
+ Val::B(b) => Ok(Val::B(!b)),
+ Val::E(_) => Err(unsupported("not applied to a carrier element", context)),
+ },
+ "and" | "or" => {
+ let mut acc = h == "and";
+ for a in args {
+ match ev(a)? {
+ Val::B(b) => {
+ if h == "and" {
+ acc &= b
+ } else {
+ acc |= b
+ }
+ }
+ Val::E(_) => {
+ return Err(unsupported(
+ "and/or applied to a carrier element",
+ context,
+ ));
+ }
+ }
+ }
+ Ok(Val::B(acc))
+ }
+ "xor" => {
+ let mut acc = false;
+ for a in args {
+ match ev(a)? {
+ Val::B(b) => acc ^= b,
+ Val::E(_) => {
+ return Err(unsupported(
+ "xor applied to a carrier element",
+ context,
+ ));
+ }
+ }
+ }
+ Ok(Val::B(acc))
+ }
+ "=>" => {
+ // Right-associative in SMT-LIB, and `(=> a)` is `a`.
+ let mut vals = Vec::new();
+ for a in args {
+ match ev(a)? {
+ Val::B(b) => vals.push(b),
+ Val::E(_) => {
+ return Err(unsupported(
+ "=> applied to a carrier element",
+ context,
+ ));
+ }
+ }
+ }
+ let mut acc = *vals.last().unwrap_or(&true);
+ for v in vals.iter().rev().skip(1) {
+ acc = !v || acc;
+ }
+ Ok(Val::B(acc))
+ }
+ "=" => {
+ let first = ev(&args[0])?;
+ let mut all = true;
+ for a in &args[1..] {
+ all &= ev(a)? == first;
+ }
+ Ok(Val::B(all))
+ }
+ "distinct" => {
+ let mut vals = Vec::new();
+ for a in args {
+ vals.push(ev(a)?);
+ }
+ let mut ok = true;
+ for i in 0..vals.len() {
+ for j in (i + 1)..vals.len() {
+ ok &= vals[i] != vals[j];
+ }
+ }
+ Ok(Val::B(ok))
+ }
+ "ite" => match ev(&args[0])? {
+ Val::B(true) => ev(&args[1]),
+ Val::B(false) => ev(&args[2]),
+ Val::E(_) => Err(unsupported("ite with a non-boolean test", context)),
+ },
+ "let" => {
+ let binds = args[0].list().ok_or_else(|| {
+ unsupported("a let whose bindings are not a list", context)
+ })?;
+ let mut inner = env.clone();
+ for b in binds {
+ let pair = b.list().ok_or_else(|| {
+ unsupported("a let binding that is not a pair", context)
+ })?;
+ let name = pair
+ .first()
+ .and_then(Sexp::atom)
+ .ok_or_else(|| unsupported("a nameless let binding", context))?;
+ // Bindings are simultaneous in SMT-LIB, so each is
+ // evaluated in the OUTER environment.
+ let v = eval(&pair[1], env, defs, domain, depth - 1, context)?;
+ inner.insert(name.to_string(), v);
+ }
+ eval(&args[1], &inner, defs, domain, depth - 1, context)
+ }
+ other => {
+ // An auxiliary function Z3 defined earlier in the same
+ // model. Anything else is refused by name.
+ if let Some(d) = defs.get(other)
+ && d.args.len() == args.len()
+ {
+ let mut inner = BTreeMap::new();
+ for (n, a) in d.args.iter().zip(args) {
+ inner.insert(n.clone(), ev(a)?);
+ }
+ return eval(d.body, &inner, defs, domain, depth - 1, context);
+ }
+ Err(IngestError::Unsupported {
+ solver: SOLVER,
+ construct: other.to_string(),
+ context: context.to_string(),
+ })
+ }
+ }
+ }
+ }
+ }
+
+ fn unsupported(what: &str, context: &str) -> IngestError {
+ IngestError::Unsupported {
+ solver: SOLVER,
+ construct: what.to_string(),
+ context: context.to_string(),
+ }
+ }
+
+ /// The declared shape of a `define-fun` against the shape the problem
+ /// says the symbol has. A mismatch is a defect in this parser or a change
+ /// in Z3's output, and either way it is named rather than worked around.
+ fn check_sort(
+ d: &Defn<'_>,
+ want_sort: &str,
+ want_args: usize,
+ symbol: &str,
+ ) -> Result<(), IngestError> {
+ if d.sort != want_sort || d.args.len() != want_args {
+ return Err(IngestError::Unsupported {
+ solver: SOLVER,
+ construct: format!(
+ "a define-fun of {} argument(s) returning {:?}",
+ d.args.len(),
+ d.sort
+ ),
+ context: format!(
+ "the symbol {symbol:?}, which the problem uses with {want_args} \
+ argument(s) and result sort {want_sort}"
+ ),
+ });
+ }
+ Ok(())
+ }
+
+ /// Turn Z3's `(get-model)` output into a structure over `0 .. domain-1`.
+ ///
+ /// `vocab` is the problem's own vocabulary. Only those symbols are read;
+ /// everything else Z3 defined is the reduct and is reported in
+ /// [`FiniteModel::dropped`].
+ pub fn parse_model(
+ text: &str,
+ vocab: &Vocabulary,
+ domain: usize,
+ ) -> Result<FiniteModel, IngestError> {
+ if domain == 0 {
+ return Err(IngestError::EmptyDomain { solver: SOLVER });
+ }
+ let forms = parse_sexps(text)?;
+ // Z3 prints the model as one top-level list of define-funs. Older
+ // spellings wrap it in `(model …)`. Take whichever is there.
+ let items: Vec<&Sexp> = forms
+ .iter()
+ .flat_map(|f| match f {
+ Sexp::List(l) => {
+ if l.first().and_then(Sexp::atom) == Some("model") {
+ l[1..].iter().collect::<Vec<_>>()
+ } else {
+ l.iter().collect::<Vec<_>>()
+ }
+ }
+ Sexp::Atom(_) => Vec::new(),
+ })
+ .collect();
+
+ let mut defs: BTreeMap<String, Defn<'_>> = BTreeMap::new();
+ let mut order: Vec<String> = Vec::new();
+ for it in &items {
+ let l = match it.list() {
+ Some(l) => l,
+ None => continue,
+ };
+ // `(define-fun NAME ((arg sort)…) RETURN-SORT BODY)`: five
+ // elements, and the body is the LAST of them.
+ if l.first().and_then(Sexp::atom) != Some("define-fun") || l.len() < 5 {
+ continue;
+ }
+ let name = match l[1].atom() {
+ Some(n) => n.to_string(),
+ None => continue,
+ };
+ let mut args = Vec::new();
+ if let Some(params) = l[2].list() {
+ for p in params {
+ let pair = p.list().ok_or_else(|| IngestError::Syntax {
+ solver: SOLVER,
+ at: name.clone(),
+ why: "a parameter that is not a (name sort) pair".into(),
+ })?;
+ args.push(
+ pair.first()
+ .and_then(Sexp::atom)
+ .ok_or_else(|| IngestError::Syntax {
+ solver: SOLVER,
+ at: name.clone(),
+ why: "a nameless parameter".into(),
+ })?
+ .to_string(),
+ );
+ }
+ }
+ let sort = l[3].atom().unwrap_or("").to_string();
+ order.push(name.clone());
+ defs.insert(name, Defn { args, sort, body: &l[4] });
+ }
+ if defs.is_empty() {
+ return Err(IngestError::NoModel {
+ solver: SOLVER,
+ saw: text.lines().take(3).collect::<Vec<_>>().join(" / "),
+ });
+ }
+
+ let mut m = FiniteModel {
+ domain,
+ unary: BTreeMap::new(),
+ binary: BTreeMap::new(),
+ consts: BTreeMap::new(),
+ source: "z3",
+ dropped: Vec::new(),
+ };
+ let wanted: BTreeSet<&String> =
+ vocab.unary.iter().chain(&vocab.binary).chain(&vocab.consts).collect();
+ for name in &order {
+ if !wanted.contains(name) {
+ m.dropped.push(name.clone());
+ }
+ }
+
+ for s in &vocab.unary {
+ let d = defs.get(s).ok_or_else(|| IngestError::Uninterpreted {
+ solver: SOLVER,
+ symbol: s.clone(),
+ arity: "unary",
+ })?;
+ check_sort(d, "Bool", 1, s)?;
+ let mut row = Vec::with_capacity(domain);
+ for i in 0..domain {
+ let mut env = BTreeMap::new();
+ if let Some(a) = d.args.first() {
+ env.insert(a.clone(), Val::E(i));
+ }
+ match eval(d.body, &env, &defs, domain, 64, s)? {
+ Val::B(b) => row.push(b),
+ Val::E(_) => {
+ return Err(unsupported("a unary predicate returning a carrier element", s));
+ }
+ }
+ }
+ m.unary.insert(s.clone(), row);
+ }
+ for s in &vocab.binary {
+ let d = defs.get(s).ok_or_else(|| IngestError::Uninterpreted {
+ solver: SOLVER,
+ symbol: s.clone(),
+ arity: "binary",
+ })?;
+ check_sort(d, "Bool", 2, s)?;
+ let mut rows = Vec::with_capacity(domain);
+ for i in 0..domain {
+ let mut row = Vec::with_capacity(domain);
+ for j in 0..domain {
+ let mut env = BTreeMap::new();
+ if d.args.len() >= 2 {
+ env.insert(d.args[0].clone(), Val::E(i));
+ env.insert(d.args[1].clone(), Val::E(j));
+ }
+ match eval(d.body, &env, &defs, domain, 64, s)? {
+ Val::B(b) => row.push(b),
+ Val::E(_) => {
+ return Err(unsupported(
+ "a binary predicate returning a carrier element",
+ s,
+ ));
+ }
+ }
+ }
+ rows.push(row);
+ }
+ m.binary.insert(s.clone(), rows);
+ }
+ for s in &vocab.consts {
+ let d = defs.get(s).ok_or_else(|| IngestError::Uninterpreted {
+ solver: SOLVER,
+ symbol: s.clone(),
+ arity: "constant",
+ })?;
+ check_sort(d, "U", 0, s)?;
+ match eval(d.body, &BTreeMap::new(), &defs, domain, 64, s)? {
+ Val::E(n) => {
+ m.consts.insert(s.clone(), n);
+ }
+ Val::B(_) => {
+ return Err(unsupported("a constant of sort U evaluating to a boolean", s));
+ }
+ }
+ }
+ m.self_check(SOLVER)?;
+ Ok(m)
+ }
+}
+
+// ── Front end 2: Mace4, a LADR interpretation ───────────────────────────────
+
+/// Reading Mace4's `interpretation(…)` block.
+///
+/// Nothing is evaluated here: LADR prints DENSE INTEGER TABLES and the reading
+/// is an indexing. The measured shape, LADR 2009-11A:
+///
+/// ```text
+/// interpretation( 2, [number=1, seconds=0], [
+/// function(c0, [ 0 ]),
+/// function(f1(_), [ 1, 0 ]),
+/// relation(p0(_), [ 1, 0 ]),
+/// relation(r0(_,_), [ 0, 1,
+/// 0, 0 ])
+/// ]).
+/// ```
+///
+/// Arity is read off the `(_)` in the name. A binary table is ROW MAJOR: entry
+/// `i*n + j` is `r(i, j)`, verified against a run whose only true pair was
+/// `r0(0,1)` and whose table was `[0, 1, 0, 0]`.
+///
+/// `f1` is a Skolem function and is dropped. Mace4 also invents Skolem
+/// CONSTANTS, and it names them `c1, c2, …`, which is the same space this
+/// repository's mangler uses. Measured: given input already mentioning `c0`
+/// and `c1`, Mace4 named its Skolem constant `c2`, so it picks a name not
+/// already in the problem and no collision occurs. The demangling does not
+/// rely on that anyway: a name the [`SymbolTable`] never issued is dropped
+/// whatever it is called, and a symbol the table DID issue that Mace4 did not
+/// interpret is [`IngestError::Uninterpreted`]. That second half is the
+/// mechanical guard against LADR's variable-letter trap, in which a mangled
+/// constant becomes a variable and simply disappears from the model.
+pub mod mace4 {
+ use super::*;
+
+ const SOLVER: &str = "mace4";
+
+ struct Entry {
+ name: String,
+ arity: usize,
+ table: Vec<i64>,
+ is_relation: bool,
+ }
+
+ /// The first `interpretation(…)` block, or `None` if there is none.
+ fn first_block(text: &str) -> Option<&str> {
+ let start = text.find("interpretation(")?;
+ let rest = &text[start..];
+ let bytes = rest.as_bytes();
+ let mut depth = 0usize;
+ for (i, b) in bytes.iter().enumerate() {
+ match b {
+ b'(' => depth += 1,
+ b')' => {
+ depth -= 1;
+ if depth == 0 {
+ return Some(&rest[..=i]);
+ }
+ }
+ _ => {}
+ }
+ }
+ None
+ }
+
+ fn parse_entries(block: &str) -> Result<(usize, Vec<Entry>), IngestError> {
+ // interpretation( N , [stats] , [ entries ] )
+ let inner = block
+ .strip_prefix("interpretation(")
+ .and_then(|s| s.strip_suffix(')'))
+ .ok_or_else(|| IngestError::Syntax {
+ solver: SOLVER,
+ at: block.chars().take(40).collect::<String>(),
+ why: "not an interpretation( … ) form".into(),
+ })?;
+ let comma = inner.find(',').ok_or_else(|| IngestError::Syntax {
+ solver: SOLVER,
+ at: inner.chars().take(40).collect::<String>(),
+ why: "no comma after the carrier size".into(),
+ })?;
+ let domain: usize =
+ inner[..comma].trim().parse().map_err(|_| IngestError::Syntax {
+ solver: SOLVER,
+ at: inner[..comma].trim().to_string(),
+ why: "the carrier size is not a number".into(),
+ })?;
+
+ let mut entries = Vec::new();
+ let chars: Vec<char> = inner.chars().collect();
+ let mut i = comma;
+ while i < chars.len() {
+ let rest: String = chars[i..].iter().collect();
+ let (kind, is_relation) = match (rest.find("function("), rest.find("relation(")) {
+ (None, None) => break,
+ (Some(f), None) => (f, false),
+ (None, Some(r)) => (r, true),
+ (Some(f), Some(r)) => {
+ if f < r {
+ (f, false)
+ } else {
+ (r, true)
+ }
+ }
+ };
+ let head_len = if is_relation { "relation(".len() } else { "function(".len() };
+ let entry_start = i + rest[..kind].chars().count() + head_len;
+ // name runs to the comma at depth 0
+ let mut j = entry_start;
+ let mut depth = 0usize;
+ while j < chars.len() {
+ match chars[j] {
+ '(' => depth += 1,
+ ')' => {
+ if depth == 0 {
+ break;
+ }
+ depth -= 1;
+ }
+ ',' if depth == 0 => break,
+ _ => {}
+ }
+ j += 1;
+ }
+ let raw_name: String = chars[entry_start..j].iter().collect();
+ let raw_name = raw_name.trim().to_string();
+ let (name, arity) = match raw_name.find('(') {
+ None => (raw_name.clone(), 0usize),
+ Some(p) => {
+ let base = raw_name[..p].to_string();
+ let args = &raw_name[p + 1..raw_name.len().saturating_sub(1)];
+ (base, args.split(',').filter(|s| !s.trim().is_empty()).count())
+ }
+ };
+ // table runs from the next '[' to its matching ']'
+ let open = chars[j..].iter().position(|c| *c == '[').ok_or_else(|| {
+ IngestError::Syntax {
+ solver: SOLVER,
+ at: name.clone(),
+ why: "no [ … ] table after the name".into(),
+ }
+ })? + j;
+ let close = chars[open..].iter().position(|c| *c == ']').ok_or_else(|| {
+ IngestError::Syntax {
+ solver: SOLVER,
+ at: name.clone(),
+ why: "an unterminated [ … ] table".into(),
+ }
+ })? + open;
+ let body: String = chars[open + 1..close].iter().collect();
+ let mut table = Vec::new();
+ for tok in body.split(',') {
+ let t = tok.trim();
+ if t.is_empty() {
+ continue;
+ }
+ table.push(t.parse::<i64>().map_err(|_| IngestError::Syntax {
+ solver: SOLVER,
+ at: format!("{name} table entry {t:?}"),
+ why: "a table entry that is not an integer".into(),
+ })?);
+ }
+ entries.push(Entry { name, arity, table, is_relation });
+ i = close + 1;
+ }
+ Ok((domain, entries))
+ }
+
+ /// Turn Mace4's output into a structure, demangling through `tab`.
+ pub fn parse_model(text: &str, tab: &SymbolTable) -> Result<FiniteModel, IngestError> {
+ let block = first_block(text).ok_or_else(|| IngestError::NoModel {
+ solver: SOLVER,
+ saw: text
+ .lines()
+ .filter(|l| l.contains("exit") || l.contains("Exiting"))
+ .take(2)
+ .collect::<Vec<_>>()
+ .join(" / "),
+ })?;
+ let (domain, entries) = parse_entries(block)?;
+ if domain == 0 {
+ return Err(IngestError::EmptyDomain { solver: SOLVER });
+ }
+ let mut m = FiniteModel {
+ domain,
+ unary: BTreeMap::new(),
+ binary: BTreeMap::new(),
+ consts: BTreeMap::new(),
+ source: "mace4",
+ dropped: Vec::new(),
+ };
+ for e in entries {
+ let (image, kind) = match tab.demangle_kind(&e.name) {
+ Some((s, k)) => (s.to_string(), k),
+ None => {
+ m.dropped.push(e.name.clone());
+ continue;
+ }
+ };
+ // The TABLE is the authority on the arity, because the table is
+ // what wrote the file. A model that answers at a different one is
+ // a disagreement about the signature, and reading it into
+ // whichever slot the file suggests would file a unary predicate as
+ // a perfectly good binary interpretation and then report the unary
+ // slot as uninterpreted: a confusing message for a real defect.
+ let claimed = match (e.is_relation, e.arity) {
+ (true, 1) => Some(SymKind::Unary),
+ (true, 2) => Some(SymKind::Binary),
+ (false, 0) => Some(SymKind::Constant),
+ _ => None,
+ };
+ if claimed != Some(kind) {
+ return Err(IngestError::Unsupported {
+ solver: SOLVER,
+ construct: format!(
+ "{} of arity {}",
+ if e.is_relation { "a relation" } else { "a function" },
+ e.arity
+ ),
+ context: format!(
+ "the symbol {image:?}, mangled to {:?}, which the problem uses as a {} \
+ symbol",
+ e.name,
+ kind.name()
+ ),
+ });
+ }
+ match (e.is_relation, e.arity) {
+ (true, 1) => {
+ if e.table.len() != domain {
+ return Err(IngestError::BadWidth {
+ solver: SOLVER,
+ symbol: image,
+ want: domain,
+ got: e.table.len(),
+ });
+ }
+ m.unary.insert(image, e.table.iter().map(|v| *v != 0).collect());
+ }
+ (true, 2) => {
+ if e.table.len() != domain * domain {
+ return Err(IngestError::BadWidth {
+ solver: SOLVER,
+ symbol: image,
+ want: domain * domain,
+ got: e.table.len(),
+ });
+ }
+ let rows = e
+ .table
+ .chunks(domain)
+ .map(|c| c.iter().map(|v| *v != 0).collect())
+ .collect();
+ m.binary.insert(image, rows);
+ }
+ (false, 0) => {
+ let v = *e.table.first().ok_or_else(|| IngestError::Syntax {
+ solver: SOLVER,
+ at: image.clone(),
+ why: "a constant with an empty table".into(),
+ })?;
+ if v < 0 || v as usize >= domain {
+ return Err(IngestError::OutOfRange {
+ solver: SOLVER,
+ symbol: image,
+ index: v.max(0) as usize,
+ domain,
+ });
+ }
+ m.consts.insert(image, v as usize);
+ }
+ // Unreachable: the kind check above admits only the three
+ // shapes matched here. Kept as an error rather than an
+ // `unreachable!` so that a future edit to that check cannot
+ // turn a missed case into a panic in a library.
+ (r, a) => {
+ return Err(IngestError::Unsupported {
+ solver: SOLVER,
+ construct: format!(
+ "{} of arity {a}",
+ if r { "a relation" } else { "a function" }
+ ),
+ context: format!("the symbol {image:?}, mangled to {:?}", e.name),
+ });
+ }
+ }
+ }
+ m.self_check(SOLVER)?;
+ Ok(m)
+ }
+}
diff --git a/src/fol_solve.rs b/src/fol_solve.rs
new file mode 100644
index 00000000..378b8983
--- /dev/null
+++ b/src/fol_solve.rs
@@ -0,0 +1,819 @@
+//! The certifying pipeline: export, solve, ingest, CHECK, and report a verdict
+//! that says what it rests on.
+//!
+//! ```text
+//! FolProblem ──┬─ problem.tsv ─────────────────────────────┐
+//! │ │
+//! ├─ problem.smt2 ── z3 ─┐ │
+//! └─ problem.in ── mace4 ┴─ model.tsv ──── oo-folmodel
+//! │
+//! Fol.satisfiable_of_check
+//! ```
+//!
+//! One `FolProblem`, three files, ONE question. The solver's file and
+//! `problem.tsv` are both folds over `FolProblem::checker_entries`, so the
+//! thing the solver is asked and the thing the checker checks cannot drift
+//! apart by construction rather than by care.
+//!
+//! # The verdict discipline, which is the reason this exists
+//!
+//! Decision 0006 item 4 fixes five fields and five verdict words, and this
+//! module is where they are computed. The rules are mechanical, and
+//! `tests/fol_solver_verdict_test.rs` fails if any of them is ever relaxed:
+//!
+//! 1. `model_checked` requires `checker_exit == 0`. There is exactly one place
+//! in this file that writes that word and it is inside the branch that has
+//! just read a zero exit code off `oo-folmodel`. No other path can reach it.
+//! 2. `unsatisfiable_oracle` requires a run whose emitted problem carried NO
+//! cardinality constraint. It is written only in the arm that reads the
+//! unbounded probe's answer. A bounded run's `unsat` is
+//! `no_model_up_to_size_k`, which is not unsatisfiability: the formula
+//! `∀x∃y (r(x,y) ∧ x≠y)` is unsat at carrier 1 and sat at carrier 2.
+//! 3. `owl_reading` is non-null only when the CHECKER reported
+//! `goal_negated_present` and the verdict is `model_checked`. It is read
+//! back out of the checker's own JSON rather than taken from this side's
+//! intention, and it carries its own long word,
+//! `not_entailed_under_unproved_translation`, which must never be shortened
+//! to "not entailed": the OWL-level reading rides on `OwlLean.adequacy` in
+//! a sibling project AND on the Rust-to-Lean correspondence that decision
+//! 0005 item 2 states is pinned by tests and NOT proved.
+//!
+//! # A rejected model is a stop-the-line event
+//!
+//! If a solver answers `sat` and the verified checker then REJECTS the
+//! structure, two things that are supposed to agree do not. Either the solver
+//! is wrong, or the ingestion misread it, or the SMT-LIB/LADR printer does not
+//! say what `problem.tsv` says. None of those is a fact about the ontology, so
+//! the verdict stays `satisfiable_oracle` exactly as decision 0006 item 5
+//! requires and is NEVER `rejected` as though the ontology were at fault.
+//!
+//! But it is not a quiet fallback either. It is reported in its own
+//! [`Disagreement`] block with `severity: STOP_THE_LINE`, it is counted in the
+//! run summary, and it makes the command exit non-zero — the same treatment
+//! `tools/shacl_differential.py` gives a FALSE_CLEAN, and for the same reason:
+//! a disagreement between a checker and the thing it is checking is the one
+//! result that must fail a pipeline rather than be filed under "other".
+//!
+//! # What a green run does NOT say
+//!
+//! Nothing about unsatisfiability unless the word `unsatisfiable_oracle` is
+//! printed, and that word is an ORACLE's, never a certificate's. The absence
+//! of a finite model implies nothing: SHIQ lacks the finite model property, so
+//! a satisfiable ontology can have only infinite models and will never receive
+//! a certificate here. That is a limitation of the method and it is the honest
+//! counterweight to the asymmetry the layer is built on.
+
+use std::collections::BTreeMap;
+use std::io::Read as _;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+use crate::fol_model::{FiniteModel, IngestError, mace4, z3};
+use crate::tptp::{FolProblem, ladr, smtlib::SmtEncoding};
+
+/// Which model finder to drive.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Solver {
+ /// Z3 over SMT-LIB 2. Carrier declared as an enumeration datatype, so a
+ /// `sat` comes with a structure of known size; also the only one of the
+ /// two that can be asked the unbounded question.
+ Z3,
+ /// Mace4 over LADR. A dedicated finite model finder, from the
+ /// unmaintained Prover9 distribution whose REFUTATION half is uncheckable
+ /// and whose MODEL half is exactly what this layer certifies.
+ Mace4,
+}
+
+impl Solver {
+ pub fn parse(s: &str) -> anyhow::Result<Solver> {
+ match s.to_ascii_lowercase().as_str() {
+ "z3" | "smt" | "smtlib" => Ok(Solver::Z3),
+ "mace4" | "ladr" => Ok(Solver::Mace4),
+ other => anyhow::bail!("unknown model finder {other:?}; expected `z3` or `mace4`"),
+ }
+ }
+ pub fn name(self) -> &'static str {
+ match self {
+ Solver::Z3 => "z3",
+ Solver::Mace4 => "mace4",
+ }
+ }
+ pub fn binary(self) -> &'static str {
+ match self {
+ Solver::Z3 => "z3",
+ Solver::Mace4 => "mace4",
+ }
+ }
+ /// The line to print when the binary is missing. G6: a missing solver
+ /// SKIPS LOUDLY with the install line and never passes silently.
+ pub fn install_line(self) -> &'static str {
+ match self {
+ Solver::Z3 => "install Z3: `brew install z3` (macOS) or \
+ https://github.com/Z3Prover/z3/releases",
+ Solver::Mace4 => "install Mace4, which ships in the LADR/Prover9 distribution: \
+ `brew install prover9` (macOS) or \
+ https://www.cs.unm.edu/~mccune/prover9/",
+ }
+ }
+ /// The smallest carrier the finder can be asked about.
+ ///
+ /// Mace4's is 2, not 1: `mace4 -n 1` is a FATAL error, measured on LADR
+ /// 2009-11A (`assign_parm: parm start_size, value 1 out of range
+ /// [2..2147483647]`). A one-element model is therefore reachable through
+ /// Z3 and not through Mace4, and a ladder that started at 1 for both would
+ /// turn that into a fatal run rather than a skipped size.
+ pub fn min_domain(self) -> u32 {
+ match self {
+ Solver::Z3 => 1,
+ Solver::Mace4 => 2,
+ }
+ }
+ /// Whether the finder can be asked about an unbounded carrier at all.
+ /// Mace4 cannot: it is a finite model finder and every run of it is
+ /// bounded, so it can never produce `unsatisfiable_oracle`.
+ pub fn can_probe_unbounded(self) -> bool {
+ matches!(self, Solver::Z3)
+ }
+ pub fn available(self) -> bool {
+ which(self.binary()).is_some()
+ }
+}
+
+fn which(bin: &str) -> Option<PathBuf> {
+ let path = std::env::var_os("PATH")?;
+ std::env::split_paths(&path)
+ .map(|d| d.join(bin))
+ .find(|p| p.is_file())
+}
+
+/// How to run the pipeline.
+#[derive(Clone, Debug)]
+pub struct SolveOptions {
+ pub solver: Solver,
+ /// The largest carrier the ladder tries. Default 16, from the measured
+ /// cost of the compiled checker: about 9M evaluation points per second and
+ /// cubic in the carrier at quantifier depth 3, so 2000 formulas at carrier
+ /// 16 is 8.2M points and 0.92s while carrier 32 is 65.5M and 6.8s.
+ pub max_domain: u32,
+ /// Seconds per solver invocation.
+ pub timeout_secs: u32,
+ /// After a bounded ladder finds nothing, ask the UNBOUNDED question too.
+ /// This is the only route to `unsatisfiable_oracle` and it is off for
+ /// Mace4, which has no unbounded question.
+ pub unbounded_probe: bool,
+ /// Path to `oo-folmodel`. `None` looks in `lean/.lake/build/bin/` and on
+ /// `$PATH`, and reports loudly if it finds neither.
+ pub checker: Option<PathBuf>,
+}
+
+impl Default for SolveOptions {
+ fn default() -> Self {
+ SolveOptions {
+ solver: Solver::Z3,
+ max_domain: 16,
+ timeout_secs: 30,
+ unbounded_probe: true,
+ checker: None,
+ }
+ }
+}
+
+/// What a single solver invocation said.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SolverSays {
+ Sat,
+ Unsat,
+ Unknown,
+}
+
+impl SolverSays {
+ pub fn name(self) -> &'static str {
+ match self {
+ SolverSays::Sat => "sat",
+ SolverSays::Unsat => "unsat",
+ SolverSays::Unknown => "unknown",
+ }
+ }
+}
+
+/// A disagreement between two things that were supposed to agree. Not a
+/// verdict about the ontology, and not a footnote either.
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct Disagreement {
+ pub severity: &'static str,
+ pub what: &'static str,
+ pub detail: String,
+ pub means: &'static str,
+}
+
+/// The five fields decision 0006 fixes, plus what is needed to audit them.
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct Outcome {
+ /// What the oracle said, on the run that decided the verdict.
+ pub solver_verdict: &'static str,
+ /// What it was asked. `unbounded` or `finite(k)`.
+ pub encoding: String,
+ /// `null` means the checker was never run.
+ pub checker_exit: Option<i32>,
+ /// The one word. See the module docstring for the three mechanical rules.
+ pub verdict: &'static str,
+ /// Non-null only when the CHECKER reported a negated goal AND the verdict
+ /// is `model_checked`.
+ pub owl_reading: Option<&'static str>,
+
+ /// The theorem the certified verdict names, when there is one.
+ pub theorem: Option<String>,
+ /// The sizes the ladder tried, in order.
+ pub cardinality_search: Vec<u32>,
+ /// What the bounded ladder established, separately from the verdict, so
+ /// that an unbounded probe's answer cannot erase it.
+ pub bounded_search: String,
+ /// The unbounded probe's answer, when it ran. This is the ONLY field the
+ /// `unsatisfiable_oracle` verdict is allowed to be computed from.
+ pub unbounded: Option<&'static str>,
+ /// `oo-folmodel`'s own JSON, verbatim, when it ran.
+ pub checker_report: Option<String>,
+ /// Symbols the solver interpreted that the translation never emitted, so
+ /// the checked structure is a reduct of the solver's.
+ pub dropped_symbols: Vec<String>,
+ pub problem_digest: String,
+ pub formulas: usize,
+ /// Set when a checker and the thing it checks disagreed. Stop the line.
+ pub disagreement: Option<Disagreement>,
+ /// Set when the run could not happen at all. G6: loud, never silent.
+ pub skipped: Option<String>,
+ pub seconds: f64,
+}
+
+impl Outcome {
+ /// A run that did not happen, with the reason. `reason` is the whole
+ /// sentence: the caller appends the install line where there is one,
+ /// because a missing CHECKER has nothing to do with the solver's.
+ fn skip(reason: String) -> Outcome {
+ Outcome {
+ solver_verdict: "unknown",
+ encoding: "none".into(),
+ checker_exit: None,
+ verdict: "unknown_oracle",
+ owl_reading: None,
+ theorem: None,
+ cardinality_search: Vec::new(),
+ bounded_search: "not run".into(),
+ unbounded: None,
+ checker_report: None,
+ dropped_symbols: Vec::new(),
+ problem_digest: String::new(),
+ formulas: 0,
+ disagreement: None,
+ skipped: Some(reason),
+ seconds: 0.0,
+ }
+ }
+}
+
+/// Find `oo-folmodel`.
+///
+/// Its absence is reported rather than worked around. A pipeline that quietly
+/// dropped to an oracle verdict because the checker was not built would make
+/// every run look like a solver limitation, which is the precise shape of
+/// mis-attribution this repository exists to catch.
+pub fn find_checker(explicit: Option<&Path>) -> Result<PathBuf, String> {
+ if let Some(p) = explicit {
+ return if p.is_file() {
+ Ok(p.to_path_buf())
+ } else {
+ Err(format!("no oo-folmodel at {}", p.display()))
+ };
+ }
+ if let Ok(v) = std::env::var("OO_FOLMODEL") {
+ let p = PathBuf::from(v);
+ if p.is_file() {
+ return Ok(p);
+ }
+ }
+ let here = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("lean/.lake/build/bin/oo-folmodel");
+ if here.is_file() {
+ return Ok(here);
+ }
+ if let Some(p) = which("oo-folmodel") {
+ return Ok(p);
+ }
+ Err(format!(
+ "oo-folmodel, the verified checker. Build it with `cd lean && lake build` (it is in \
+ defaultTargets, so a bare `lake build` is enough), or set OO_FOLMODEL. Looked in {} \
+ and on PATH",
+ here.display()
+ ))
+}
+
+/// Run a command with a wall-clock limit, capturing stdout+stderr to a file.
+///
+/// Output goes to a FILE and not a pipe: a solver that fills a pipe while
+/// nobody reads it deadlocks, and Mace4 is chatty.
+fn run_limited(
+ mut cmd: Command,
+ out_path: &Path,
+ limit: Duration,
+) -> std::io::Result<(Option<i32>, String, bool)> {
+ let f = std::fs::File::create(out_path)?;
+ let f2 = f.try_clone()?;
+ cmd.stdout(Stdio::from(f)).stderr(Stdio::from(f2)).stdin(Stdio::null());
+ let mut child = cmd.spawn()?;
+ let start = Instant::now();
+ let mut timed_out = false;
+ let code = loop {
+ match child.try_wait()? {
+ Some(status) => break status.code(),
+ None => {
+ if start.elapsed() > limit {
+ let _ = child.kill();
+ let _ = child.wait();
+ timed_out = true;
+ break None;
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ }
+ };
+ let mut text = String::new();
+ std::fs::File::open(out_path)?.read_to_string(&mut text).ok();
+ Ok((code, text, timed_out))
+}
+
+fn read_sat(text: &str) -> SolverSays {
+ // The FIRST standalone status line. Z3 prints `sat` / `unsat` / `unknown`
+ // on its own line before the model, and `(error …)` before that if the
+ // file was bad. Matching a bare substring would find the `unsat` inside
+ // `unsatisfiable` in a comment, which is why this is line-oriented.
+ for line in text.lines() {
+ match line.trim() {
+ "sat" => return SolverSays::Sat,
+ "unsat" => return SolverSays::Unsat,
+ "unknown" => return SolverSays::Unknown,
+ _ => {}
+ }
+ }
+ SolverSays::Unknown
+}
+
+/// Mace4's exit codes, measured on LADR 2009-11A on this machine:
+/// 0 a model was found (`exit (max_models)`), 1 a FATAL error (including
+/// `-n 1`, whose carrier is below its minimum of 2), 2 the search was
+/// exhausted with no model (`exit (exhausted)`). Anything else is a resource
+/// limit and is `unknown`, never `unsat`.
+fn read_mace4(code: Option<i32>, text: &str, timed_out: bool) -> (SolverSays, Option<String>) {
+ if timed_out {
+ return (SolverSays::Unknown, None);
+ }
+ match code {
+ Some(0) => (SolverSays::Sat, None),
+ Some(2) => (SolverSays::Unsat, None),
+ Some(1) => (
+ SolverSays::Unknown,
+ Some(format!(
+ "mace4 exited 1 (fatal). It said: {}",
+ text.lines()
+ .filter(|l| l.contains("Fatal") || l.contains("error"))
+ .take(3)
+ .collect::<Vec<_>>()
+ .join(" / ")
+ )),
+ ),
+ other => (
+ SolverSays::Unknown,
+ Some(format!("mace4 exited {other:?}, which is a resource limit, not a verdict")),
+ ),
+ }
+}
+
+/// One bounded attempt at one carrier size.
+struct Attempt {
+ says: SolverSays,
+ model: Option<Result<FiniteModel, IngestError>>,
+ note: Option<String>,
+}
+
+#[allow(clippy::too_many_arguments)]
+fn attempt(
+ problem: &FolProblem,
+ opts: &SolveOptions,
+ dir: &Path,
+ k: u32,
+ table: Option<&ladr::SymbolTable>,
+) -> anyhow::Result<Attempt> {
+ let limit = Duration::from_secs(opts.timeout_secs.max(1) as u64);
+ match opts.solver {
+ Solver::Z3 => {
+ let enc = SmtEncoding::Finite(k);
+ let file = dir.join(format!("problem_k{k}.smt2"));
+ std::fs::write(&file, problem.to_smtlib(enc)?)?;
+ let mut cmd = Command::new("z3");
+ cmd.arg(format!("-T:{}", opts.timeout_secs.max(1))).arg(&file);
+ let (_, text, timed_out) =
+ run_limited(cmd, &dir.join(format!("z3_k{k}.out")), limit)?;
+ let says = if timed_out { SolverSays::Unknown } else { read_sat(&text) };
+ let model = match says {
+ SolverSays::Sat => {
+ Some(z3::parse_model(&text, &problem.vocabulary(), k as usize))
+ }
+ _ => None,
+ };
+ Ok(Attempt { says, model, note: None })
+ }
+ Solver::Mace4 => {
+ let tab = table.expect("mace4 needs a symbol table");
+ let file = dir.join("problem.in");
+ if !file.exists() {
+ std::fs::write(&file, ladr::problem(problem, tab, opts.timeout_secs.max(1))?)?;
+ }
+ let mut cmd = Command::new("mace4");
+ cmd.arg("-n").arg(k.to_string())
+ .arg("-N").arg(k.to_string())
+ .arg("-t").arg(opts.timeout_secs.max(1).to_string())
+ .arg("-f").arg(&file);
+ let (code, text, timed_out) =
+ run_limited(cmd, &dir.join(format!("mace4_k{k}.out")), limit)?;
+ let (says, note) = read_mace4(code, &text, timed_out);
+ let model = match says {
+ SolverSays::Sat => Some(mace4::parse_model(&text, tab)),
+ _ => None,
+ };
+ Ok(Attempt { says, model, note })
+ }
+ }
+}
+
+/// Export, solve, ingest, check, and report.
+///
+/// `dir` receives every intermediate file, so a run is reproducible by hand
+/// from what it left behind: the problem in the checker's format, the problem
+/// in the solver's, the solver's raw output, the model in the checker's
+/// format, and the checker's own JSON.
+pub fn solve(problem: &FolProblem, opts: &SolveOptions, dir: &Path) -> anyhow::Result<Outcome> {
+ let started = Instant::now();
+ std::fs::create_dir_all(dir)?;
+
+ if !opts.solver.available() {
+ // G6. Loud, with the install line, and never a silent pass. The
+ // distinctive marker is the same one tests/common/mod.rs uses.
+ let msg = format!(
+ "missing solver: {} ({})",
+ opts.solver.binary(),
+ opts.solver.install_line()
+ );
+ eprintln!("SKIPPED_SOLVER: {msg}");
+ return Ok(Outcome::skip(msg));
+ }
+ let checker = match find_checker(opts.checker.as_deref()) {
+ Ok(p) => p,
+ Err(why) => {
+ eprintln!("SKIPPED_CHECKER: {why}");
+ return Ok(Outcome::skip(format!("missing checker: {why}")));
+ }
+ };
+
+ let (problem_tsv, digest) = problem.to_problem_tsv()?;
+ std::fs::write(dir.join("problem.tsv"), &problem_tsv)?;
+ let entries = problem.checker_entries();
+ let table = match opts.solver {
+ Solver::Mace4 => {
+ let t = ladr::SymbolTable::build(problem)?;
+ std::fs::write(dir.join("symbols.tsv"), ladr::table_tsv(&t))?;
+ Some(t)
+ }
+ Solver::Z3 => None,
+ };
+
+ let mut out = Outcome {
+ solver_verdict: "unknown",
+ encoding: "none".into(),
+ checker_exit: None,
+ verdict: "unknown_oracle",
+ owl_reading: None,
+ theorem: None,
+ cardinality_search: Vec::new(),
+ bounded_search: String::new(),
+ unbounded: None,
+ checker_report: None,
+ dropped_symbols: Vec::new(),
+ problem_digest: digest.clone(),
+ formulas: entries.len(),
+ disagreement: None,
+ skipped: None,
+ seconds: 0.0,
+ };
+
+ // ── The bounded ladder ──────────────────────────────────────────────
+ let lo = opts.solver.min_domain();
+ let hi = opts.max_domain.max(lo);
+ let mut last_unknown: Option<String> = None;
+ for k in lo..=hi {
+ out.cardinality_search.push(k);
+ let a = attempt(problem, opts, dir, k, table.as_ref())?;
+ match a.says {
+ SolverSays::Unsat => continue,
+ SolverSays::Unknown => {
+ last_unknown = a.note.or_else(|| {
+ Some(format!("{} gave no verdict at carrier {k}", opts.solver.name()))
+ });
+ break;
+ }
+ SolverSays::Sat => {
+ out.solver_verdict = "sat";
+ out.encoding = SmtEncoding::Finite(k).name();
+ out.bounded_search = format!("a model was reported at carrier {k}");
+ let model = match a.model.expect("sat carries a model attempt") {
+ Ok(m) => m,
+ Err(e) => {
+ // The solver said sat and we could not read what it
+ // built. Not a fact about the ontology, and not quiet.
+ out.verdict = "satisfiable_oracle";
+ out.disagreement = Some(Disagreement {
+ severity: "STOP_THE_LINE",
+ what: "model_not_ingested",
+ detail: e.to_string(),
+ means: "the solver answered sat and this pipeline could not turn \
+ what it printed into a structure, so NOTHING was checked. \
+ Either the ingestion is wrong or the solver printed \
+ something it has not printed before. This is a defect in \
+ the pipeline until shown otherwise, and it is not a \
+ statement about the ontology",
+ });
+ out.seconds = started.elapsed().as_secs_f64();
+ return Ok(out);
+ }
+ };
+ out.dropped_symbols = model.dropped.clone();
+ if let Err(e) = model.covers(&problem.vocabulary(), opts.solver.name()) {
+ out.verdict = "satisfiable_oracle";
+ out.disagreement = Some(Disagreement {
+ severity: "STOP_THE_LINE",
+ what: "model_incomplete",
+ detail: e.to_string(),
+ means: "the solver answered sat and left a symbol of the problem \
+ uninterpreted. The checker's own coverage gate would report \
+ this as an ATTRIBUTION failure; it is caught here so the \
+ message can name the solver. Nothing was certified",
+ });
+ out.seconds = started.elapsed().as_secs_f64();
+ return Ok(out);
+ }
+ let model_tsv = model.to_model_tsv(&digest, &out.cardinality_search);
+ let model_path = dir.join("model.tsv");
+ std::fs::write(&model_path, &model_tsv)?;
+
+ // ── The only place the certified word can be reached ──
+ let co = Command::new(&checker)
+ .arg(dir.join("problem.tsv"))
+ .arg(&model_path)
+ .output()?;
+ let report = String::from_utf8_lossy(&co.stdout).trim().to_string();
+ std::fs::write(dir.join("checker.json"), &report)?;
+ let exit = co.status.code().unwrap_or(-1);
+ out.checker_exit = Some(exit);
+ out.checker_report = Some(report.clone());
+ if exit == 0 {
+ out.verdict = "model_checked";
+ out.theorem = Some("Fol.satisfiable_of_check".to_string());
+ // Read the goal flag back off the CHECKER's report, not
+ // off this side's intention.
+ if report.contains("\"goal_negated_present\":true") {
+ out.owl_reading = Some("not_entailed_under_unproved_translation");
+ }
+ } else {
+ out.verdict = "satisfiable_oracle";
+ out.disagreement = Some(Disagreement {
+ severity: "STOP_THE_LINE",
+ what: "model_not_confirmed",
+ detail: format!(
+ "oo-folmodel exited {exit} on the structure {} reported. It said: \
+ {report}",
+ opts.solver.name()
+ ),
+ means: "a solver answered sat and the VERIFIED checker rejected the \
+ structure it produced. One of the solver, the ingestion and \
+ the two printers is wrong, and this is not a statement about \
+ the ontology: the verdict stays satisfiable_oracle and is \
+ never `rejected`. Treat it the way shacl_differential.py \
+ treats a false clean",
+ });
+ }
+ out.seconds = started.elapsed().as_secs_f64();
+ return Ok(out);
+ }
+ }
+ }
+
+ // ── The ladder found nothing ────────────────────────────────────────
+ match &last_unknown {
+ Some(why) => {
+ out.solver_verdict = "unknown";
+ out.encoding = SmtEncoding::Finite(*out.cardinality_search.last().unwrap_or(&hi)).name();
+ out.bounded_search = format!("stopped: {why}");
+ out.verdict = "unknown_oracle";
+ }
+ None => {
+ out.solver_verdict = "unsat";
+ out.encoding = SmtEncoding::Finite(hi).name();
+ out.bounded_search = format!("exhausted: no model of size {lo}..{hi}");
+ // NOT unsatisfiability. Decision 0006 item 4.
+ out.verdict = "no_model_up_to_size_k";
+ }
+ }
+
+ // ── The unbounded probe, the only route to unsatisfiable_oracle ─────
+ if opts.unbounded_probe && opts.solver.can_probe_unbounded() && last_unknown.is_none() {
+ let file = dir.join("problem_unbounded.smt2");
+ std::fs::write(&file, problem.to_smtlib(SmtEncoding::Unbounded)?)?;
+ let mut cmd = Command::new("z3");
+ cmd.arg(format!("-T:{}", opts.timeout_secs.max(1))).arg(&file);
+ let (_, text, timed_out) = run_limited(
+ cmd,
+ &dir.join("z3_unbounded.out"),
+ Duration::from_secs(opts.timeout_secs.max(1) as u64),
+ )?;
+ let says = if timed_out { SolverSays::Unknown } else { read_sat(&text) };
+ out.unbounded = Some(says.name());
+ match says {
+ SolverSays::Unsat => {
+ out.solver_verdict = "unsat";
+ out.encoding = SmtEncoding::Unbounded.name();
+ out.verdict = "unsatisfiable_oracle";
+ }
+ SolverSays::Sat => {
+ out.solver_verdict = "sat";
+ out.encoding = SmtEncoding::Unbounded.name();
+ // Satisfiable, and with no finite model small enough to
+ // certify. Exactly the SHIQ finite-model-property case.
+ out.verdict = "satisfiable_oracle";
+ }
+ SolverSays::Unknown => {}
+ }
+ }
+
+ out.seconds = started.elapsed().as_secs_f64();
+ Ok(out)
+}
+
+/// The JSON one run reports, with the vocabulary written out beside the
+/// verdict so that a reader who has never opened decision 0006 still cannot
+/// mistake an oracle's word for a certificate's.
+pub fn outcome_json(o: &Outcome) -> serde_json::Value {
+ serde_json::json!({
+ "solver_verdict": o.solver_verdict,
+ "encoding": o.encoding,
+ "checker_exit": o.checker_exit,
+ "verdict": o.verdict,
+ "owl_reading": o.owl_reading,
+ "theorem": o.theorem,
+ "formulas": o.formulas,
+ "problem_digest": o.problem_digest,
+ "cardinality_search": o.cardinality_search,
+ "bounded_search": o.bounded_search,
+ "unbounded_probe": o.unbounded,
+ "dropped_symbols": o.dropped_symbols,
+ "checker_report": o.checker_report,
+ "disagreement": o.disagreement,
+ "skipped": o.skipped,
+ "seconds": (o.seconds * 1000.0).round() / 1000.0,
+ "verdict_means": verdict_means(o.verdict),
+ })
+}
+
+/// One sentence per word, so a report is readable without the decision record
+/// open beside it.
+pub fn verdict_means(v: &str) -> &'static str {
+ match v {
+ "model_checked" => "CERTIFIED. A finite structure was checked against the problem by \
+ lean/Fol/, whose soundness is machine-checked: \
+ Fol.satisfiable_of_check turns an accepted structure into \
+ Satisfiable. This says nothing about unsatisfiability in any \
+ direction",
+ "satisfiable_oracle" => "a solver said satisfiable and no structure was certified. \
+ Trust the solver or do not; nothing here checked it",
+ "no_model_up_to_size_k" => "a bounded search was exhausted. This is NOT \
+ unsatisfiability: a theory with no model of size k can \
+ have one of size k+1, and SHIQ has no finite model \
+ property at all, so a satisfiable ontology can have only \
+ infinite models",
+ "unsatisfiable_oracle" => "a solver said unsatisfiable on the UNBOUNDED encoding. It \
+ can never be more than an oracle opinion: checking a \
+ refutation needs a verified first-order calculus with \
+ unification, which does not exist in core Lean \
+ (decision 0005)",
+ "unknown_oracle" => "the solver timed out, gave up, or is incomplete on this problem. \
+ Not evidence in either direction",
+ _ => "unrecognised verdict",
+ }
+}
+
+/// Run the pipeline over the loaded ontology and, optionally, one problem per
+/// goal. Returns the report JSON.
+pub fn solve_export(
+ graph: &std::sync::Arc<crate::graph::GraphStore>,
+ dir: &Path,
+ opts: &SolveOptions,
+ goals: Option<&Path>,
+ goals_skip_columns: usize,
+) -> anyhow::Result<String> {
+ let triples = graph.all_triples()?;
+ let read = crate::tptp::read_graph(triples);
+ std::fs::create_dir_all(dir)?;
+
+ let base = FolProblem::build(&read.axioms, None)?;
+ let ontology = solve(&base, opts, &dir.join("ontology"))?;
+
+ let mut goal_reports = Vec::new();
+ // A goal the fragment cannot express is NAMED, not skipped. `tptp::export`
+ // already reports its `not_asked` list for the same reason: a run that
+ // silently asked fewer questions than the file contained would report a
+ // clean sweep over a subset nobody chose, which is the shape decision 0005
+ // item 7 records happening in this repository already.
+ let mut not_asked: Vec<serde_json::Value> = Vec::new();
+ let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
+ *counts.entry(ontology.verdict).or_default() += 1;
+ let mut stop_the_line = usize::from(ontology.disagreement.is_some());
+
+ if let Some(path) = goals {
+ let text = std::fs::read_to_string(path)?;
+ for (i, line) in text.lines().enumerate() {
+ if line.trim().is_empty() {
+ continue;
+ }
+ let cols: Vec<&str> = line.split('\t').collect();
+ if cols.len() < goals_skip_columns + 3 {
+ not_asked.push(serde_json::json!({
+ "line": line,
+ "why": format!(
+ "fewer than {} tab-separated columns",
+ goals_skip_columns + 3
+ ),
+ }));
+ continue;
+ }
+ let (s, p, o) = (
+ cols[goals_skip_columns],
+ cols[goals_skip_columns + 1],
+ cols[goals_skip_columns + 2],
+ );
+ let ax = match crate::tptp::triple_as_axiom(&read, s, p, o) {
+ Ok(ax) => ax,
+ Err(why) => {
+ not_asked.push(serde_json::json!({
+ "triple": [s, p, o],
+ "why": why,
+ }));
+ continue;
+ }
+ };
+ let gp = FolProblem::build(&read.axioms, Some(&ax))?;
+ let g = solve(&gp, opts, &dir.join(format!("goal_{i:05}")))?;
+ *counts.entry(g.verdict).or_default() += 1;
+ if g.disagreement.is_some() {
+ stop_the_line += 1;
+ }
+ goal_reports.push(serde_json::json!({
+ "triple": [s, p, o],
+ "outcome": outcome_json(&g),
+ }));
+ }
+ }
+
+ Ok(serde_json::json!({
+ "solver": opts.solver.name(),
+ "max_domain": opts.max_domain,
+ "timeout_secs": opts.timeout_secs,
+ "dir": dir.display().to_string(),
+ "ontology": outcome_json(&ontology),
+ "goals": goal_reports,
+ "goals_not_asked": not_asked.len(),
+ "not_asked": not_asked,
+ "not_asked_means": "no axiom form in OwlLean/Syntax.lean corresponds to the triple, so \
+ the question could not be put at all. NOT evidence about the \
+ ontology in either direction, and listed rather than skipped so a \
+ run cannot report a clean sweep over a subset nobody chose",
+ "verdict_counts": counts,
+ "verdict_counts_include_the_ontology_itself": true,
+ "stop_the_line": stop_the_line,
+ "stop_the_line_means": "a solver answered sat and the VERIFIED checker rejected, or \
+ could not be given, the structure it produced. The command \
+ exits non-zero on any of these, the way \
+ tools/shacl_differential.py exits non-zero on a FALSE_CLEAN. \
+ It is a bug in the solver, the ingestion or the printers, and \
+ it is NOT a statement about the ontology",
+ "not_certified": "only the verdict `model_checked` rests on a machine-checked theorem. \
+ `unsatisfiable_oracle` is a solver's opinion and can never be more, \
+ because checking a refutation needs a verified first-order calculus \
+ with unification that does not exist in core Lean. \
+ `no_model_up_to_size_k` is a statement about a bounded search and \
+ not about satisfiability",
+ "owl_reading_means": "the OWL-level sentence rides on OwlLean.adequacy in the sibling \
+ owl-lean project AND on the Rust-to-Lean translation \
+ correspondence, which decision 0005 item 2 states is PINNED BY \
+ TESTS AND NOT PROVED. That is why it carries its own word and \
+ must never be shortened to `not entailed`",
+ })
+ .to_string())
+}
diff --git a/src/inputs.rs b/src/inputs.rs
index 390a5540..376eb261 100644
--- a/src/inputs.rs
+++ b/src/inputs.rs
@@ -317,6 +317,40 @@ pub struct OntoFolExportInput {
/// lose the entire content of such a file, BFO's own included. Ignored
/// for `tptp`.
pub clif_comments: Option<String>,
+ /// Carrier size, when `format` is `smtlib`. Omit for the UNBOUNDED
+ /// encoding (`declare-sort U 0`), where a solver's `unsat` really is
+ /// unsatisfiability and a `sat` carries no size bound. Set to `k` for the
+ /// FINITE encoding (`U` as an enumeration datatype of exactly k elements),
+ /// where a `sat` comes with a structure `oo-folmodel` can check and an
+ /// `unsat` establishes ONLY that no model of size k exists, which is not
+ /// unsatisfiability. Ignored for every other format; 0 is refused.
+ pub smt_domain: Option<u32>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoFolModelInput {
+ /// Working directory. Every intermediate file lands here: the problem in
+ /// the checker's format, the problem in the solver's, the solver's raw
+ /// output, the model in the checker's format, and the checker's own JSON.
+ pub out_dir: String,
+ /// `z3` (default; SMT-LIB, and the only finder that can be asked the
+ /// UNBOUNDED question, hence the only route to `unsatisfiable_oracle`) or
+ /// `mace4` (LADR, a dedicated finite model finder whose minimum carrier
+ /// is 2, measured: `mace4 -n 1` is a fatal error).
+ pub solver: Option<String>,
+ /// Largest carrier the ladder tries. Default 16.
+ pub max_domain: Option<u32>,
+ /// Seconds per solver invocation. Default 30.
+ pub timeout_secs: Option<u32>,
+ /// After a bounded ladder finds nothing, ask the UNBOUNDED question too.
+ /// Default true, and Z3 only. This is the ONLY route to
+ /// `unsatisfiable_oracle`.
+ pub unbounded_probe: Option<bool>,
+ /// A TSV of triples to ask as conjectures, one run per line; the shape
+ /// `onto_reason` writes with `certificate_dir`.
+ pub goals_file: Option<String>,
+ /// Leading tab-separated columns to skip before the subject. Default 0.
+ pub goals_skip_columns: Option<usize>,
}
#[derive(Deserialize, JsonSchema)]
diff --git a/src/lib.rs b/src/lib.rs
index 249d40f3..136886ea 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -86,6 +86,8 @@ pub mod tableaux;
pub mod toolfilter;
/// First-order export (TPTP FOF and ISO/IEC 24707 CLIF) over the translation
/// owl-lean's machine-checked adequacy theorem is about.
+pub mod fol_model;
+pub mod fol_solve;
pub mod tptp;
#[cfg(feature = "turbovec")]
pub mod turbo_index;
diff --git a/src/main.rs b/src/main.rs
index d53049f2..0bbda9f5 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -443,21 +443,37 @@ enum Commands {
#[arg(long)]
rules: Option<String>,
},
- /// Export the loaded ontology as first-order logic, for an ATP
+ /// Export the loaded ontology as first-order logic, for a prover or a model finder
///
/// The translation is the one owl-lean's machine-checked adequacy theorem
/// (`OwlLean.adequacy`) is about. The correspondence between this emitter
/// and that Lean is PINNED BY TESTS AND NOT ITSELF PROVED, and a prover's
- /// verdict on the output is an oracle opinion, never a certificate.
+ /// verdict on the output is an oracle opinion, never a certificate. A
+ /// MODEL is the other case: see `fol-model`.
Fol {
- /// Output directory. `ontology.p` (or `.clif`) lands here, plus one
- /// problem per goal under `goals/` when --goals is given.
+ /// Output directory. `ontology.p`, `.clif`, `.smt2` or `.in` lands
+ /// here, plus one problem per goal under `goals/` when --goals is
+ /// given. Every run also writes `problem.tsv`, the format the verified
+ /// checker `oo-folmodel` reads, with its digest in the report.
#[arg(long)]
out: String,
- /// `tptp` (FOF, what provers read) or `clif` (ISO/IEC 24707 Common
- /// Logic, restricted to the first-order-equivalent fragment).
+ /// `tptp` (FOF, what provers read), `clif` (ISO/IEC 24707 Common
+ /// Logic, restricted to the first-order-equivalent fragment),
+ /// `smtlib` (SMT-LIB 2, what Z3 reads) or `ladr` (what Mace4 reads,
+ /// with every symbol MANGLED and the table in `symbols.tsv`).
+ ///
+ /// The last two assert the NEGATED goal rather than declaring a
+ /// conjecture, because they are read by model finders and a
+ /// countermodel to `G |= phi` is a model of `G + {not phi}`.
#[arg(long, default_value = "tptp")]
format: String,
+ /// With --format smtlib: the carrier size. Omitted gives the UNBOUNDED
+ /// encoding, where `unsat` really is unsatisfiability. Given `k`, the
+ /// carrier is an enumeration datatype of exactly k elements, a `sat`
+ /// comes with a structure `oo-folmodel` can check, and an `unsat`
+ /// establishes only that no model of size k exists.
+ #[arg(long)]
+ smt_domain: Option<u32>,
/// With --format clif: `iso` (default, `cl:text`, what ISO/IEC 21838-2
/// publishes BFO in) or `colore` (`cl-text`, what COLORE and the
/// Macleod toolchain read; Macleod cannot read the ISO spelling).
@@ -478,6 +494,46 @@ enum Commands {
#[arg(long, default_value_t = 0)]
goals_skip_columns: usize,
},
+ /// Find a finite model and CHECK it, for a verdict that says what it rests on
+ ///
+ /// Export, run Z3 or Mace4, read the structure back, and hand it to the
+ /// verified checker `oo-folmodel`. Only the verdict `model_checked` rests
+ /// on a machine-checked theorem (`Fol.satisfiable_of_check`). A solver's
+ /// `unsat` is an ORACLE OPINION and can never be more, and an exhausted
+ /// BOUNDED search is `no_model_up_to_size_k`, which is not
+ /// unsatisfiability. Exits 1 if any run is a stop-the-line disagreement.
+ FolModel {
+ /// Working directory. Every intermediate file lands here, so a run is
+ /// reproducible by hand from what it leaves behind.
+ #[arg(long)]
+ out: String,
+ /// `z3` (SMT-LIB, and the only one that can be asked the UNBOUNDED
+ /// question) or `mace4` (LADR, a dedicated finite model finder whose
+ /// minimum carrier is 2).
+ #[arg(long, default_value = "z3")]
+ solver: String,
+ /// The largest carrier the ladder tries. The default is from the
+ /// measured cost of the compiled checker: about 9M evaluation points
+ /// per second, cubic in the carrier at quantifier depth 3.
+ #[arg(long, default_value_t = 16)]
+ max_domain: u32,
+ #[arg(long, default_value_t = 30)]
+ timeout_secs: u32,
+ /// After a bounded ladder finds nothing, ask the UNBOUNDED question
+ /// too. This is the ONLY route to `unsatisfiable_oracle`. Z3 only.
+ #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
+ unbounded_probe: bool,
+ /// A TSV of triples to ask as conjectures, one run per line, the same
+ /// shape `fol --goals` takes.
+ #[arg(long)]
+ goals: Option<String>,
+ #[arg(long, default_value_t = 0)]
+ goals_skip_columns: usize,
+ /// Path to `oo-folmodel`. Defaults to `lean/.lake/build/bin/` then
+ /// `$PATH`; its absence is reported loudly and never worked around.
+ #[arg(long)]
+ checker: Option<String>,
+ },
/// Full pipeline: ingest → SHACL → reason
Extend {
data_path: String,
@@ -680,7 +736,7 @@ impl Commands {
}
cmd("reason", a)
}
- Commands::Fol { out, format, clif_dialect, clif_comments, goals, goals_skip_columns } => {
+ Commands::Fol { out, format, smt_domain, clif_dialect, clif_comments, goals, goals_skip_columns } => {
let mut a = vec![
"--out".into(),
absolutize(out),
@@ -691,6 +747,10 @@ impl Commands {
"--clif-comments".into(),
clif_comments.clone(),
];
+ if let Some(k) = smt_domain {
+ a.push("--smt-domain".into());
+ a.push(k.to_string());
+ }
if let Some(g) = goals {
a.push("--goals".into());
a.push(absolutize(g));
@@ -699,6 +759,40 @@ impl Commands {
}
cmd("fol", a)
}
+ Commands::FolModel {
+ out,
+ solver,
+ max_domain,
+ timeout_secs,
+ unbounded_probe,
+ goals,
+ goals_skip_columns,
+ checker,
+ } => {
+ let mut a = vec![
+ "--out".into(),
+ absolutize(out),
+ "--solver".into(),
+ solver.clone(),
+ "--max-domain".into(),
+ max_domain.to_string(),
+ "--timeout-secs".into(),
+ timeout_secs.to_string(),
+ "--unbounded-probe".into(),
+ unbounded_probe.to_string(),
+ ];
+ if let Some(g) = goals {
+ a.push("--goals".into());
+ a.push(absolutize(g));
+ a.push("--goals-skip-columns".into());
+ a.push(goals_skip_columns.to_string());
+ }
+ if let Some(c) = checker {
+ a.push("--checker".into());
+ a.push(absolutize(c));
+ }
+ cmd("fol-model", a)
+ }
Commands::Shacl { shapes } => cmd("shacl", vec![absolutize(shapes)]),
Commands::Status => cmd("status", vec![]),
Commands::Pull { url, sparql, query } => {
@@ -2411,12 +2505,56 @@ async fn async_main() -> anyhow::Result<()> {
};
output_result_checked(&result, cli.pretty);
}
- Commands::Fol { out, format, clif_dialect, clif_comments, goals, goals_skip_columns } => {
+ Commands::FolModel {
+ out,
+ solver,
+ max_domain,
+ timeout_secs,
+ unbounded_probe,
+ goals,
+ goals_skip_columns,
+ checker,
+ } => {
+ use open_ontologies::fol_solve::{SolveOptions, Solver, solve_export};
+ let (_db, graph) = setup(&cli.data_dir)?;
+ let result = match Solver::parse(&solver) {
+ Ok(s) => {
+ let opts = SolveOptions {
+ solver: s,
+ max_domain,
+ timeout_secs,
+ unbounded_probe,
+ checker: checker.as_deref().map(std::path::PathBuf::from),
+ };
+ solve_export(
+ &graph,
+ std::path::Path::new(&out),
+ &opts,
+ goals.as_deref().map(std::path::Path::new),
+ goals_skip_columns,
+ )
+ .unwrap_or_else(|e| serde_json::json!({"error": e.to_string()}).to_string())
+ }
+ Err(e) => serde_json::json!({"error": e.to_string()}).to_string(),
+ };
+ output_result_checked(&result, cli.pretty);
+ // A stop-the-line disagreement must fail a pipeline, the way
+ // tools/shacl_differential.py exits 1 on a FALSE_CLEAN.
+ let stop = serde_json::from_str::<serde_json::Value>(&result)
+ .ok()
+ .and_then(|v| v.get("stop_the_line").and_then(|n| n.as_u64()))
+ .unwrap_or(0);
+ if stop > 0 {
+ std::process::exit(1);
+ }
+ }
+ Commands::Fol { out, format, smt_domain, clif_dialect, clif_comments, goals, goals_skip_columns } => {
let (_db, graph) = setup(&cli.data_dir)?;
let result = match open_ontologies::tptp::Syntax::parse(
&format,
Some(&clif_dialect),
Some(&clif_comments),
+ smt_domain,
) {
Ok(syntax) => open_ontologies::tptp::export(
&graph,
@@ -2944,7 +3082,8 @@ mod proxy_serialization_tests {
Commands::Query { query: "SELECT ?s WHERE { ?s ?p ?o }".into() },
Commands::Lint { input: "x.ttl".into() },
Commands::Reason { profile: "rdfs".into(), certificate: None, rules: None },
- Commands::Fol { out: "/tmp/fol".into(), format: "tptp".into(), clif_dialect: "iso".into(), clif_comments: "standalone".into(), goals: None, goals_skip_columns: 0 },
+ Commands::Fol { out: "/tmp/fol".into(), format: "tptp".into(), smt_domain: None, clif_dialect: "iso".into(), clif_comments: "standalone".into(), goals: None, goals_skip_columns: 0 },
+ Commands::FolModel { out: "/tmp/folmodel".into(), solver: "z3".into(), max_domain: 16, timeout_secs: 30, unbounded_probe: true, goals: None, goals_skip_columns: 0, checker: None },
Commands::Shacl { shapes: "s.ttl".into() },
Commands::Status,
Commands::Pull { url: "http://example.org".into(), sparql: false, query: None },
diff --git a/src/server.rs b/src/server.rs
index 8a7d22f7..05845229 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -1922,12 +1922,13 @@ impl OpenOntologiesServer {
.unwrap_or_else(Self::err_json)
}
- #[tool(name = "onto_fol_export", description = "Export the loaded ontology as first-order logic, so it can be handed to the automated-theorem-proving ecosystem. Two syntaxes over ONE translation: `tptp` (FOF, what E, Vampire and every other first-order prover read) and `clif` (ISO/IEC 24707 Common Logic Interchange Format, restricted to the first-order-equivalent fragment: no sequence markers, fixed arity, no quantification into a predicate position). The translation is the one a MACHINE-CHECKED ADEQUACY THEOREM is about: `OwlLean.adequacy` in the sibling owl-lean project, axioms propext + Classical.choice + Quot.sound, no sorry, no Mathlib. That theorem is why the emitted file means what it says. THE CORRESPONDENCE BETWEEN THIS EMITTER AND THAT LEAN IS PINNED BY TESTS AND IS NOT ITSELF PROVED. The output includes the background axioms (the two domains are disjoint, the object domain is non-empty) and the individual typing axioms `thing(a)`, whose ABSENCE REFUTES ADEQUACY OUTRIGHT (OwlLean.Refutations.adequacy_needs_ind_axioms). Constructs outside the fragment are NOT dropped silently: `exports_a_weaker_axiom_set` and `constructs_not_exported` name every one with its count and the reason, and `reduced_to_fragment` names every construct rewritten before translation. Pass `goals_file` (a TSV of triples, e.g. the `derivations.tsv` from onto_reason with certificate_dir, with goals_skip_columns=1) to also write one problem per conjecture. A PROVER'S VERDICT ON THESE FILES IS AN ORACLE OPINION AND NEVER A CERTIFICATE: checking a superposition refutation needs a verified first-order calculus with unification, which does not exist in core Lean. Use tools/fol_differential.py, which reports disagreement between this engine and an ATP and does not adjudicate it.")]
+ #[tool(name = "onto_fol_export", description = "Export the loaded ontology as first-order logic, so it can be handed to the automated-theorem-proving ecosystem. FOUR syntaxes over ONE translation: `tptp` (FOF, what E, Vampire and every other first-order prover read), `clif` (ISO/IEC 24707 Common Logic Interchange Format, restricted to the first-order-equivalent fragment: no sequence markers, fixed arity, no quantification into a predicate position), `smtlib` (SMT-LIB 2, what Z3 reads) and `ladr` (what Mace4 reads, with every symbol MANGLED and the table written beside it as symbols.tsv, because LADR reads a name beginning with u, v, w, x, y or z as a VARIABLE and has no quoting construct that survives an IRI). The last two are read by MODEL FINDERS, so they assert the NEGATED goal rather than declaring a conjecture: a countermodel to `G |= phi` is a model of `G + {not phi}`. With `smtlib`, omit `smt_domain` for the UNBOUNDED encoding, where `unsat` really is unsatisfiability, or set it to k for an enumeration carrier of exactly k elements, where a `sat` comes with a structure `oo-folmodel` can CHECK and an `unsat` establishes only that no model of size k exists. Every run also writes `problem.tsv`, the checker's own format, with its digest, so a solver result can be handed to `oo-folmodel` without going back through the engine; use onto_fol_model to do all of that in one call. The translation is the one a MACHINE-CHECKED ADEQUACY THEOREM is about: `OwlLean.adequacy` in the sibling owl-lean project, axioms propext + Classical.choice + Quot.sound, no sorry, no Mathlib. That theorem is why the emitted file means what it says. THE CORRESPONDENCE BETWEEN THIS EMITTER AND THAT LEAN IS PINNED BY TESTS AND IS NOT ITSELF PROVED. The output includes the background axioms (the two domains are disjoint, the object domain is non-empty) and the individual typing axioms `thing(a)`, whose ABSENCE REFUTES ADEQUACY OUTRIGHT (OwlLean.Refutations.adequacy_needs_ind_axioms). Constructs outside the fragment are NOT dropped silently: `exports_a_weaker_axiom_set` and `constructs_not_exported` name every one with its count and the reason, and `reduced_to_fragment` names every construct rewritten before translation. Pass `goals_file` (a TSV of triples, e.g. the `derivations.tsv` from onto_reason with certificate_dir, with goals_skip_columns=1) to also write one problem per conjecture. A PROVER'S VERDICT ON THESE FILES IS AN ORACLE OPINION AND NEVER A CERTIFICATE: checking a superposition refutation needs a verified first-order calculus with unification, which does not exist in core Lean. Use tools/fol_differential.py, which reports disagreement between this engine and an ATP and does not adjudicate it.")]
async fn onto_fol_export(&self, Parameters(input): Parameters<OntoFolExportInput>) -> String {
let syntax = match crate::tptp::Syntax::parse(
input.format.as_deref().unwrap_or("tptp"),
input.clif_dialect.as_deref(),
input.clif_comments.as_deref(),
+ input.smt_domain,
) {
Ok(s) => s,
Err(e) => return Self::err_json(e),
@@ -1942,6 +1943,30 @@ impl OpenOntologiesServer {
.unwrap_or_else(Self::err_json)
}
+ #[tool(name = "onto_fol_model", description = "Find a finite model of the loaded ontology and CHECK IT, so the answer names what it rests on. This is the SAT/SMT family, and it is deliberately not symmetric. A REFUTATION cannot be replayed in core Lean, so a solver saying `unsat` is an ORACLE OPINION for ever (decision 0005). A MODEL is a finite object, checking a formula against it is decidable, and `lean/Fol/` holds a checker whose soundness is machine-checked: `Fol.satisfiable_of_check` turns an accepted structure into satisfiability of exactly the formulas it was checked against, and `Fol.not_entails_of_check` turns a checked model of the NEGATED goal into a machine-checked NON-ENTAILMENT, which is the one sentence no theorem prover can produce. The pipeline exports SMT-LIB 2 (for Z3) or LADR (for Mace4) and `problem.tsv` from ONE representation, climbs a cardinality ladder, reads the structure back, and runs `oo-folmodel`. FIVE FIELDS THAT ARE NEVER COLLAPSED: `solver_verdict` (sat/unsat/unknown, what the oracle said), `encoding` (unbounded or finite(k), what it was asked), `checker_exit` (null means the checker never ran), `verdict`, and `owl_reading`. The verdict is one of FIVE WORDS: `model_checked` is the ONLY certified one and requires checker_exit 0; `satisfiable_oracle` is sat with nothing checked; `no_model_up_to_size_k` is an exhausted BOUNDED search and IS NOT UNSATISFIABILITY (a theory with no model of size k can have one of size k+1, and SHIQ has no finite model property at all, so a satisfiable ontology can have only infinite models and will never receive a certificate here); `unsatisfiable_oracle` may be produced ONLY by a run with no cardinality constraint of any kind and can never be more than an opinion; `unknown_oracle` is a timeout or a give-up. A solver answering sat whose model the checker REJECTS is a STOP-THE-LINE disagreement reported in its own block with severity STOP_THE_LINE, never `rejected` as though the ontology were at fault and never `model_checked`. The OWL-level reading carries its own word, `not_entailed_under_unproved_translation`, because it rides on OwlLean.adequacy in a sibling project AND on the Rust-to-Lean correspondence that is PINNED BY TESTS AND NOT PROVED. Needs z3 or mace4 on PATH and `oo-folmodel` built (cd lean && lake build); the absence of either is reported loudly in `skipped` and never worked around. See docs/decisions/0006.")]
+ async fn onto_fol_model(&self, Parameters(input): Parameters<OntoFolModelInput>) -> String {
+ use crate::fol_solve::{SolveOptions, Solver, solve_export};
+ let solver = match Solver::parse(input.solver.as_deref().unwrap_or("z3")) {
+ Ok(s) => s,
+ Err(e) => return Self::err_json(e),
+ };
+ let opts = SolveOptions {
+ solver,
+ max_domain: input.max_domain.unwrap_or(16),
+ timeout_secs: input.timeout_secs.unwrap_or(30),
+ unbounded_probe: input.unbounded_probe.unwrap_or(true),
+ checker: None,
+ };
+ solve_export(
+ &self.graph,
+ std::path::Path::new(&input.out_dir),
+ &opts,
+ input.goals_file.as_deref().map(std::path::Path::new),
+ input.goals_skip_columns.unwrap_or(0),
+ )
+ .unwrap_or_else(Self::err_json)
+ }
+
#[tool(name = "onto_dl_explain", description = "Explain why a class is unsatisfiable using DL tableaux reasoning. Returns an explanation trace showing the logical contradictions that make the class impossible to instantiate.")]
async fn onto_dl_explain(&self, Parameters(input): Parameters<OntoDlExplainInput>) -> String {
use crate::tableaux::DlReasoner;
diff --git a/src/tptp.rs b/src/tptp.rs
index 8a16c1a7..4149f770 100644
--- a/src/tptp.rs
+++ b/src/tptp.rs
@@ -781,6 +781,68 @@ pub struct FolProblem {
pub individuals: BTreeSet<String>,
}
+/// One line of the model-finding problem: a role, a diagnostic label, and the
+/// formula the solver is asked about and the checker then checks.
+#[derive(Clone, Debug)]
+pub struct CheckerEntry {
+ /// `axiom` or `goal_negated`, and nothing else.
+ pub role: &'static str,
+ /// The emitter's own label. DIAGNOSTIC ONLY: not digested, and no theorem
+ /// looks at it.
+ pub label: String,
+ pub form: Form,
+}
+
+/// The symbols a problem uses, by arity, in a fixed order.
+///
+/// Three separate sets rather than one, because `Fol.FinModel` has three
+/// separate fields: `c:X` as a unary predicate and `op:X` as a binary one
+/// could not collide even without the [`sym`] prefixes.
+#[derive(Clone, Debug, Default)]
+pub struct Vocabulary {
+ pub unary: BTreeSet<String>,
+ pub binary: BTreeSet<String>,
+ pub consts: BTreeSet<String>,
+}
+
+impl Vocabulary {
+ pub fn len(&self) -> usize {
+ self.unary.len() + self.binary.len() + self.consts.len()
+ }
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+}
+
+fn collect(f: &Form, v: &mut Vocabulary) {
+ fn t(term: &Term, v: &mut Vocabulary) {
+ if let Term::Const(a) = term {
+ v.consts.insert(sym::constant(a));
+ }
+ }
+ match f {
+ Form::App1(p, x) => {
+ v.unary.insert(sym::p1(p));
+ t(x, v);
+ }
+ Form::App2(p, x, y) => {
+ v.binary.insert(sym::p2(p));
+ t(x, v);
+ t(y, v);
+ }
+ Form::Eq(x, y) => {
+ t(x, v);
+ t(y, v);
+ }
+ Form::Tru | Form::Fls => {}
+ Form::Neg(g) | Form::All(_, g) | Form::Ex(_, g) => collect(g, v),
+ Form::And(g, h) | Form::Or(g, h) | Form::Imp(g, h) => {
+ collect(g, v);
+ collect(h, v);
+ }
+ }
+}
+
impl FolProblem {
/// Build the problem for an ontology and an optional goal.
///
@@ -837,10 +899,89 @@ impl FolProblem {
out
}
+ /// Every formula as the MODEL-FINDING half of the pipeline sees it.
+ ///
+ /// This is [`FolProblem::formulas`] with one difference, and the
+ /// difference is the whole point of the model direction: a conjecture
+ /// becomes a `goal_negated` line carrying `¬φ`. A countermodel to
+ /// `Γ ⊨ φ` is a model of `Γ ∪ {¬φ}`, so the negation happens ONCE, here,
+ /// and neither the solver nor `oo-folmodel` negates anything again.
+ ///
+ /// The SMT-LIB file, the LADR file and `problem.tsv` are all folds over
+ /// this one list. That is the mechanical reason the solver cannot be asked
+ /// a different question from the one the checker then checks, and it is
+ /// the same argument [`FolProblem::formulas`] makes for TPTP and CLIF.
+ pub fn checker_entries(&self) -> Vec<CheckerEntry> {
+ let mut out = Vec::new();
+ for (label, role, f) in self.formulas() {
+ match role {
+ "conjecture" => out.push(CheckerEntry {
+ role: "goal_negated",
+ label,
+ form: Form::neg(f.clone()),
+ }),
+ _ => out.push(CheckerEntry { role: "axiom", label, form: f.clone() }),
+ }
+ }
+ out
+ }
+
+ /// The symbols the problem actually uses, by arity.
+ ///
+ /// Collected from [`FolProblem::checker_entries`] and therefore including
+ /// the negated goal's, because a model file that did not interpret a
+ /// symbol occurring only in the goal would fail `Fol.covers`.
+ pub fn vocabulary(&self) -> Vocabulary {
+ let mut v = Vocabulary::default();
+ for e in self.checker_entries() {
+ collect(&e.form, &mut v);
+ }
+ v
+ }
+
+ /// `problem.tsv` for `oo-folmodel`, and its digest.
+ pub fn to_problem_tsv(&self) -> Result<(String, String), UnwritableSymbol> {
+ let entries = self.checker_entries();
+ let mut file = String::new();
+ let mut canonical: Vec<String> = Vec::with_capacity(entries.len());
+ for e in &entries {
+ let shown = checkfmt::show_form(&e.form)?;
+ let _ = writeln!(file, "{}\t{}\t{}", e.role, e.label, shown);
+ canonical.push(format!("{}\t{}", e.role, shown));
+ }
+ let digest = checkfmt::hex16(checkfmt::fnv1a64(&canonical.join("\n")));
+ Ok((file, digest))
+ }
+
+ /// SMT-LIB 2, with the goal already negated.
+ pub fn to_smtlib(&self, enc: smtlib::SmtEncoding) -> Result<String, UnwritableSymbol> {
+ let v = self.vocabulary();
+ let mut s = header(";", self.conjecture.is_some(), SMTLIB_STYLE);
+ let _ = writeln!(s, "\n(set-logic {})", smtlib::logic(enc));
+ let _ = writeln!(s, "(set-option :produce-models true)");
+ let _ = writeln!(s, "{}", smtlib::sort_decl(enc));
+ for p in &v.unary {
+ let _ = writeln!(s, "(declare-fun {} (U) Bool)", smtlib::symbol(p)?);
+ }
+ for p in &v.binary {
+ let _ = writeln!(s, "(declare-fun {} (U U) Bool)", smtlib::symbol(p)?);
+ }
+ for c in &v.consts {
+ let _ = writeln!(s, "(declare-fun {} () U)", smtlib::symbol(c)?);
+ }
+ for e in self.checker_entries() {
+ let _ = writeln!(s, "; {} ({})", e.label, e.role);
+ let _ = writeln!(s, "(assert {})", smtlib::form(&e.form)?);
+ }
+ let _ = writeln!(s, "(check-sat)");
+ let _ = writeln!(s, "(get-model)");
+ Ok(s)
+ }
+
/// TPTP FOF.
pub fn to_tptp(&self) -> String {
let mut s = String::new();
- s.push_str(&header("%", self.conjecture.is_some()));
+ s.push_str(&header("%", self.conjecture.is_some(), TPTP_STYLE));
for (name, role, f) in self.formulas() {
let _ = writeln!(s, "fof({name}, {role}, {}).", fof::form(f));
}
@@ -871,7 +1012,7 @@ impl FolProblem {
let _ = writeln!(
s,
" {}",
- clif::standalone_comment(dialect, &header_text(self.conjecture.is_some(), true))
+ clif::standalone_comment(dialect, &header_text(self.conjecture.is_some(), CLIF_STYLE))
);
for (label, role, f) in self.formulas() {
match comments {
@@ -897,11 +1038,11 @@ impl FolProblem {
}
}
-/// The header both serialisers carry, with each line prefixed by the syntax's
-/// comment marker. It is not decoration: a file that leaves its own limits to
-/// a README gets read without one.
-fn header(comment: &str, has_goal: bool) -> String {
- header_text(has_goal, comment == "//")
+/// The header every serialiser carries, with each line prefixed by the
+/// syntax's comment marker. It is not decoration: a file that leaves its own
+/// limits to a README gets read without one.
+fn header(comment: &str, has_goal: bool, style: HeaderStyle) -> String {
+ header_text(has_goal, style)
.lines()
.map(|l| {
if l.is_empty() {
@@ -913,8 +1054,52 @@ fn header(comment: &str, has_goal: bool) -> String {
.collect()
}
+/// The syntax-specific paragraphs of the header.
+///
+/// `extra` is what the syntax itself needs a reader to know. `goal` replaces
+/// the paragraph about the conjecture, and it has to be swappable rather than
+/// shared: TPTP and CLIF carry the goal as a CONJECTURE and a prover negates
+/// it internally, while SMT-LIB and LADR carry the NEGATION as an assertion
+/// and a `sat` answer is the non-entailment. A reader told the wrong one of
+/// those two reads the file backwards.
+#[derive(Clone, Copy)]
+struct HeaderStyle {
+ extra: &'static [&'static str],
+ goal: &'static [&'static str],
+}
+
+/// What a refutation-style consumer is told: its verdict is an oracle opinion.
+const ORACLE_GOAL: &[&str] = &[
+ "",
+ "A prover's verdict on this file is an ORACLE OPINION, not a certificate.",
+ "Checking a superposition refutation needs a verified first-order calculus",
+ "with unification, which does not exist in core Lean. Disagreement between",
+ "a prover and this engine is a bug in one of the two and nothing here says",
+ "which.",
+];
+
+/// What a model-finding consumer is told: the goal is already negated, and its
+/// SATISFIABILITY answer is the one this repository can certify.
+const MODEL_GOAL: &[&str] = &[
+ "",
+ "THE GOAL IS ALREADY NEGATED IN THIS FILE. A countermodel to `G |= phi` is a",
+ "model of `G + {not phi}`, so the negation is asserted here and nothing",
+ "downstream negates anything again. A `sat` answer therefore says the",
+ "conjecture is NOT entailed, and an `unsat` answer says nothing this",
+ "repository will print the word `unsatisfiable` for unless the encoding was",
+ "unbounded.",
+ "",
+ "A MODEL THIS FILE YIELDS CAN BE CERTIFIED; A REFUTATION CANNOT. Hand the",
+ "solver's structure to `oo-folmodel` (lean/Fol/) and a machine-checked",
+ "theorem, Fol.satisfiable_of_check, turns an accepted structure into",
+ "satisfiability of exactly these formulas. Nothing in this repository",
+ "certifies the other direction. See docs/decisions/0006.",
+];
+
+const TPTP_STYLE: HeaderStyle = HeaderStyle { extra: &[], goal: ORACLE_GOAL };
+
/// The header, unprefixed, so CLIF can carry it inside a `cl:comment` string.
-fn header_text(has_goal: bool, clif: bool) -> String {
+fn header_text(has_goal: bool, style: HeaderStyle) -> String {
let mut lines: Vec<&str> = vec![
"Generated by open-ontologies `fol` export.",
"",
@@ -928,8 +1113,16 @@ fn header_text(has_goal: bool, clif: bool) -> String {
"owl-lean's `background`; the `ind_typing_*` axioms are its `indAxioms`, and",
"omitting them refutes adequacy outright (OwlLean.Refutations).",
];
- if clif {
- lines.extend([
+ lines.extend(style.extra.iter().copied());
+ if has_goal {
+ lines.extend(style.goal.iter().copied());
+ }
+ lines.join("\n")
+}
+
+/// The CLIF paragraphs of the header.
+const CLIF_NOTES: &[&str] = &{
+ [
"",
"CLIF RESTRICTION. Common Logic is not plain first-order logic. This text",
"uses only the first-order-equivalent fragment: no sequence markers, fixed",
@@ -963,20 +1156,58 @@ fn header_text(has_goal: bool, clif: bool) -> String {
"the Macleod toolchain's shipped lexer use `cl-text` and `cl-comment`",
"instead, and will not read the colon spelling. Re-export with the other",
"dialect rather than hand-editing.",
- ]);
- }
- if has_goal {
- lines.extend([
- "",
- "A prover's verdict on this file is an ORACLE OPINION, not a certificate.",
- "Checking a superposition refutation needs a verified first-order calculus",
- "with unification, which does not exist in core Lean. Disagreement between",
- "a prover and this engine is a bug in one of the two and nothing here says",
- "which.",
- ]);
- }
- lines.join("\n")
-}
+ ]
+};
+
+const CLIF_STYLE: HeaderStyle = HeaderStyle { extra: CLIF_NOTES, goal: ORACLE_GOAL };
+
+/// The SMT-LIB paragraphs.
+const SMTLIB_NOTES: &[&str] = &[
+ "",
+ "SMT-LIB 2. One sort `U`, unary and binary predicates over it, and nullary",
+ "constants. There are no function symbols of positive arity, no theories and",
+ "no sorts beyond `U`, because `OwlLean.FOL` has none: `FSig` is exactly P1,",
+ "P2 and Const.",
+ "",
+ "`U` is declared one of two ways and the difference decides what an answer",
+ "means. `declare-sort` leaves the cardinality open, so `unsat` is real",
+ "unsatisfiability. An enumeration datatype `(e0 … e(k-1))` fixes it at k, so",
+ "`unsat` establishes only that NO MODEL OF SIZE k EXISTS, which is not",
+ "unsatisfiability: `(forall ((x U)) (exists ((y U)) (and (r x y) (not (= x",
+ "y))))) ` is unsat at k=1 and sat at k=2.",
+ "",
+ "`e0 …`, `U` and `X0 …` cannot collide with a translated symbol: every one",
+ "of those is `thing`, `lit`, or carries a colon prefix.",
+];
+
+const SMTLIB_STYLE: HeaderStyle = HeaderStyle { extra: SMTLIB_NOTES, goal: MODEL_GOAL };
+
+/// The LADR paragraphs.
+const LADR_NOTES: &[&str] = &[
+ "",
+ "LADR, for Mace4. EVERY SYMBOL IN THIS FILE IS MANGLED and the table is",
+ "written beside it as `symbols.tsv`: p0… are the unary predicates, r0… the",
+ "binary ones, c0… the constants, and x0… are bound variables. Do not read an",
+ "IRI back out of this file by hand.",
+ "",
+ "The mangling is not cosmetic. LADR reads a name whose first letter is in",
+ "{u,v,w,x,y,z} as a VARIABLE, so an IRI beginning with one of those would",
+ "silently become universally quantified and Mace4 would search a different",
+ "problem and report `exhausted` with no error. Measured on LADR 2009-11A:",
+ "the input `p0(w0). -p0(k0).` is echoed in Mace4's own CLAUSES FOR SEARCH",
+ "block as `p0(x).` and `-p0(k0).`. LADR also has no quoting construct that",
+ "survives the colon and the slash an IRI contains.",
+ "",
+ "Mace4 CLAUSIFIES AND SKOLEMISES, so the model it prints interprets names",
+ "this file never declared (f1, and fresh c… it chose itself). Those are",
+ "dropped on the way back in, which is taking the reduct of its structure,",
+ "and the driver reports the dropped names rather than passing over them.",
+ "",
+ "Mace4's minimum domain size is 2: `-n 1` is a fatal error, measured. A",
+ "one-element model can be found by the SMT-LIB route and not by this one.",
+];
+
+const LADR_STYLE: HeaderStyle = HeaderStyle { extra: LADR_NOTES, goal: MODEL_GOAL };
fn axiom_label(a: &OwlAxiom) -> &'static str {
match a {
@@ -1005,6 +1236,99 @@ fn axiom_label(a: &OwlAxiom) -> &'static str {
}
}
+// ── The namer: one module, four consumers ───────────────────────────────────
+
+/// The seven prefixed images of the Lean's symbol arms. ONE namer.
+///
+/// `lean/Fol/Syntax.lean` monomorphises `OwlLean.FOL.Form` at `Sym := String`,
+/// which flattens `OwlP1`'s four arms, `OwlP2`'s two and `FSig.Const` into one
+/// string space. That flattening is sound only if the map is INJECTIVE, and
+/// the injectivity is supplied by these prefixes: `thing` and `lit` carry no
+/// colon and every other arm carries its own, so the seven images are pairwise
+/// disjoint whatever the IRIs are.
+///
+/// ```text
+/// OwlP1.Thing -> thing OwlP2.Op r -> op:r
+/// OwlP1.Lit -> lit OwlP2.Dp d -> dp:d
+/// OwlP1.Cls a -> c:a FSig.Const a -> i:a
+/// OwlP1.Dt d -> d:d
+/// ```
+///
+/// Four consumers: [`fof`] wraps these in single-quoted TPTP atoms, [`clif`]
+/// in double-quoted CLIF enclosed names, [`smtlib`] in `|…|` quoted symbols,
+/// and [`checkfmt`] writes them bare into the file the Lean checker reads. The
+/// fifth, [`ladr`], does not use them at all: LADR has no quoting construct
+/// that survives a colon or a slash, so it mangles instead and keeps a table.
+///
+/// Writing a second namer by stripping the quotes off the TPTP output is the
+/// obvious shortcut and is exactly what this module exists to prevent. If the
+/// prefixes ever drift apart between two syntaxes, a class IRI and a datatype
+/// IRI with the same spelling become one predicate in one of them.
+pub mod sym {
+ use super::{P1, P2};
+
+ /// The image of a unary predicate symbol.
+ pub fn p1(p: &P1) -> String {
+ match p {
+ P1::Cls(a) => format!("c:{a}"),
+ P1::Dt(d) => format!("d:{d}"),
+ P1::Thing => "thing".to_string(),
+ P1::Lit => "lit".to_string(),
+ }
+ }
+
+ /// The image of a binary predicate symbol.
+ pub fn p2(p: &P2) -> String {
+ match p {
+ P2::Op(r) => format!("op:{r}"),
+ P2::Dp(d) => format!("dp:{d}"),
+ }
+ }
+
+ /// The image of an individual name.
+ pub fn constant(a: &str) -> String {
+ format!("i:{a}")
+ }
+
+ /// The characters a symbol may not contain, and why.
+ ///
+ /// `bare()` strips the angle brackets before an IRI reaches `Term::Const`
+ /// or `P1::Cls`, so the symbols here are RAW IRIs out of the graph and
+ /// this refusal is live rather than belt and braces. In the checker format
+ /// a symbol containing a space re-parses as a DIFFERENT formula (the token
+ /// stream splits on spaces) and one containing a tab re-parses as a
+ /// different set of fields. The 13 September 2026 audit of this repository
+ /// found exactly that truncation class silently disabling SHACL
+ /// constraints, so the writer returns an error rather than emitting one.
+ pub fn unwritable_char(s: &str) -> Option<char> {
+ s.chars().find(|c| matches!(c, ' ' | '\t' | '\r' | '\n'))
+ }
+}
+
+/// A symbol that cannot be written into a target syntax, named with the reason.
+///
+/// Returned rather than escaped or dropped: a dropped symbol is a different
+/// theory and an escaped one is a different symbol.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct UnwritableSymbol {
+ pub symbol: String,
+ pub character: char,
+ pub syntax: &'static str,
+ pub why: &'static str,
+}
+
+impl std::fmt::Display for UnwritableSymbol {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "the symbol {:?} contains {:?}, which cannot be written in {}: {}",
+ self.symbol, self.character, self.syntax, self.why
+ )
+ }
+}
+
+impl std::error::Error for UnwritableSymbol {}
+
// ── Serialiser 1: TPTP FOF ──────────────────────────────────────────────────
/// TPTP FOF rendering of [`Form`]. A fold over the formula and nothing else.
@@ -1012,21 +1336,28 @@ fn axiom_label(a: &OwlAxiom) -> &'static str {
/// Named `fof` rather than `tptp` so it sits beside [`clif`] as one of two
/// syntaxes, which is what it is.
pub mod fof {
- use super::{Form, P1, P2, Term};
+ use super::{Form, P1, P2, Term, sym};
/// Symbols are single-quoted TPTP atoms carrying a kind prefix.
///
- /// The prefix is not cosmetic. `OwlP1` and `OwlP2` are disjoint sums in
- /// the Lean, so a class and an object property that happen to share an IRI
- /// are two unrelated symbols, and a rendering that collapsed them would
- /// emit a different theory. Every prefix contains a colon, which is not
- /// legal in an unquoted TPTP lower-word, so no prefixed symbol can ever
- /// collide with the bare atoms `thing` and `lit`.
- fn quoted(prefix: &str, iri: &str) -> String {
- let mut s = String::with_capacity(iri.len() + prefix.len() + 4);
+ /// The prefix comes from [`super::sym`] and is not cosmetic: `OwlP1` and
+ /// `OwlP2` are disjoint sums in the Lean, so a class and an object
+ /// property that happen to share an IRI are two unrelated symbols, and a
+ /// rendering that collapsed them would emit a different theory. Every
+ /// prefix contains a colon, which is not legal in an unquoted TPTP
+ /// lower-word, so no prefixed symbol can ever collide with the bare atoms
+ /// `thing` and `lit`.
+ ///
+ /// Only `\` and `'` are escaped, and the prefixes contain neither, so
+ /// quoting the prefixed image is byte for byte what quoting the prefix and
+ /// the escaped IRI separately used to produce.
+ fn quoted(image: &str) -> String {
+ if image == "thing" || image == "lit" {
+ return image.to_string();
+ }
+ let mut s = String::with_capacity(image.len() + 4);
s.push('\'');
- s.push_str(prefix);
- for ch in iri.chars() {
+ for ch in image.chars() {
if ch == '\\' || ch == '\'' {
s.push('\\');
}
@@ -1037,25 +1368,17 @@ pub mod fof {
}
fn p1(p: &P1) -> String {
- match p {
- P1::Cls(a) => quoted("c:", a),
- P1::Dt(d) => quoted("d:", d),
- P1::Thing => "thing".to_string(),
- P1::Lit => "lit".to_string(),
- }
+ quoted(&sym::p1(p))
}
fn p2(p: &P2) -> String {
- match p {
- P2::Op(r) => quoted("op:", r),
- P2::Dp(d) => quoted("dp:", d),
- }
+ quoted(&sym::p2(p))
}
fn term(t: &Term) -> String {
match t {
Term::Var(n) => format!("X{n}"),
- Term::Const(a) => quoted("i:", a),
+ Term::Const(a) => quoted(&sym::constant(a)),
}
}
@@ -1228,7 +1551,7 @@ impl ClifDialect {
/// `tests/fol_translation_correspondence_test.rs` is the check that it still
/// does.
pub mod clif {
- use super::{ClifDialect, Form, P1, P2, Term};
+ use super::{ClifDialect, Form, P1, P2, Term, sym};
/// Names are written as CLIF **enclosed names**, delimited by DOUBLE
/// QUOTES, with `"` and `\` escaped.
@@ -1240,13 +1563,13 @@ pub mod clif {
/// containing two pipes and would not protect a slash or a colon. The
/// bar convention belongs to Common Lisp and to KIF, not to CLIF.
///
- /// The kind prefixes are the TPTP serialiser's, for the same reason:
- /// `OwlP1` and `OwlP2` are disjoint sums in the Lean.
- fn enclosed(prefix: &str, iri: &str) -> String {
- let mut s = String::with_capacity(iri.len() + prefix.len() + 4);
+ /// The kind prefixes come from [`super::sym`], the same module the TPTP
+ /// and SMT-LIB serialisers read, for the same reason: `OwlP1` and `OwlP2`
+ /// are disjoint sums in the Lean.
+ fn enclosed(image: &str) -> String {
+ let mut s = String::with_capacity(image.len() + 4);
s.push('"');
- s.push_str(prefix);
- for ch in iri.chars() {
+ for ch in image.chars() {
if ch == '\\' || ch == '"' {
s.push('\\');
}
@@ -1338,24 +1661,20 @@ pub mod clif {
fn p1(p: &P1) -> String {
match p {
- P1::Cls(a) => enclosed("c:", a),
- P1::Dt(d) => enclosed("d:", d),
P1::Thing => "thing".to_string(),
P1::Lit => "lit".to_string(),
+ other => enclosed(&sym::p1(other)),
}
}
fn p2(p: &P2) -> String {
- match p {
- P2::Op(r) => enclosed("op:", r),
- P2::Dp(d) => enclosed("dp:", d),
- }
+ enclosed(&sym::p2(p))
}
fn term(t: &Term) -> String {
match t {
Term::Var(n) => format!("X{n}"),
- Term::Const(a) => enclosed("i:", a),
+ Term::Const(a) => enclosed(&sym::constant(a)),
}
}
@@ -1381,6 +1700,486 @@ pub mod clif {
}
}
+// ── Serialiser 3: SMT-LIB 2 ─────────────────────────────────────────────────
+
+/// SMT-LIB 2 rendering of [`Form`]. The third printer over the same [`Form`],
+/// and no more OWL-specific than the other two.
+///
+/// # Why this one exists and the other two were not enough
+///
+/// TPTP and CLIF are refutation formats: the consumer takes a conjecture,
+/// negates it and searches for a contradiction, and by decision 0005 what it
+/// hands back is an oracle opinion. SMT-LIB is read by solvers that also build
+/// MODELS, and a model is a finite object this repository can check. The file
+/// this module writes is therefore asked a different question, and it asserts
+/// the NEGATED goal rather than declaring a conjecture, because a countermodel
+/// to `Γ ⊨ φ` is a model of `Γ ∪ {¬φ}`.
+///
+/// # The two encodings, and why the difference is load-bearing
+///
+/// [`SmtEncoding::Unbounded`] declares `U` with `declare-sort`, so a model may
+/// be of any cardinality and `unsat` really means unsatisfiable. Nothing
+/// constrains the solver to return a finite structure, so a `sat` here is an
+/// oracle opinion.
+///
+/// [`SmtEncoding::Finite`] declares `U` as an enumeration datatype with
+/// exactly `k` nullary constructors `e0 … e(k-1)`. Now `sat` comes with a
+/// structure over a known finite carrier, which is exactly what `oo-folmodel`
+/// can check, and `unsat` establishes only that no model of size `k` exists.
+/// Reporting the second as unsatisfiability is the ten-minute mistake
+/// decision 0006 item 4 exists to stop: `∀x∃y (r(x,y) ∧ x≠y)` is `unsat` at
+/// carrier 1 and `sat` at carrier 2.
+///
+/// `e0 … e(k-1)`, `U` and `X0 …` cannot collide with a problem symbol, because
+/// every problem symbol is `thing`, `lit`, or carries one of the five colon
+/// prefixes from [`sym`], and none of those spellings contains a colon.
+pub mod smtlib {
+ use super::{Form, P1, P2, Term, UnwritableSymbol, sym};
+
+ /// Which sort declaration the file carries.
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub enum SmtEncoding {
+ /// `(declare-sort U 0)`. Any cardinality, so `unsat` is real
+ /// unsatisfiability and `sat` carries no size bound.
+ Unbounded,
+ /// `(declare-datatypes ((U 0)) (((e0) … )))`, exactly `k` elements.
+ /// `unsat` establishes only `no_model_up_to_size_k`.
+ Finite(u32),
+ }
+
+ impl SmtEncoding {
+ /// The word a report prints for this encoding. Decision 0006 makes the
+ /// verdict depend on it mechanically, so it is a value and not prose.
+ pub fn name(self) -> String {
+ match self {
+ SmtEncoding::Unbounded => "unbounded".to_string(),
+ SmtEncoding::Finite(k) => format!("finite({k})"),
+ }
+ }
+ pub fn bound(self) -> Option<u32> {
+ match self {
+ SmtEncoding::Unbounded => None,
+ SmtEncoding::Finite(k) => Some(k),
+ }
+ }
+ }
+
+ /// An SMT-LIB 2 symbol.
+ ///
+ /// `thing` and `lit` are legal simple symbols and are written bare.
+ /// Everything else carries a colon, which SMT-LIB's simple-symbol
+ /// character set excludes (a leading colon is a keyword), so it goes in
+ /// `|…|`. A quoted symbol may contain anything except `|` and `\`
+ /// (SMT-LIB 2.6 §3.1), and there is no escape for either, so a symbol
+ /// containing one is REFUSED rather than mangled into a different symbol.
+ pub fn symbol(image: &str) -> Result<String, UnwritableSymbol> {
+ if image == "thing" || image == "lit" {
+ return Ok(image.to_string());
+ }
+ if let Some(c) = image.chars().find(|c| matches!(c, '|' | '\\')) {
+ return Err(UnwritableSymbol {
+ symbol: image.to_string(),
+ character: c,
+ syntax: "SMT-LIB 2",
+ why: "a quoted symbol admits every character except | and \\, and SMT-LIB \
+ defines no escape for either (2.6 section 3.1)",
+ });
+ }
+ Ok(format!("|{image}|"))
+ }
+
+ fn p1(p: &P1) -> Result<String, UnwritableSymbol> {
+ symbol(&sym::p1(p))
+ }
+ fn p2(p: &P2) -> Result<String, UnwritableSymbol> {
+ symbol(&sym::p2(p))
+ }
+ fn term(t: &Term) -> Result<String, UnwritableSymbol> {
+ match t {
+ Term::Var(n) => Ok(format!("X{n}")),
+ Term::Const(a) => symbol(&sym::constant(a)),
+ }
+ }
+
+ /// Render a formula. Fully parenthesised, because S-expressions are.
+ pub fn form(f: &Form) -> Result<String, UnwritableSymbol> {
+ Ok(match f {
+ Form::App1(p, t) => format!("({} {})", p1(p)?, term(t)?),
+ Form::App2(p, t, u) => format!("({} {} {})", p2(p)?, term(t)?, term(u)?),
+ Form::Eq(t, u) => format!("(= {} {})", term(t)?, term(u)?),
+ Form::Tru => "true".to_string(),
+ Form::Fls => "false".to_string(),
+ Form::Neg(g) => format!("(not {})", form(g)?),
+ Form::And(g, h) => format!("(and {} {})", form(g)?, form(h)?),
+ Form::Or(g, h) => format!("(or {} {})", form(g)?, form(h)?),
+ Form::Imp(g, h) => format!("(=> {} {})", form(g)?, form(h)?),
+ Form::All(n, g) => format!("(forall ((X{n} U)) {})", form(g)?),
+ Form::Ex(n, g) => format!("(exists ((X{n} U)) {})", form(g)?),
+ })
+ }
+
+ /// The sort declaration for an encoding.
+ pub fn sort_decl(enc: SmtEncoding) -> String {
+ match enc {
+ SmtEncoding::Unbounded => "(declare-sort U 0)".to_string(),
+ SmtEncoding::Finite(k) => {
+ let ctors: Vec<String> = (0..k).map(|i| format!("(e{i})")).collect();
+ format!("(declare-datatypes ((U 0)) (({})))", ctors.join(" "))
+ }
+ }
+ }
+
+ /// The logic name. `UF` is quantified uninterpreted functions; `UFDT` adds
+ /// the datatypes the finite encoding declares the carrier with.
+ pub fn logic(enc: SmtEncoding) -> &'static str {
+ match enc {
+ SmtEncoding::Unbounded => "UF",
+ SmtEncoding::Finite(_) => "UFDT",
+ }
+ }
+}
+
+// ── Serialiser 4: LADR, for Mace4 ───────────────────────────────────────────
+
+/// LADR rendering of [`Form`], for Mace4, the finite model finder that ships
+/// with Prover9.
+///
+/// # Why a dead toolchain is here at all
+///
+/// Prover9 is unmaintained and its refutations are uncheckable, so by
+/// decision 0005 it is an oracle like any other prover. Mace4 ships in the
+/// same distribution, is a FINITE MODEL FINDER, and prints exactly the kind of
+/// object `lean/Fol/` can certify. The dead toolchain has a live half.
+///
+/// # The trap this module is built around
+///
+/// LADR's default convention is that a name whose first letter is in
+/// `{u,v,w,x,y,z}` is a VARIABLE. A mangler that turned an IRI into `w0` would
+/// turn a constant into a universally quantified variable, and Mace4 would
+/// silently search a different and usually unsatisfiable problem. Measured on
+/// this machine with LADR 2009-11A: the input
+///
+/// ```text
+/// p0(w0).
+/// -p0(k0).
+/// ```
+///
+/// is echoed by Mace4 in its own `CLAUSES FOR SEARCH` block as `p0(x).` and
+/// `-p0(k0).`, the search is then exhausted, and the run reports no model at
+/// all. Nothing errors. So this module never writes an IRI: it MANGLES every
+/// symbol into `p0…` (unary), `r0…` (binary) and `c0…` (constants), renders
+/// bound variables as `x0, x1, …` so that they still ARE variables under the
+/// same convention, and keeps a [`SymbolTable`] to read the answer back.
+/// [`check_not_variable`] is run over every emitted name, so the gate exists
+/// as a function that can be made to fire rather than as a comment.
+///
+/// Mangling also solves the quoting problem, which LADR has no answer to: an
+/// IRI contains `:` and `/` and LADR has no quoting construct that survives
+/// either.
+pub mod ladr {
+ use super::{FolProblem, Form, Term, sym};
+ use std::collections::BTreeMap;
+ use std::fmt::Write as _;
+
+ /// A name LADR would read as a variable, so the writer refused it.
+ #[derive(Debug, Clone, PartialEq, Eq)]
+ pub struct LadrVariableName {
+ pub name: String,
+ pub why: &'static str,
+ }
+
+ impl std::fmt::Display for LadrVariableName {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "LADR would read {:?} as a VARIABLE, not a symbol: {}", self.name, self.why)
+ }
+ }
+ impl std::error::Error for LadrVariableName {}
+
+ /// True when LADR's default convention reads this name as a variable.
+ pub fn is_variable_name(name: &str) -> bool {
+ matches!(
+ name.chars().next(),
+ Some('u' | 'v' | 'w' | 'x' | 'y' | 'z' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z')
+ )
+ }
+
+ /// The gate. Every name this module emits in a symbol position goes
+ /// through it, so that the trap above cannot be reintroduced by an edit to
+ /// the mangler.
+ pub fn check_not_variable(name: &str) -> Result<(), LadrVariableName> {
+ if is_variable_name(name) {
+ return Err(LadrVariableName {
+ name: name.to_string(),
+ why: "LADR treats a name beginning with u, v, w, x, y or z as universally \
+ quantified. A constant mangled to such a name makes Mace4 search a \
+ different problem and report `exhausted` with no error",
+ });
+ }
+ Ok(())
+ }
+
+ /// Which slot of `Fol.FinModel` a symbol belongs in. Three separate
+ /// fields there, so this is a kind and not a number.
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub enum SymKind {
+ Unary,
+ Binary,
+ Constant,
+ }
+
+ impl SymKind {
+ pub fn name(self) -> &'static str {
+ match self {
+ SymKind::Unary => "unary",
+ SymKind::Binary => "binary",
+ SymKind::Constant => "constant",
+ }
+ }
+ }
+
+ /// The mangling, and its inverse.
+ ///
+ /// Built in sorted order so that a given problem always produces the same
+ /// file, which is what makes a Mace4 run reproducible and a diff readable.
+ ///
+ /// The inverse carries the KIND as well as the image, and that is not
+ /// bookkeeping. A model finder that returned `relation(p0(_,_))` for a
+ /// symbol the problem uses as a unary predicate would otherwise be filed
+ /// as a perfectly good binary interpretation, and the unary slot would
+ /// then be reported as uninterpreted: a confusing message for a defect
+ /// that is really a disagreement about the signature. The table is the
+ /// authority on the arity, because the table is what wrote the file.
+ #[derive(Debug, Clone, Default)]
+ pub struct SymbolTable {
+ /// `c:Person` → `p3`
+ pub unary: BTreeMap<String, String>,
+ /// `op:worksFor` → `r0`
+ pub binary: BTreeMap<String, String>,
+ /// `i:a` → `c0`
+ pub consts: BTreeMap<String, String>,
+ inverse: BTreeMap<String, (String, SymKind)>,
+ }
+
+ impl SymbolTable {
+ /// Mangle every symbol the problem uses.
+ pub fn build(problem: &FolProblem) -> Result<SymbolTable, LadrVariableName> {
+ let v = problem.vocabulary();
+ let mut t = SymbolTable::default();
+ for (i, s) in v.unary.iter().enumerate() {
+ let m = format!("p{i}");
+ check_not_variable(&m)?;
+ t.unary.insert(s.clone(), m.clone());
+ t.inverse.insert(m, (s.clone(), SymKind::Unary));
+ }
+ for (i, s) in v.binary.iter().enumerate() {
+ let m = format!("r{i}");
+ check_not_variable(&m)?;
+ t.binary.insert(s.clone(), m.clone());
+ t.inverse.insert(m, (s.clone(), SymKind::Binary));
+ }
+ for (i, s) in v.consts.iter().enumerate() {
+ let m = format!("c{i}");
+ check_not_variable(&m)?;
+ t.consts.insert(s.clone(), m.clone());
+ t.inverse.insert(m, (s.clone(), SymKind::Constant));
+ }
+ Ok(t)
+ }
+
+ /// The symbol a mangled name stands for, or `None` when LADR invented
+ /// it. Mace4 clausifies and Skolemises, so its models interpret names
+ /// this table never issued; those are the reduct and are dropped.
+ pub fn demangle(&self, mangled: &str) -> Option<&str> {
+ self.inverse.get(mangled).map(|(s, _)| s.as_str())
+ }
+
+ /// The image AND the slot it belongs in. The arity a model file claims
+ /// is checked against this rather than believed.
+ pub fn demangle_kind(&self, mangled: &str) -> Option<(&str, SymKind)> {
+ self.inverse.get(mangled).map(|(s, k)| (s.as_str(), *k))
+ }
+
+ pub fn len(&self) -> usize {
+ self.unary.len() + self.binary.len() + self.consts.len()
+ }
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+ }
+
+ fn term(t: &Term, tab: &SymbolTable) -> Result<String, LadrVariableName> {
+ Ok(match t {
+ // A bound variable is deliberately `x…`, because under the same
+ // convention that makes `c0` a symbol, `x0` is a variable.
+ Term::Var(n) => format!("x{n}"),
+ Term::Const(a) => lookup(&tab.consts, &sym::constant(a))?,
+ })
+ }
+
+ fn lookup(m: &BTreeMap<String, String>, image: &str) -> Result<String, LadrVariableName> {
+ match m.get(image) {
+ Some(s) => Ok(s.clone()),
+ // Unreachable through `problem`, which builds the table from the
+ // same vocabulary it then renders. Reported rather than panicking
+ // so that a future caller that builds the two separately gets a
+ // sentence instead of a crash.
+ None => Err(LadrVariableName {
+ name: image.to_string(),
+ why: "the symbol is not in the table this file was mangled with, so the \
+ LADR name for it does not exist",
+ }),
+ }
+ }
+
+ /// Render a formula. Fully parenthesised: LADR's precedence table is not
+ /// worth relying on and a misparse here is silent.
+ pub fn form(f: &Form, tab: &SymbolTable) -> Result<String, LadrVariableName> {
+ Ok(match f {
+ Form::App1(p, t) => format!("{}({})", lookup(&tab.unary, &sym::p1(p))?, term(t, tab)?),
+ Form::App2(p, t, u) => format!(
+ "{}({},{})",
+ lookup(&tab.binary, &sym::p2(p))?,
+ term(t, tab)?,
+ term(u, tab)?
+ ),
+ Form::Eq(t, u) => format!("({} = {})", term(t, tab)?, term(u, tab)?),
+ // LADR's own truth constants. Measured: Mace4 2009-11A accepts a
+ // bare `$T.` as an assumption.
+ Form::Tru => "$T".to_string(),
+ Form::Fls => "$F".to_string(),
+ Form::Neg(g) => format!("-({})", form(g, tab)?),
+ Form::And(g, h) => format!("({} & {})", form(g, tab)?, form(h, tab)?),
+ Form::Or(g, h) => format!("({} | {})", form(g, tab)?, form(h, tab)?),
+ Form::Imp(g, h) => format!("({} -> {})", form(g, tab)?, form(h, tab)?),
+ Form::All(n, g) => format!("(all x{n} ({}))", form(g, tab)?),
+ Form::Ex(n, g) => format!("(exists x{n} ({}))", form(g, tab)?),
+ })
+ }
+
+ /// The whole input file, goal already negated.
+ ///
+ /// `max_seconds` is written into the file rather than passed on the
+ /// command line so that a saved file reproduces the run it came from.
+ pub fn problem(
+ p: &FolProblem,
+ tab: &SymbolTable,
+ max_seconds: u32,
+ ) -> Result<String, LadrVariableName> {
+ let mut s = super::header("%", p.conjecture.is_some(), super::LADR_STYLE);
+ let _ = writeln!(s, "\nassign(max_seconds, {max_seconds}).\n");
+ let _ = writeln!(s, "formulas(assumptions).");
+ for e in p.checker_entries() {
+ let _ = writeln!(s, " % {} ({})", e.label, e.role);
+ let _ = writeln!(s, " {}.", form(&e.form, tab)?);
+ }
+ let _ = writeln!(s, "end_of_list.");
+ Ok(s)
+ }
+
+ /// The mangling, as data, so a report can say what a Mace4 name meant.
+ pub fn table_tsv(tab: &SymbolTable) -> String {
+ let mut s = String::new();
+ for (image, m) in &tab.unary {
+ let _ = writeln!(s, "unary\t{m}\t{image}");
+ }
+ for (image, m) in &tab.binary {
+ let _ = writeln!(s, "binary\t{m}\t{image}");
+ }
+ for (image, m) in &tab.consts {
+ let _ = writeln!(s, "constant\t{m}\t{image}");
+ }
+ s
+ }
+}
+
+// ── Serialiser 5: the checker format ────────────────────────────────────────
+
+/// `problem.tsv`, the file `oo-folmodel` reads, and the digest that binds a
+/// model file to it.
+///
+/// The grammar and the hash are specified in `lean/Fol/Syntax.lean` and
+/// `lean/Fol/Parse.lean`. This module is the second implementation of both,
+/// and the pinned digest `4403d8aaa0c422f7` for the worked example is what
+/// holds the two together: `lean/Fol/Parse.lean` has a `#guard` on it and
+/// `tests/fol_checker_format_test.rs` has an assertion on it, so a change to
+/// either printer or to the hash fails a build on one side and a test on the
+/// other.
+///
+/// FNV-1a IDENTIFIES, IT DOES NOT COMMIT. It is not a cryptographic hash. It
+/// exists so that two implementations can be compared, not so that one can be
+/// defended against someone who controls the file. Decision 0003 item 5, in
+/// the same words, for the same reason.
+pub mod checkfmt {
+ use super::{Form, P1, P2, Term, UnwritableSymbol, sym};
+
+ /// Refuse a symbol the token stream cannot survive. See
+ /// [`sym::unwritable_char`] for why this is live rather than defensive.
+ fn clean(image: String) -> Result<String, UnwritableSymbol> {
+ match sym::unwritable_char(&image) {
+ None => Ok(image),
+ Some(c) => Err(UnwritableSymbol {
+ symbol: image,
+ character: c,
+ syntax: "the oo-folmodel checker format",
+ why: "the formula is a space-separated token stream and the file is \
+ tab-separated, so a symbol containing either re-parses as a DIFFERENT \
+ formula or as a different set of fields",
+ }),
+ }
+ }
+
+ fn p1(p: &P1) -> Result<String, UnwritableSymbol> {
+ clean(sym::p1(p))
+ }
+ fn p2(p: &P2) -> Result<String, UnwritableSymbol> {
+ clean(sym::p2(p))
+ }
+
+ /// `Fol.Parse.showTerm`.
+ pub fn show_term(t: &Term) -> Result<String, UnwritableSymbol> {
+ Ok(match t {
+ Term::Var(n) => format!("var {n}"),
+ Term::Const(a) => format!("const {}", clean(sym::constant(a))?),
+ })
+ }
+
+ /// `Fol.Parse.showForm`. Prefix, no parentheses, single spaces.
+ pub fn show_form(f: &Form) -> Result<String, UnwritableSymbol> {
+ Ok(match f {
+ Form::App1(p, t) => format!("app1 {} {}", p1(p)?, show_term(t)?),
+ Form::App2(p, t, u) => {
+ format!("app2 {} {} {}", p2(p)?, show_term(t)?, show_term(u)?)
+ }
+ Form::Eq(t, u) => format!("eq {} {}", show_term(t)?, show_term(u)?),
+ Form::Tru => "tru".to_string(),
+ Form::Fls => "fls".to_string(),
+ Form::Neg(g) => format!("neg {}", show_form(g)?),
+ Form::And(g, h) => format!("and {} {}", show_form(g)?, show_form(h)?),
+ Form::Or(g, h) => format!("or {} {}", show_form(g)?, show_form(h)?),
+ Form::Imp(g, h) => format!("imp {} {}", show_form(g)?, show_form(h)?),
+ Form::All(n, g) => format!("all {n} {}", show_form(g)?),
+ Form::Ex(n, g) => format!("ex {n} {}", show_form(g)?),
+ })
+ }
+
+ /// FNV-1a, 64 bit, over the UTF-8 bytes. Offset basis
+ /// 14695981039346656037, prime 1099511628211, wrapping at 2^64.
+ ///
+ /// Written out rather than taken from a library because the Lean side
+ /// writes it out too: `String.hash` there is an opaque extern with no
+ /// specification a second implementation could target.
+ pub fn fnv1a64(s: &str) -> u64 {
+ s.as_bytes().iter().fold(14695981039346656037u64, |h, b| {
+ (h ^ (*b as u64)).wrapping_mul(1099511628211)
+ })
+ }
+
+ /// Sixteen lowercase hex digits, most significant first, zero padded.
+ pub fn hex16(x: u64) -> String {
+ format!("{x:016x}")
+ }
+}
+
// ── Reading an ontology out of the graph ────────────────────────────────────
const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
@@ -2078,6 +2877,43 @@ impl Reader {
/// Constructs that have no place in the fragment at all. Counted by
/// scanning for the predicate or the class, the same shape as
/// `DlReasoner::unmodelled_constructs`.
+ /// How many assertions a punned subject carries.
+ ///
+ /// Mirrors the assertion loop's own conditions exactly, so the count is
+ /// the number of axioms that WOULD have been exported had the subject not
+ /// been declared an entity of another kind. Declarations, subsumptions,
+ /// domains, ranges and annotations are not assertions and are not counted:
+ /// those ARE exported for a punned subject, which is why the omission was
+ /// invisible.
+ fn count_punned_assertions(&mut self, s: &str) -> u64 {
+ let mut n = 0u64;
+ let pairs = self.by_subject.get(s).cloned().unwrap_or_default();
+ for (p, o) in &pairs {
+ let bp = bare(p).to_string();
+ if bp == RDF_TYPE {
+ let bo = bare(o).to_string();
+ if !bo.starts_with(OWL)
+ && !bo.starts_with("http://www.w3.org/2000/01/rdf-schema#")
+ && self.concept(o).is_some()
+ {
+ n += 1;
+ }
+ continue;
+ }
+ if bp.starts_with(OWL)
+ || bp.starts_with("http://www.w3.org/2000/01/rdf-schema#")
+ || bp.starts_with("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
+ || is_literal(o)
+ {
+ continue;
+ }
+ if self.is_object_property(&bp) {
+ n += 1;
+ }
+ }
+ n
+ }
+
fn count_out_of_fragment(&mut self) {
const OUT: [(&str, &str, &str); 6] = [
(
@@ -2387,13 +3223,34 @@ impl Reader {
// Assertions. An individual is a subject that is neither a class, a
// property, nor a piece of OWL syntax.
+ //
+ // A subject that IS one of those and still carries an assertion is
+ // PUNNED: the same IRI used as a class in one triple and as an
+ // individual in another. OWL 2 DL allows that, `OwlLean/Syntax.lean`
+ // does not — `Sig` gives each entity kind its own type — so the
+ // assertion is outside the fragment and is not exported.
+ //
+ // It used to be dropped SILENTLY, and that was found by running the
+ // model-certificate pipeline over the shipped case studies: five of
+ // the nine derivations the OWL-RL reasoner claims on
+ // `case-studies/blast-furnace-ironmaking/` came back with a
+ // machine-checked countermodel, because `bf:Hanging`, a class, also
+ // carries `bf:hasSeverity bf:HighSeverity` and the domain axiom on
+ // that property is what the reasoner used. The export was genuinely
+ // weaker than the graph and the report said `exports_a_weaker_axiom_set:
+ // false`, which is the laundering shape this project exists to catch,
+ // in its own output. Counted here so the report is true; the reading
+ // itself is unchanged.
+ let mut punned = 0u64;
for s in &subjects {
let bare_s = bare(s).to_string();
- if self.classes.contains(&bare_s)
+ let is_entity = self.classes.contains(&bare_s)
|| self.object_properties.contains(&bare_s)
- || self.data_properties.contains(&bare_s)
- || bare_s.starts_with(OWL)
- {
+ || self.data_properties.contains(&bare_s);
+ if is_entity || bare_s.starts_with(OWL) {
+ if is_entity {
+ punned += self.count_punned_assertions(s);
+ }
continue;
}
let pairs = self.by_subject.get(s).cloned().unwrap_or_default();
@@ -2429,6 +3286,16 @@ impl Reader {
}
}
+ if punned > 0 {
+ self.dropped.insert(
+ "assertion on a punned entity".to_string(),
+ (
+ punned,
+ "the subject is declared a class or a property AND carries an assertion, so the same IRI is used as two entity kinds. OWL 2 DL permits the punning; OwlLean/Syntax.lean does not, because `Sig` gives each entity kind its own type and `Sig.Ind` is disjoint from `Sig.Cls`. The assertion is therefore outside the fragment and the exported theory is WEAKER than the graph. An RDFS or OWL-RL reasoner will still derive consequences from it, so a conjecture that rests on one is genuinely not entailed by this export and is not evidence of a defect in either side"
+ .to_string(),
+ ),
+ );
+ }
self.count_out_of_fragment();
// Data property assertions have no constructor in the fragment: the
// Axiom type has oPropAssert and no dPropAssert.
@@ -2734,15 +3601,23 @@ pub enum Syntax {
/// syntax for the same first-order content, and the one ISO/IEC 21838-2
/// publishes BFO in.
Clif(ClifDialect, ClifComments),
+ /// SMT-LIB 2, the format the SAT/SMT family reads. The goal is asserted
+ /// NEGATED, because this is the syntax a MODEL comes back out of and a
+ /// model is the thing this repository can certify.
+ Smtlib(smtlib::SmtEncoding),
+ /// LADR, for Mace4. Mangled symbols, the table beside the file.
+ Ladr,
}
impl Syntax {
/// `dialect` and `comments` are consulted only for CLIF and default to
- /// `iso` and `standalone`.
+ /// `iso` and `standalone`; `domain` only for SMT-LIB, where `None` is the
+ /// unbounded encoding.
pub fn parse(
s: &str,
dialect: Option<&str>,
comments: Option<&str>,
+ domain: Option<u32>,
) -> anyhow::Result<Syntax> {
match s.to_ascii_lowercase().as_str() {
"tptp" | "fof" | "tptp-fof" => Ok(Syntax::Tptp),
@@ -2750,8 +3625,18 @@ impl Syntax {
ClifDialect::parse(dialect.unwrap_or("iso"))?,
ClifComments::parse(comments.unwrap_or("standalone"))?,
)),
+ "smtlib" | "smt" | "smt2" | "smt-lib" => Ok(Syntax::Smtlib(match domain {
+ None => smtlib::SmtEncoding::Unbounded,
+ Some(0) => anyhow::bail!(
+ "--smt-domain 0 asks for a model with an empty carrier; a first-order \
+ structure cannot have one, and `Fol.FinModel` is defined only at n+1"
+ ),
+ Some(k) => smtlib::SmtEncoding::Finite(k),
+ })),
+ "ladr" | "mace4" | "prover9" => Ok(Syntax::Ladr),
other => anyhow::bail!(
- "unknown first-order syntax {other:?}; expected `tptp` or `clif`"
+ "unknown first-order syntax {other:?}; expected `tptp`, `clif`, `smtlib` or \
+ `ladr`"
),
}
}
@@ -2759,31 +3644,48 @@ impl Syntax {
match self {
Syntax::Tptp => "p",
Syntax::Clif(..) => "clif",
+ Syntax::Smtlib(_) => "smt2",
+ Syntax::Ladr => "in",
}
}
pub fn name(self) -> &'static str {
match self {
Syntax::Tptp => "tptp",
Syntax::Clif(..) => "clif",
+ Syntax::Smtlib(_) => "smtlib",
+ Syntax::Ladr => "ladr",
}
}
pub fn dialect(self) -> Option<ClifDialect> {
match self {
- Syntax::Tptp => None,
Syntax::Clif(d, _) => Some(d),
+ _ => None,
}
}
pub fn comments(self) -> Option<ClifComments> {
match self {
- Syntax::Tptp => None,
Syntax::Clif(_, c) => Some(c),
+ _ => None,
}
}
- fn render(self, problem: &FolProblem, name: &str) -> String {
+ pub fn encoding(self) -> Option<smtlib::SmtEncoding> {
match self {
+ Syntax::Smtlib(e) => Some(e),
+ _ => None,
+ }
+ }
+ /// Render. Fallible from the SMT-LIB and LADR arms on: both refuse a
+ /// symbol they cannot write rather than mangling it into a different one.
+ fn render(self, problem: &FolProblem, name: &str) -> anyhow::Result<String> {
+ Ok(match self {
Syntax::Tptp => problem.to_tptp(),
Syntax::Clif(d, c) => problem.to_clif(d, c, name),
- }
+ Syntax::Smtlib(e) => problem.to_smtlib(e)?,
+ Syntax::Ladr => {
+ let tab = ladr::SymbolTable::build(problem)?;
+ ladr::problem(problem, &tab, 30)?
+ }
+ })
}
}
@@ -2823,7 +3725,21 @@ pub fn export(
let problem = FolProblem::build(&read.axioms, None)?;
std::fs::create_dir_all(dir)?;
let main = dir.join(format!("ontology.{}", syntax.extension()));
- std::fs::write(&main, syntax.render(&problem, &ontology_iri))?;
+ std::fs::write(&main, syntax.render(&problem, &ontology_iri)?)?;
+ // LADR mangles every symbol, so the file is unreadable without the table.
+ // Written beside it rather than into it, because Mace4 echoes its input
+ // and a comment per symbol would bury the clause block a reader needs.
+ if syntax == Syntax::Ladr {
+ std::fs::write(
+ dir.join("symbols.tsv"),
+ ladr::table_tsv(&ladr::SymbolTable::build(&problem)?),
+ )?;
+ }
+ // The checker's own format, for every syntax, so that a run of any solver
+ // over any of these files can be handed to `oo-folmodel` without going
+ // back through the engine. The digest is what binds the two.
+ let (problem_tsv, problem_digest) = problem.to_problem_tsv()?;
+ std::fs::write(dir.join("problem.tsv"), &problem_tsv)?;
let mut goal_files = Vec::new();
let mut not_asked: Vec<GoalNotAsked> = Vec::new();
@@ -2866,10 +3782,21 @@ pub fn export(
let name = format!("goal_{i:05}.{}", syntax.extension());
std::fs::write(
goals_dir.join(&name),
- syntax.render(&gp, &format!("{ontology_iri}#goal-{i:05}")),
+ syntax.render(&gp, &format!("{ontology_iri}#goal-{i:05}"))?,
)?;
+ let (gtsv, gdigest) = gp.to_problem_tsv()?;
+ let gtsv_name = format!("goal_{i:05}.problem.tsv");
+ std::fs::write(goals_dir.join(&gtsv_name), gtsv)?;
+ if syntax == Syntax::Ladr {
+ std::fs::write(
+ goals_dir.join(format!("goal_{i:05}.symbols.tsv")),
+ ladr::table_tsv(&ladr::SymbolTable::build(&gp)?),
+ )?;
+ }
manifest.push(serde_json::json!({
"file": name,
+ "checker_problem_file": gtsv_name,
+ "checker_problem_digest": gdigest,
"triple": [s, p, o],
"axiom_form": axiom_label(&ax),
}));
@@ -2889,8 +3816,13 @@ pub fn export(
"clif_dialect": syntax.dialect().map(|d| d.name()),
"clif_comments": syntax.comments().map(|c| c.name()),
"clif_text_name": syntax.dialect().map(|_| ontology_iri.clone()),
+ "smt_encoding": syntax.encoding().map(|e| e.name()),
"dir": dir.display().to_string(),
"ontology_file": main.display().to_string(),
+ "checker_problem_file": dir.join("problem.tsv").display().to_string(),
+ "checker_problem_digest": problem_digest,
+ "ladr_symbol_table": (syntax == Syntax::Ladr)
+ .then(|| dir.join("symbols.tsv").display().to_string()),
"initial_triples": initial_triples,
"axioms_exported": problem.axioms.len(),
"background_axioms": problem.background.len(),
diff --git a/tests/fixtures/folmodel/model.tsv b/tests/fixtures/folmodel/model.tsv
new file mode 100644
index 00000000..fc73b3bd
--- /dev/null
+++ b/tests/fixtures/folmodel/model.tsv
@@ -0,0 +1,17 @@
+domain 2
+problem 4403d8aaa0c422f7
+source z3
+decl1 thing
+decl1 lit
+decl1 c:Person
+decl1 c:Company
+decl2 op:worksFor
+declc i:a
+p1 thing 11
+p1 lit 00
+p1 c:Person 10
+p1 c:Company 01
+p2 op:worksFor 0 01
+p2 op:worksFor 1 00
+const i:a 0
+cardinality_search 1,2
diff --git a/tests/fixtures/folmodel/model_bad_arity.tsv b/tests/fixtures/folmodel/model_bad_arity.tsv
new file mode 100644
index 00000000..20fb26ba
--- /dev/null
+++ b/tests/fixtures/folmodel/model_bad_arity.tsv
@@ -0,0 +1,17 @@
+domain 2
+problem 4403d8aaa0c422f7
+source z3
+decl1 thing
+decl1 lit
+decl1 c:Person
+decl1 c:Company
+decl1 op:worksFor
+declc i:a
+p1 thing 11
+p1 lit 00
+p1 c:Person 10
+p1 c:Company 01
+p2 op:worksFor 0 01
+p2 op:worksFor 1 00
+const i:a 0
+cardinality_search 1,2
diff --git a/tests/fixtures/folmodel/model_empty_domain.tsv b/tests/fixtures/folmodel/model_empty_domain.tsv
new file mode 100644
index 00000000..7ded088d
--- /dev/null
+++ b/tests/fixtures/folmodel/model_empty_domain.tsv
@@ -0,0 +1,17 @@
+domain 0
+problem 4403d8aaa0c422f7
+source z3
+decl1 thing
+decl1 lit
+decl1 c:Person
+decl1 c:Company
+decl2 op:worksFor
+declc i:a
+p1 thing 11
+p1 lit 00
+p1 c:Person 10
+p1 c:Company 01
+p2 op:worksFor 0 01
+p2 op:worksFor 1 00
+const i:a 0
+cardinality_search 1,2
diff --git a/tests/fixtures/folmodel/model_index_out_of_range.tsv b/tests/fixtures/folmodel/model_index_out_of_range.tsv
new file mode 100644
index 00000000..a354cecc
--- /dev/null
+++ b/tests/fixtures/folmodel/model_index_out_of_range.tsv
@@ -0,0 +1,17 @@
+domain 2
+problem 4403d8aaa0c422f7
+source z3
+decl1 thing
+decl1 lit
+decl1 c:Person
+decl1 c:Company
+decl2 op:worksFor
+declc i:a
+p1 thing 11
+p1 lit 00
+p1 c:Person 10
+p1 c:Company 01
+p2 op:worksFor 0 01
+p2 op:worksFor 1 00
+const i:a 5
+cardinality_search 1,2
diff --git a/tests/fixtures/folmodel/model_missing_row.tsv b/tests/fixtures/folmodel/model_missing_row.tsv
new file mode 100644
index 00000000..eca168be
--- /dev/null
+++ b/tests/fixtures/folmodel/model_missing_row.tsv
@@ -0,0 +1,16 @@
+domain 2
+problem 4403d8aaa0c422f7
+source z3
+decl1 thing
+decl1 lit
+decl1 c:Person
+decl1 c:Company
+decl2 op:worksFor
+declc i:a
+p1 thing 11
+p1 lit 00
+p1 c:Person 10
+p1 c:Company 01
+p2 op:worksFor 0 01
+const i:a 0
+cardinality_search 1,2
diff --git a/tests/fixtures/folmodel/model_no_edge.tsv b/tests/fixtures/folmodel/model_no_edge.tsv
new file mode 100644
index 00000000..8d8d4600
--- /dev/null
+++ b/tests/fixtures/folmodel/model_no_edge.tsv
@@ -0,0 +1,17 @@
+domain 2
+problem 4403d8aaa0c422f7
+source z3
+decl1 thing
+decl1 lit
+decl1 c:Person
+decl1 c:Company
+decl2 op:worksFor
+declc i:a
+p1 thing 11
+p1 lit 00
+p1 c:Person 10
+p1 c:Company 01
+p2 op:worksFor 0 00
+p2 op:worksFor 1 00
+const i:a 0
+cardinality_search 1,2
diff --git a/tests/fixtures/folmodel/model_undeclared.tsv b/tests/fixtures/folmodel/model_undeclared.tsv
new file mode 100644
index 00000000..668a3e9a
--- /dev/null
+++ b/tests/fixtures/folmodel/model_undeclared.tsv
@@ -0,0 +1,15 @@
+domain 2
+problem 4403d8aaa0c422f7
+source z3
+decl1 thing
+decl1 lit
+decl1 c:Person
+decl2 op:worksFor
+declc i:a
+p1 thing 11
+p1 lit 00
+p1 c:Person 10
+p2 op:worksFor 0 01
+p2 op:worksFor 1 00
+const i:a 0
+cardinality_search 1,2
diff --git a/tests/fixtures/folmodel/model_wrong_digest.tsv b/tests/fixtures/folmodel/model_wrong_digest.tsv
new file mode 100644
index 00000000..d93a665c
--- /dev/null
+++ b/tests/fixtures/folmodel/model_wrong_digest.tsv
@@ -0,0 +1,17 @@
+domain 2
+problem 0000000000000000
+source z3
+decl1 thing
+decl1 lit
+decl1 c:Person
+decl1 c:Company
+decl2 op:worksFor
+declc i:a
+p1 thing 11
+p1 lit 00
+p1 c:Person 10
+p1 c:Company 01
+p2 op:worksFor 0 01
+p2 op:worksFor 1 00
+const i:a 0
+cardinality_search 1,2
diff --git a/tests/fixtures/folmodel/problem.tsv b/tests/fixtures/folmodel/problem.tsv
new file mode 100644
index 00000000..f98b1cf6
--- /dev/null
+++ b/tests/fixtures/folmodel/problem.tsv
@@ -0,0 +1,5 @@
+axiom background_1 all 0 neg and app1 thing var 0 app1 lit var 0
+axiom ind_typing_1 app1 thing const i:a
+axiom owl_1_subClassOf all 0 imp app1 c:Person var 0 ex 1 and app2 op:worksFor var 0 var 1 app1 c:Company var 1
+axiom owl_2_classAssertion app1 c:Person const i:a
+goal_negated goal_classAssertion neg app1 c:Company const i:a
diff --git a/tests/fixtures/folmodel/problem_empty.tsv b/tests/fixtures/folmodel/problem_empty.tsv
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/fixtures/folmodel/problem_other.tsv b/tests/fixtures/folmodel/problem_other.tsv
new file mode 100644
index 00000000..a63ca7ec
--- /dev/null
+++ b/tests/fixtures/folmodel/problem_other.tsv
@@ -0,0 +1,2 @@
+axiom other_1 app1 c:Person const i:a
+axiom other_2 neg app1 c:Person const i:a
diff --git a/tests/fol_checker_format_test.rs b/tests/fol_checker_format_test.rs
new file mode 100644
index 00000000..d4bc998f
--- /dev/null
+++ b/tests/fol_checker_format_test.rs
@@ -0,0 +1,577 @@
+//! The three new printers: SMT-LIB 2, LADR, and the checker's own format.
+//!
+//! One representation, five printers. `src/tptp.rs` computes `Form` once and
+//! `fof`, `clif`, `smtlib`, `ladr` and `checkfmt` are folds over it. These
+//! tests pin what each of the three new ones writes.
+//!
+//! **Every expected string here was computed by hand.** A golden file captured
+//! from the emitter agrees with the emitter by construction and proves
+//! nothing, which is the same argument `fol_translation_correspondence_test.rs`
+//! makes at the top of itself and the reason that file exists at all. The
+//! SMT-LIB cases are unrolled from SMT-LIB 2.6's own grammar; the LADR cases
+//! from the Prover9/Mace4 manual's connective table; the checker-format cases
+//! from `Fol.Parse.showForm` in `lean/Fol/Parse.lean`, constructor by
+//! constructor.
+//!
+//! The digest is the sharpest of them. `4403d8aaa0c422f7` is pinned THREE
+//! times: by a `#guard` in `lean/Fol/Parse.lean`, by the fixture
+//! `tests/fixtures/folmodel/problem.tsv`, and here. Two independent
+//! implementations of FNV-1a 64 and of one canonical printer have to agree on
+//! it, and a change to either fails on its own side.
+//!
+//! The groups:
+//!
+//! 1. The checker format: `showForm`, the digest, the whitespace refusal.
+//! 2. The goal is negated ONCE, on the way into the model-finding half.
+//! 3. SMT-LIB 2, hand-computed, both encodings, and the symbols it refuses.
+//! 4. LADR, hand-computed, the mangling, and the variable-letter gate.
+//! 5. One problem, three files: the printers cannot be asked different
+//! questions.
+
+use open_ontologies::tptp::{
+ Concept, FolProblem, Form, OwlAxiom, P1, P2, Syntax, Term, Translation, checkfmt, ladr,
+ smtlib, smtlib::SmtEncoding, sym,
+};
+
+fn v(n: u32) -> Term {
+ Term::Var(n)
+}
+fn k(a: &str) -> Term {
+ Term::Const(a.to_string())
+}
+fn cls(a: &str, t: Term) -> Form {
+ Form::App1(P1::Cls(a.to_string()), t)
+}
+fn thing(t: Term) -> Form {
+ Form::App1(P1::Thing, t)
+}
+fn lit(t: Term) -> Form {
+ Form::App1(P1::Lit, t)
+}
+fn op(r: &str, t: Term, u: Term) -> Form {
+ Form::App2(P2::Op(r.to_string()), t, u)
+}
+fn neg(f: Form) -> Form {
+ Form::Neg(Box::new(f))
+}
+fn and(f: Form, g: Form) -> Form {
+ Form::And(Box::new(f), Box::new(g))
+}
+fn imp(f: Form, g: Form) -> Form {
+ Form::Imp(Box::new(f), Box::new(g))
+}
+fn all(n: u32, f: Form) -> Form {
+ Form::All(n, Box::new(f))
+}
+fn ex(n: u32, f: Form) -> Form {
+ Form::Ex(n, Box::new(f))
+}
+
+/// The five formulas of the worked example in `lean/Fol/Syntax.lean`, built
+/// here from `Form` rather than read off the fixture, so that this side and
+/// the Lean side are two independent constructions of the same object.
+fn worked_example() -> Vec<(&'static str, Form)> {
+ vec![
+ ("axiom", all(0, neg(and(thing(v(0)), lit(v(0)))))),
+ ("axiom", thing(k("a"))),
+ (
+ "axiom",
+ all(
+ 0,
+ imp(
+ cls("Person", v(0)),
+ ex(1, and(op("worksFor", v(0), v(1)), cls("Company", v(1)))),
+ ),
+ ),
+ ),
+ ("axiom", cls("Person", k("a"))),
+ ("goal_negated", neg(cls("Company", k("a")))),
+ ]
+}
+
+fn fixture(name: &str) -> std::path::PathBuf {
+ std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("tests/fixtures/folmodel")
+ .join(name)
+}
+
+// ── 1. The checker format ───────────────────────────────────────────────────
+
+/// `Fol.Parse.showForm`, constructor by constructor.
+///
+/// Prefix, no parentheses, single spaces. The grammar is unambiguous because
+/// every constructor has fixed arity, which is why the file can afford to have
+/// no brackets at all and why a symbol containing a space would re-parse as a
+/// DIFFERENT formula rather than as a syntax error.
+#[test]
+fn show_form_is_the_leans_printer() {
+ let cases: Vec<(Form, &str)> = vec![
+ (Form::Tru, "tru"),
+ (Form::Fls, "fls"),
+ (thing(v(3)), "app1 thing var 3"),
+ (lit(k("a")), "app1 lit const i:a"),
+ (cls("Person", v(0)), "app1 c:Person var 0"),
+ (Form::App1(P1::Dt("int".into()), v(0)), "app1 d:int var 0"),
+ (op("worksFor", v(0), v(1)), "app2 op:worksFor var 0 var 1"),
+ (
+ Form::App2(P2::Dp("age".into()), k("a"), v(1)),
+ "app2 dp:age const i:a var 1",
+ ),
+ (Form::Eq(k("a"), k("b")), "eq const i:a const i:b"),
+ (neg(Form::Tru), "neg tru"),
+ (and(Form::Tru, Form::Fls), "and tru fls"),
+ (Form::Or(Box::new(Form::Tru), Box::new(Form::Fls)), "or tru fls"),
+ (imp(Form::Tru, Form::Fls), "imp tru fls"),
+ (all(7, Form::Tru), "all 7 tru"),
+ (ex(2, Form::Fls), "ex 2 fls"),
+ ];
+ for (f, want) in cases {
+ assert_eq!(checkfmt::show_form(&f).expect("writable"), want, "for {f:?}");
+ }
+}
+
+/// The formulas this side builds print exactly the fixture the Lean side
+/// reads. Byte for byte, in file order.
+#[test]
+fn the_worked_example_round_trips_against_the_lean_fixture() {
+ let text = std::fs::read_to_string(fixture("problem.tsv")).expect("fixture");
+ let want: Vec<(&str, &str)> = text
+ .lines()
+ .map(|l| {
+ let c: Vec<&str> = l.split('\t').collect();
+ (c[0], c[2])
+ })
+ .collect();
+ let got = worked_example();
+ assert_eq!(got.len(), want.len(), "the fixture has {} lines", want.len());
+ for ((role, f), (wrole, wform)) in got.iter().zip(&want) {
+ assert_eq!(role, wrole);
+ assert_eq!(&checkfmt::show_form(f).expect("writable"), wform);
+ }
+}
+
+/// FNV-1a 64 and the canonical string, against the value pinned in the Lean.
+///
+/// `lean/Fol/Parse.lean` carries `#guard problemDigest … = "4403d8aaa0c422f7"`,
+/// so a change to either printer or to either hash fails a build on one side
+/// and this test on the other. The constant is spelled out here rather than
+/// read from the fixture on purpose: reading it would make this test agree
+/// with whatever the fixture said.
+#[test]
+fn the_digest_agrees_with_the_lean() {
+ let canonical: Vec<String> = worked_example()
+ .iter()
+ .map(|(role, f)| format!("{role}\t{}", checkfmt::show_form(f).expect("writable")))
+ .collect();
+ let digest = checkfmt::hex16(checkfmt::fnv1a64(&canonical.join("\n")));
+ assert_eq!(digest, "4403d8aaa0c422f7");
+ // And the model fixture the Lean checker accepts carries that same digest,
+ // which is what binds the two files to each other.
+ let model = std::fs::read_to_string(fixture("model.tsv")).expect("fixture");
+ assert!(
+ model.contains("problem\t4403d8aaa0c422f7"),
+ "the shipped model.tsv must carry the digest this side computes"
+ );
+}
+
+/// The digest is over the parsed formulas and the ROLES, not over the bytes.
+///
+/// A file that relabelled `goal_negated` as `axiom` would otherwise digest the
+/// same, and a report reads the role to decide whether a non-entailment was
+/// even asked about.
+#[test]
+fn relabelling_the_goal_changes_the_digest() {
+ let canon = |entries: &[(&str, Form)]| {
+ let v: Vec<String> = entries
+ .iter()
+ .map(|(r, f)| format!("{r}\t{}", checkfmt::show_form(f).expect("writable")))
+ .collect();
+ checkfmt::hex16(checkfmt::fnv1a64(&v.join("\n")))
+ };
+ let real = worked_example();
+ let mut forged: Vec<(&str, Form)> =
+ real.iter().map(|(r, f)| (*r, f.clone())).collect();
+ forged.last_mut().expect("five entries").0 = "axiom";
+ assert_ne!(canon(&real), canon(&forged));
+}
+
+/// A symbol containing a space, a tab, a CR or a newline is REFUSED.
+///
+/// `bare()` strips the angle brackets before an IRI reaches `Term::Const`, so
+/// the symbols are raw IRIs out of the graph and this is live rather than
+/// defensive. Shown failing on each of the four characters: a gate that cannot
+/// fail is decoration.
+#[test]
+fn a_symbol_the_token_stream_cannot_survive_is_refused() {
+ for bad in [" ", "\t", "\r", "\n"] {
+ let f = cls(&format!("http://e/A{bad}B"), v(0));
+ let e = checkfmt::show_form(&f).expect_err("must refuse");
+ assert_eq!(e.character, bad.chars().next().expect("one char"));
+ assert_eq!(e.syntax, "the oo-folmodel checker format");
+ assert!(e.to_string().contains("DIFFERENT formula"), "{e}");
+ }
+ // And the same symbol in a constant position, which is the one `bare()`
+ // actually feeds raw IRIs into.
+ let f = thing(k("http://e/a b"));
+ assert!(checkfmt::show_form(&f).is_err());
+ // A symbol WITHOUT one of those is written, so the gate is not a constant.
+ assert_eq!(
+ checkfmt::show_form(&thing(k("http://e/a"))).expect("writable"),
+ "app1 thing const i:http://e/a"
+ );
+}
+
+// ── 2. The goal is negated once ─────────────────────────────────────────────
+
+/// `formulas()` carries the conjecture; `checker_entries()` carries its
+/// NEGATION under the role `goal_negated`, and nothing downstream negates
+/// again.
+///
+/// This is the one difference between the refutation half of the export and
+/// the model-finding half, and getting it wrong in either direction is silent:
+/// a file asserting the unnegated conjecture is satisfiable exactly when the
+/// ontology already says so, and a checker that negated a second time would
+/// certify a countermodel to the wrong sentence.
+#[test]
+fn the_goal_is_negated_exactly_once() {
+ let axioms = vec![OwlAxiom::ClassAssert(
+ Concept::Atom("http://e/Person".into()),
+ "http://e/a".into(),
+ )];
+ let goal = OwlAxiom::ClassAssert(Concept::Atom("http://e/Company".into()), "http://e/a".into());
+ let p = FolProblem::build(&axioms, Some(&goal)).expect("freshness holds");
+
+ let exported = p.formulas();
+ let (_, role, conj) = exported.last().expect("a conjecture row");
+ assert_eq!(*role, "conjecture");
+
+ let entries = p.checker_entries();
+ let last = entries.last().expect("a goal row");
+ assert_eq!(last.role, "goal_negated");
+ assert_eq!(last.form, Form::Neg(Box::new((*conj).clone())));
+ // Every other row keeps its formula and is an axiom.
+ assert!(entries[..entries.len() - 1].iter().all(|e| e.role == "axiom"));
+ assert_eq!(entries.len(), exported.len());
+ // A problem with no goal has no goal_negated row at all.
+ let bare = FolProblem::build(&axioms, None).expect("freshness holds");
+ assert!(bare.checker_entries().iter().all(|e| e.role == "axiom"));
+}
+
+// ── 3. SMT-LIB 2 ────────────────────────────────────────────────────────────
+
+/// Hand-computed from SMT-LIB 2.6. Fully parenthesised, `=>` for implication,
+/// `(forall ((x S)) …)` for the binder, and `true`/`false` for the two truth
+/// constants, which SMT-LIB has and TPTP spells `$true`/`$false`.
+#[test]
+fn smtlib_renders_every_constructor() {
+ let cases: Vec<(Form, &str)> = vec![
+ (Form::Tru, "true"),
+ (Form::Fls, "false"),
+ (thing(v(0)), "(thing X0)"),
+ (lit(v(1)), "(lit X1)"),
+ (cls("http://e/A", v(0)), "(|c:http://e/A| X0)"),
+ (
+ op("http://e/r", v(0), k("http://e/a")),
+ "(|op:http://e/r| X0 |i:http://e/a|)",
+ ),
+ (
+ Form::Eq(k("http://e/a"), k("http://e/b")),
+ "(= |i:http://e/a| |i:http://e/b|)",
+ ),
+ (neg(thing(v(0))), "(not (thing X0))"),
+ (and(Form::Tru, Form::Fls), "(and true false)"),
+ (Form::Or(Box::new(Form::Tru), Box::new(Form::Fls)), "(or true false)"),
+ (imp(Form::Tru, Form::Fls), "(=> true false)"),
+ (all(0, thing(v(0))), "(forall ((X0 U)) (thing X0))"),
+ (ex(2, lit(v(2))), "(exists ((X2 U)) (lit X2))"),
+ ];
+ for (f, want) in cases {
+ assert_eq!(smtlib::form(&f).expect("writable"), want, "for {f:?}");
+ }
+}
+
+/// One real translated axiom, unrolled by hand through `OwlLean.trAx` and then
+/// through the SMT-LIB grammar, so that the two unrollings meet.
+///
+/// `trAx (subClass (atom A) (some_ r (atom B)))` is
+/// `allObj 0 (imp (cls A (v 0)) (exObj 2 (and (op r (v 0) (v 2)) (cls B (v 2)))))`
+/// with `allObj n f = all n (imp (thing (v n)) f)` and
+/// `exObj n f = ex n (and (thing (v n)) f)`. The bound variable is X2 because
+/// `trAx` starts the counter at 2, which is the same fact
+/// `some_values_from_allocates_x2` pins on the TPTP side.
+#[test]
+fn smtlib_of_a_translated_axiom() {
+ let f = Translation::axiom(&OwlAxiom::SubClass(
+ Concept::Atom("http://e/A".into()),
+ Concept::Some_("http://e/r".into(), Box::new(Concept::Atom("http://e/B".into()))),
+ ))
+ .expect("freshness holds at trAx's own call sites");
+ assert_eq!(
+ smtlib::form(&f).expect("writable"),
+ "(forall ((X0 U)) (=> (thing X0) (=> (|c:http://e/A| X0) \
+ (exists ((X2 U)) (and (thing X2) (and (|op:http://e/r| X0 X2) (|c:http://e/B| X2)))))))"
+ );
+}
+
+/// The two sort declarations, and the difference between them, which is what
+/// decides whether an `unsat` means anything.
+#[test]
+fn the_two_encodings_declare_the_carrier_differently() {
+ assert_eq!(smtlib::sort_decl(SmtEncoding::Unbounded), "(declare-sort U 0)");
+ assert_eq!(smtlib::logic(SmtEncoding::Unbounded), "UF");
+ assert_eq!(SmtEncoding::Unbounded.name(), "unbounded");
+ assert_eq!(SmtEncoding::Unbounded.bound(), None);
+
+ assert_eq!(
+ smtlib::sort_decl(SmtEncoding::Finite(3)),
+ "(declare-datatypes ((U 0)) (((e0) (e1) (e2))))"
+ );
+ assert_eq!(smtlib::logic(SmtEncoding::Finite(3)), "UFDT");
+ assert_eq!(SmtEncoding::Finite(3).name(), "finite(3)");
+ assert_eq!(SmtEncoding::Finite(3).bound(), Some(3));
+}
+
+/// `thing` and `lit` are legal simple symbols and stay bare; everything else
+/// carries a colon, which SMT-LIB's simple-symbol set excludes, and is quoted.
+#[test]
+fn smtlib_quotes_exactly_what_it_must() {
+ assert_eq!(smtlib::symbol("thing").expect("writable"), "thing");
+ assert_eq!(smtlib::symbol("lit").expect("writable"), "lit");
+ assert_eq!(smtlib::symbol("c:X").expect("writable"), "|c:X|");
+ assert_eq!(
+ smtlib::symbol("i:http://e/a#b").expect("writable"),
+ "|i:http://e/a#b|"
+ );
+}
+
+/// A symbol containing `|` or `\` is REFUSED, because a quoted SMT-LIB symbol
+/// admits every character except those two and defines no escape for either.
+/// Shown failing on both.
+#[test]
+fn smtlib_refuses_the_two_characters_it_cannot_escape() {
+ for bad in ['|', '\\'] {
+ let e = smtlib::symbol(&format!("c:http://e/A{bad}B")).expect_err("must refuse");
+ assert_eq!(e.character, bad);
+ assert_eq!(e.syntax, "SMT-LIB 2");
+ // And through the whole formula printer, not only the symbol function.
+ let f = cls(&format!("http://e/A{bad}B"), v(0));
+ assert!(smtlib::form(&f).is_err(), "form() must propagate the refusal");
+ }
+}
+
+/// `--smt-domain 0` asks for an empty carrier, which no first-order structure
+/// has and which `Fol.FinModel`, defined only at `n+1`, cannot represent.
+#[test]
+fn an_empty_carrier_is_refused_at_the_flag() {
+ let e = Syntax::parse("smtlib", None, None, Some(0)).expect_err("must refuse");
+ assert!(e.to_string().contains("empty carrier"), "{e}");
+ assert!(Syntax::parse("smtlib", None, None, Some(1)).is_ok());
+ assert!(Syntax::parse("smtlib", None, None, None).is_ok());
+}
+
+// ── 4. LADR, for Mace4 ──────────────────────────────────────────────────────
+
+/// Hand-computed from the Prover9/Mace4 manual's connective table: `-` for
+/// negation, `&`, `|`, `->`, `all x`, `exists x`, and `$T`/`$F` for the truth
+/// constants. Fully parenthesised, because LADR's precedence table is not
+/// worth relying on and a misparse there is silent.
+#[test]
+fn ladr_renders_every_constructor() {
+ let problem = FolProblem {
+ background: vec![],
+ ind_axioms: vec![],
+ axioms: vec![
+ ("x".into(), cls("http://e/A", v(0))),
+ ("x".into(), lit(v(0))),
+ ("x".into(), thing(v(0))),
+ ("x".into(), op("http://e/r", v(0), k("http://e/a"))),
+ ],
+ conjecture: None,
+ individuals: Default::default(),
+ };
+ let t = ladr::SymbolTable::build(&problem).expect("no variable letters");
+ // Sorted order: c:http://e/A, lit, thing → p0, p1, p2.
+ assert_eq!(t.unary.get("c:http://e/A").map(String::as_str), Some("p0"));
+ assert_eq!(t.unary.get("lit").map(String::as_str), Some("p1"));
+ assert_eq!(t.unary.get("thing").map(String::as_str), Some("p2"));
+ assert_eq!(t.binary.get("op:http://e/r").map(String::as_str), Some("r0"));
+ assert_eq!(t.consts.get("i:http://e/a").map(String::as_str), Some("c0"));
+
+ let cases: Vec<(Form, &str)> = vec![
+ (Form::Tru, "$T"),
+ (Form::Fls, "$F"),
+ (thing(v(0)), "p2(x0)"),
+ (cls("http://e/A", k("http://e/a")), "p0(c0)"),
+ (op("http://e/r", v(0), v(1)), "r0(x0,x1)"),
+ (
+ Form::Eq(k("http://e/a"), k("http://e/a")),
+ "(c0 = c0)",
+ ),
+ (neg(thing(v(0))), "-(p2(x0))"),
+ (and(Form::Tru, Form::Fls), "($T & $F)"),
+ (Form::Or(Box::new(Form::Tru), Box::new(Form::Fls)), "($T | $F)"),
+ (imp(Form::Tru, Form::Fls), "($T -> $F)"),
+ (all(0, thing(v(0))), "(all x0 (p2(x0)))"),
+ (ex(1, thing(v(1))), "(exists x1 (p2(x1)))"),
+ ];
+ for (f, want) in cases {
+ assert_eq!(ladr::form(&f, &t).expect("in the table"), want, "for {f:?}");
+ }
+}
+
+/// THE LADR TRAP, as a gate that fires.
+///
+/// LADR reads a name whose first letter is in {u,v,w,x,y,z} as a VARIABLE.
+/// Measured on LADR 2009-11A: `p0(w0). -p0(k0).` is echoed in Mace4's own
+/// CLAUSES FOR SEARCH block as `p0(x).` and `-p0(k0).`, the search is
+/// exhausted, and the run reports no model with no error at all. A mangler
+/// that emitted such a name would make every Mace4 run silently wrong, so the
+/// check is a function and this is it failing.
+#[test]
+fn the_ladr_variable_letters_are_refused() {
+ for bad in ["u0", "v1", "w0", "x3", "y", "z_name", "X0", "Z9"] {
+ assert!(ladr::is_variable_name(bad), "{bad} must read as a variable");
+ let e = ladr::check_not_variable(bad).expect_err("must refuse");
+ assert_eq!(e.name, bad);
+ assert!(e.to_string().contains("VARIABLE"), "{e}");
+ }
+ // The prefixes the mangler actually uses are not variables, so the gate is
+ // not a constant. `c…` is included deliberately: LADR names its own Skolem
+ // constants `c1, c2, …` and picks one not already in the problem, measured.
+ for good in ["p0", "r0", "c0", "p17", "thing"] {
+ assert!(!ladr::is_variable_name(good), "{good} must read as a symbol");
+ assert!(ladr::check_not_variable(good).is_ok());
+ }
+ // Bound variables ARE variables under the same convention, which is the
+ // point: `x0` has to read as one.
+ assert!(ladr::is_variable_name("x0"));
+}
+
+/// A symbol the table never issued cannot be rendered, and cannot be
+/// demangled back into one either.
+#[test]
+fn the_mangling_is_a_closed_table() {
+ let problem = FolProblem {
+ background: vec![],
+ ind_axioms: vec![],
+ axioms: vec![("x".into(), thing(v(0)))],
+ conjecture: None,
+ individuals: Default::default(),
+ };
+ let t = ladr::SymbolTable::build(&problem).expect("no variable letters");
+ assert_eq!(t.len(), 1);
+ assert_eq!(t.demangle("p0"), Some("thing"));
+ // A Skolem name Mace4 invented is not in the table, which is how the
+ // ingestion knows to drop it rather than claim it interpreted something.
+ assert_eq!(t.demangle("f1"), None);
+ assert_eq!(t.demangle("c7"), None);
+ // And a formula over a symbol outside the table is an error, not a guess.
+ assert!(ladr::form(&cls("http://e/A", v(0)), &t).is_err());
+}
+
+// ── 5. One problem, three files ─────────────────────────────────────────────
+
+/// The SMT-LIB file, the LADR file and `problem.tsv` are folds over the same
+/// `checker_entries()`, so they carry the same formulas in the same order.
+///
+/// This is the mechanical reason the solver cannot be asked a different
+/// question from the one the checker then checks. It is the same argument
+/// `FolProblem::formulas` makes for TPTP and CLIF, one level down.
+#[test]
+fn the_three_printers_carry_the_same_problem() {
+ let axioms = vec![
+ OwlAxiom::SubClass(
+ Concept::Atom("http://e/A".into()),
+ Concept::Some_("http://e/r".into(), Box::new(Concept::Atom("http://e/B".into()))),
+ ),
+ OwlAxiom::ClassAssert(Concept::Atom("http://e/A".into()), "http://e/a".into()),
+ ];
+ let goal = OwlAxiom::ClassAssert(Concept::Atom("http://e/B".into()), "http://e/a".into());
+ let p = FolProblem::build(&axioms, Some(&goal)).expect("freshness holds");
+ let entries = p.checker_entries();
+
+ let (tsv, digest) = p.to_problem_tsv().expect("writable");
+ assert_eq!(tsv.lines().count(), entries.len());
+ assert_eq!(digest.len(), 16);
+ assert!(digest.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));
+
+ let smt = p.to_smtlib(SmtEncoding::Finite(2)).expect("writable");
+ assert_eq!(smt.matches("\n(assert ").count(), entries.len());
+
+ let t = ladr::SymbolTable::build(&p).expect("no variable letters");
+ let la = ladr::problem(&p, &t, 5).expect("writable");
+ // One clause line per entry, each terminated by LADR's `.`
+ let clauses = la
+ .lines()
+ .skip_while(|l| !l.starts_with("formulas(assumptions)"))
+ .filter(|l| l.starts_with(" ") && !l.trim_start().starts_with('%'))
+ .count();
+ assert_eq!(clauses, entries.len());
+
+ // And the LAST formula of each is the negated goal, not the conjecture.
+ let goal_form = &entries.last().expect("a goal").form;
+ assert!(tsv.lines().last().expect("a line").starts_with("goal_negated\t"));
+ assert!(smt.contains(&format!("(assert {})", smtlib::form(goal_form).expect("writable"))));
+ assert!(la.contains(&format!(" {}.", ladr::form(goal_form, &t).expect("in table"))));
+}
+
+/// The vocabulary is collected from the NEGATED goal too, so a symbol that
+/// occurs only in the conjecture is still declared. Without that, the model
+/// file would omit it and `Fol.covers` would reject the run on an attribution
+/// failure that is really an exporter bug.
+#[test]
+fn the_vocabulary_includes_the_goals_symbols() {
+ let axioms = vec![OwlAxiom::ClassAssert(
+ Concept::Atom("http://e/A".into()),
+ "http://e/a".into(),
+ )];
+ let goal = OwlAxiom::ClassAssert(Concept::Atom("http://e/OnlyInTheGoal".into()), "http://e/a".into());
+ let p = FolProblem::build(&axioms, Some(&goal)).expect("freshness holds");
+ let v = p.vocabulary();
+ assert!(v.unary.contains("c:http://e/OnlyInTheGoal"), "{:?}", v.unary);
+ assert!(v.unary.contains("thing"));
+ assert!(v.consts.contains("i:http://e/a"));
+ assert!(!v.is_empty());
+}
+
+/// One namer, and the seven images are pairwise disjoint whatever the IRIs
+/// are. `thing` and `lit` carry no colon; every other arm carries its own.
+///
+/// This is what makes the monomorphisation at `Sym := String` in
+/// `lean/Fol/Syntax.lean` sound: without the prefixes a class IRI and a
+/// datatype IRI with the same spelling would become ONE predicate, and a model
+/// could satisfy a problem the ontology does not.
+#[test]
+fn the_seven_symbol_images_are_disjoint() {
+ let same = "http://e/X";
+ let images = [
+ sym::p1(&P1::Thing),
+ sym::p1(&P1::Lit),
+ sym::p1(&P1::Cls(same.into())),
+ sym::p1(&P1::Dt(same.into())),
+ sym::p2(&P2::Op(same.into())),
+ sym::p2(&P2::Dp(same.into())),
+ sym::constant(same),
+ ];
+ let unique: std::collections::BTreeSet<&String> = images.iter().collect();
+ assert_eq!(unique.len(), 7, "{images:?}");
+ assert_eq!(images[2], "c:http://e/X");
+ assert_eq!(images[3], "d:http://e/X");
+ assert_eq!(images[4], "op:http://e/X");
+ assert_eq!(images[5], "dp:http://e/X");
+ assert_eq!(images[6], "i:http://e/X");
+}
+
+/// The namer is the one the OTHER two printers already used, so a drift in it
+/// shows up in all five. Checked by stripping the quoting each adds.
+#[test]
+fn the_older_printers_read_the_same_namer() {
+ let f = cls("http://e/A", v(0));
+ let tptp = open_ontologies::tptp::fof::form(&f);
+ let clif = open_ontologies::tptp::clif::form(&f);
+ let smt = smtlib::form(&f).expect("writable");
+ let image = sym::p1(&P1::Cls("http://e/A".into()));
+ assert!(tptp.contains(&format!("'{image}'")), "{tptp}");
+ assert!(clif.contains(&format!("\"{image}\"")), "{clif}");
+ assert!(smt.contains(&format!("|{image}|")), "{smt}");
+}
diff --git a/tests/fol_model_ingest_test.rs b/tests/fol_model_ingest_test.rs
new file mode 100644
index 00000000..3a6cd1b3
--- /dev/null
+++ b/tests/fol_model_ingest_test.rs
@@ -0,0 +1,553 @@
+//! Reading a solver's model back, and every way of failing to.
+//!
+//! Two printed formats, one structure. Z3 prints `define-fun` bodies that have
+//! to be EVALUATED; Mace4 prints dense integer tables that have to be INDEXED.
+//! The point of the shape of `src/fol_model.rs` is that a third finder costs a
+//! third `parse_model` and nothing else, so these tests exercise the two front
+//! ends separately and the shared half once.
+//!
+//! # Every solver string below was MEASURED
+//!
+//! Z3 4.16.0 and LADR 2009-11A on this machine, copied out of a real run and
+//! then edited only where the test says it is a forgery. A hand-invented
+//! format would test the parser against a format nobody emits.
+//!
+//! # G3: every way of lying, each shown failing on its own
+//!
+//! A gate that cannot fail is decoration, so each of these has a positive case
+//! beside it that the same code path accepts:
+//!
+//! * a model omitting a symbol the problem uses (`Uninterpreted`);
+//! * a model whose carrier is empty (`EmptyDomain`);
+//! * a model interpreting a predicate at an arity the problem does not use
+//! (`Unsupported`, through the `define-fun` sort check on the Z3 side and
+//! through the `relation(p(_,_))` arity on the Mace4 side);
+//! * a table whose width is not the declared carrier (`BadWidth`);
+//! * a constant outside the carrier (`OutOfRange`);
+//! * a body using a construct the evaluator does not know (`Unsupported`,
+//! naming the construct rather than approximating it);
+//! * no model at all where one was expected (`NoModel`).
+//!
+//! The fifth forgery of G3, a model built for a DIFFERENT problem, is not an
+//! ingestion failure at all: it is caught by the digest inside the verified
+//! checker, and `lean_fol_model_test.rs` shows that one failing.
+//!
+//! # Why a bug here cannot produce a false certificate
+//!
+//! The checker re-evaluates the ORIGINAL formulas against whatever structure
+//! comes out of this module, so a misread table yields a structure that fails
+//! `Fol.check` and the pipeline reports a stop-the-line disagreement. The
+//! failure mode of a parser bug here is a false alarm, never a false clean.
+
+use open_ontologies::fol_model::{FiniteModel, IngestError, mace4, z3};
+use open_ontologies::tptp::{FolProblem, Form, P1, P2, Term, Vocabulary, ladr};
+
+fn vocab(unary: &[&str], binary: &[&str], consts: &[&str]) -> Vocabulary {
+ Vocabulary {
+ unary: unary.iter().map(|s| s.to_string()).collect(),
+ binary: binary.iter().map(|s| s.to_string()).collect(),
+ consts: consts.iter().map(|s| s.to_string()).collect(),
+ }
+}
+
+/// Z3 4.16.0, `(get-model)` over an enumeration carrier of 2, verbatim from a
+/// run of the worked example in `lean/Fol/Syntax.lean`. Four body shapes
+/// appear in it and all four are ones Z3 really emits: a bare `true`, a bare
+/// `false`, an `ite` over an `=`, and a nullary `define-fun` returning an
+/// element.
+const Z3_MODEL: &str = r#"sat
+(
+ (define-fun |i:a| () U
+ e0)
+ (define-fun |c:Person| ((x!0 U)) Bool
+ true)
+ (define-fun |c:Company| ((x!0 U)) Bool
+ (ite (= x!0 e1) true
+ false))
+ (define-fun lit ((x!0 U)) Bool
+ false)
+ (define-fun |op:worksFor| ((x!0 U) (x!1 U)) Bool
+ true)
+ (define-fun thing ((x!0 U)) Bool
+ true)
+)"#;
+
+fn full_vocab() -> Vocabulary {
+ vocab(
+ &["thing", "lit", "c:Person", "c:Company"],
+ &["op:worksFor"],
+ &["i:a"],
+ )
+}
+
+// ── Z3: the positive case ───────────────────────────────────────────────────
+
+#[test]
+fn a_z3_model_is_read_as_the_structure_it_describes() {
+ let m = z3::parse_model(Z3_MODEL, &full_vocab(), 2).expect("a readable model");
+ assert_eq!(m.domain, 2);
+ assert_eq!(m.source, "z3");
+ // `true` at every element.
+ assert_eq!(m.unary["thing"], vec![true, true]);
+ assert_eq!(m.unary["lit"], vec![false, false]);
+ // `(ite (= x!0 e1) true false)` is the singleton {1}, EVALUATED and not
+ // pattern-matched: this is the one body shape a naive reader gets wrong.
+ assert_eq!(m.unary["c:Company"], vec![false, true]);
+ assert_eq!(m.binary["op:worksFor"], vec![vec![true, true], vec![true, true]]);
+ assert_eq!(m.consts["i:a"], 0);
+ assert!(m.dropped.is_empty());
+ m.self_check("z3").expect("well shaped");
+ m.covers(&full_vocab(), "z3").expect("complete");
+}
+
+/// The bodies Z3 actually emits on larger models: `and`, `or`, `not`, `=>`,
+/// `distinct`, `xor` and `let`. Measured shapes, one per case, evaluated
+/// pointwise over a carrier of 4.
+#[test]
+fn the_evaluator_handles_the_connectives_z3_emits() {
+ let model = r#"(
+ (define-fun p ((x!0 U)) Bool
+ (and (not (= x!0 e1)) (not (= x!0 e3))))
+ (define-fun q ((x!0 U)) Bool
+ (or (= x!0 e0) (= x!0 e2)))
+ (define-fun s ((x!0 U)) Bool
+ (=> (= x!0 e0) false))
+ (define-fun t ((x!0 U)) Bool
+ (distinct x!0 e0 ))
+ (define-fun u ((x!0 U)) Bool
+ (xor (= x!0 e0) (= x!0 e1)))
+ (define-fun w ((x!0 U)) Bool
+ (let ((a!1 (= x!0 e2))) (not a!1)))
+ (define-fun r ((x!0 U) (x!1 U)) Bool
+ (or (and (= x!0 e1) (= x!1 e0)) (and (not (= x!0 e1)) (= x!1 e1))))
+)"#;
+ let v = vocab(&["p", "q", "s", "t", "u", "w"], &["r"], &[]);
+ let m = z3::parse_model(model, &v, 4).expect("a readable model");
+ assert_eq!(m.unary["p"], vec![true, false, true, false]);
+ assert_eq!(m.unary["q"], vec![true, false, true, false]);
+ assert_eq!(m.unary["s"], vec![false, true, true, true]);
+ assert_eq!(m.unary["t"], vec![false, true, true, true]);
+ assert_eq!(m.unary["u"], vec![true, true, false, false]);
+ assert_eq!(m.unary["w"], vec![true, true, false, true]);
+ // r(1,0) and r(i,1) for i != 1.
+ assert_eq!(
+ m.binary["r"],
+ vec![
+ vec![false, true, false, false],
+ vec![true, false, false, false],
+ vec![false, true, false, false],
+ vec![false, true, false, false],
+ ]
+ );
+}
+
+/// Symbols the translation never emitted are the REDUCT and are reported
+/// rather than hidden. Taking one needs no lemma, because the checker
+/// re-evaluates formulas that cannot mention them.
+#[test]
+fn symbols_outside_the_problem_are_dropped_and_named() {
+ let model = r#"(
+ (define-fun thing ((x!0 U)) Bool true)
+ (define-fun |k!17| ((x!0 U)) Bool false)
+ (define-fun |f!aux| () U e0)
+)"#;
+ let m = z3::parse_model(model, &vocab(&["thing"], &[], &[]), 1).expect("readable");
+ assert_eq!(m.dropped, vec!["k!17".to_string(), "f!aux".to_string()]);
+ assert_eq!(m.unary.len(), 1);
+}
+
+// ── Z3: the forgeries ───────────────────────────────────────────────────────
+
+/// G3.4, at the ingestion boundary. A symbol the problem uses that the solver
+/// left uninterpreted is an ERROR here and not a default.
+///
+/// The checker would catch it one step later as an attribution failure, and
+/// `FinModel`'s fields are total so soundness would survive it either way.
+/// What would not survive is the sentence "the solver's model was checked",
+/// because the thing checked would be the solver's model completed with
+/// defaults. It is caught here so the message can name the solver.
+#[test]
+fn a_z3_model_missing_a_symbol_is_rejected() {
+ let e = z3::parse_model(Z3_MODEL, &vocab(&["thing", "c:Missing"], &[], &[]), 2)
+ .expect_err("must reject");
+ match &e {
+ IngestError::Uninterpreted { solver, symbol, arity } => {
+ assert_eq!(*solver, "z3");
+ assert_eq!(symbol, "c:Missing");
+ assert_eq!(*arity, "unary");
+ }
+ other => panic!("wrong arm: {other:?}"),
+ }
+ assert!(e.to_string().contains("would DEFAULT"), "{e}");
+ // The same model with the symbol removed from the problem is accepted, so
+ // the gate is not a constant.
+ assert!(z3::parse_model(Z3_MODEL, &vocab(&["thing"], &[], &[]), 2).is_ok());
+}
+
+/// G3.2 at the ingestion boundary: an empty carrier, refused before anything
+/// is read. `Fol.FinModel` is defined only at `n+1`, so the empty carrier is
+/// unrepresentable downstream and this is the file-level half of that.
+#[test]
+fn an_empty_carrier_is_rejected() {
+ let e = z3::parse_model(Z3_MODEL, &full_vocab(), 0).expect_err("must reject");
+ assert!(matches!(e, IngestError::EmptyDomain { solver: "z3" }), "{e:?}");
+ // A carrier of one is fine, so the gate is about the EMPTY carrier and not
+ // about small ones. A model for a carrier of one, measured from a run of
+ // the shipped ontology fixture at `--max-domain 1`.
+ let one = r#"( (define-fun thing ((x!0 U)) Bool true) (define-fun |i:a| () U e0) )"#;
+ let m = z3::parse_model(one, &vocab(&["thing"], &[], &["i:a"]), 1).expect("readable");
+ assert_eq!(m.domain, 1);
+ assert_eq!(m.unary["thing"], vec![true]);
+}
+
+/// Reading a carrier-2 model at a carrier of 1 FAILS rather than truncating.
+///
+/// `Z3_MODEL`'s body for `c:Company` names the element `e1`, which does not
+/// exist at domain 1. Silently treating an unknown `eN` as false would build a
+/// structure the solver never described, so the evaluator refuses by name.
+#[test]
+fn a_model_read_at_the_wrong_carrier_is_rejected() {
+ let e = z3::parse_model(Z3_MODEL, &full_vocab(), 1).expect_err("must reject");
+ match &e {
+ IngestError::Unsupported { construct, .. } => assert_eq!(construct, "e1"),
+ other => panic!("wrong arm: {other:?}"),
+ }
+}
+
+/// G3.3 at the ingestion boundary: a predicate interpreted at an arity the
+/// problem does not use.
+///
+/// The first version of this parser took the `define-fun`'s RETURN SORT for
+/// its body, and every ingestion failed with `z3's model uses "Bool"`. The
+/// stop-the-line block caught it on the first real run; the sort check is what
+/// turns that into a message naming the symbol.
+#[test]
+fn a_z3_symbol_at_the_wrong_arity_is_rejected() {
+ // `thing` supplied as a BINARY predicate while the problem uses it unary.
+ let model = r#"(
+ (define-fun thing ((x!0 U) (x!1 U)) Bool true)
+)"#;
+ let e = z3::parse_model(model, &vocab(&["thing"], &[], &[]), 2).expect_err("must reject");
+ match &e {
+ IngestError::Unsupported { solver, construct, context } => {
+ assert_eq!(*solver, "z3");
+ assert!(construct.contains("2 argument(s)"), "{construct}");
+ assert!(context.contains("thing"), "{context}");
+ }
+ other => panic!("wrong arm: {other:?}"),
+ }
+ // A constant whose define-fun returns Bool rather than U.
+ let model2 = r#"( (define-fun |i:a| () Bool true) )"#;
+ assert!(z3::parse_model(model2, &vocab(&[], &[], &["i:a"]), 2).is_err());
+ // Correct arities are accepted.
+ let good = r#"( (define-fun thing ((x!0 U)) Bool true) (define-fun |i:a| () U e1) )"#;
+ let m = z3::parse_model(good, &vocab(&["thing"], &[], &["i:a"]), 2).expect("readable");
+ assert_eq!(m.consts["i:a"], 1);
+}
+
+/// A construct the evaluator does not know is NAMED, never approximated. An
+/// approximated structure is a different structure, and certifying it would
+/// say something true about the wrong object.
+#[test]
+fn an_unknown_construct_is_named_rather_than_guessed() {
+ let model = r#"( (define-fun p ((x!0 U)) Bool (bvult x!0 e1)) )"#;
+ let e = z3::parse_model(model, &vocab(&["p"], &[], &[]), 2).expect_err("must reject");
+ match &e {
+ IngestError::Unsupported { construct, .. } => assert_eq!(construct, "bvult"),
+ other => panic!("wrong arm: {other:?}"),
+ }
+ assert!(e.to_string().contains("DIFFERENT structure"), "{e}");
+}
+
+/// A constant naming an element outside the declared carrier.
+#[test]
+fn a_z3_constant_outside_the_carrier_is_rejected() {
+ let model = r#"( (define-fun |i:a| () U e5) )"#;
+ // `e5` is not a carrier element at domain 2, so it is not even an element
+ // name: the evaluator has nothing to map it to and says so.
+ let e = z3::parse_model(model, &vocab(&[], &[], &["i:a"]), 2).expect_err("must reject");
+ assert!(matches!(e, IngestError::Unsupported { .. }), "{e:?}");
+ // At a carrier that contains it, the same file reads.
+ let m = z3::parse_model(model, &vocab(&[], &[], &["i:a"]), 6).expect("readable");
+ assert_eq!(m.consts["i:a"], 5);
+}
+
+/// No model where one was expected.
+#[test]
+fn a_z3_run_with_no_model_is_rejected() {
+ let e = z3::parse_model("unsat\n", &full_vocab(), 2).expect_err("must reject");
+ assert!(matches!(e, IngestError::NoModel { solver: "z3", .. }), "{e:?}");
+ let e2 = z3::parse_model("(error \"line 3: unknown sort\")", &full_vocab(), 2)
+ .expect_err("must reject");
+ assert!(matches!(e2, IngestError::NoModel { .. }), "{e2:?}");
+}
+
+/// The S-expression reader itself, on the three things Z3's output contains
+/// that a naive splitter gets wrong: `|quoted symbols|` holding slashes and
+/// colons, `;;` comment lines, and nesting.
+#[test]
+fn the_sexp_reader_survives_z3s_own_punctuation() {
+ let text = ";; universe for U:\n;; U!val!0\n( (define-fun |c:http://e/A#x| ((x!0 U)) Bool true) )";
+ let m = z3::parse_model(text, &vocab(&["c:http://e/A#x"], &[], &[]), 1).expect("readable");
+ assert_eq!(m.unary["c:http://e/A#x"], vec![true]);
+ // An unclosed bracket is a syntax error and not a partial read.
+ assert!(matches!(
+ z3::parse_sexps("(define-fun p ("),
+ Err(IngestError::Syntax { .. })
+ ));
+ assert!(matches!(z3::parse_sexps(")"), Err(IngestError::Syntax { .. })));
+}
+
+// ── Mace4: the positive case ────────────────────────────────────────────────
+
+/// LADR 2009-11A, verbatim. `f1` is a Skolem function and `c2` a Skolem
+/// constant Mace4 chose itself; both are outside the mangling table and are
+/// the reduct.
+const MACE4_MODEL: &str = r#"============================== MODEL =================================
+
+interpretation( 2, [number=1, seconds=0], [
+
+ function(c0, [ 0 ]),
+
+ function(c2, [ 1 ]),
+
+ function(f1(_), [ 1, 0 ]),
+
+ relation(p0(_), [ 1, 0 ]),
+
+ relation(p1(_), [ 0, 0 ]),
+
+ relation(r0(_,_), [
+ 0, 1,
+ 0, 0 ])
+]).
+
+============================== end of model ==========================
+"#;
+
+/// A problem whose mangling is p0 = `c:A`, p1 = `lit`, r0 = `op:r`,
+/// c0 = `i:a`, built through the real `SymbolTable::build` so the test uses
+/// the mangling the writer would have used.
+fn mace4_table() -> ladr::SymbolTable {
+ let p = FolProblem {
+ background: vec![],
+ ind_axioms: vec![],
+ axioms: vec![
+ ("x".into(), Form::App1(P1::Cls("A".into()), Term::Var(0))),
+ ("x".into(), Form::App1(P1::Lit, Term::Var(0))),
+ (
+ "x".into(),
+ Form::App2(P2::Op("r".into()), Term::Var(0), Term::Const("a".into())),
+ ),
+ ],
+ conjecture: None,
+ individuals: Default::default(),
+ };
+ ladr::SymbolTable::build(&p).expect("no variable letters")
+}
+
+#[test]
+fn a_mace4_model_is_read_as_the_structure_it_describes() {
+ let t = mace4_table();
+ assert_eq!(t.unary.get("c:A").map(String::as_str), Some("p0"));
+ assert_eq!(t.unary.get("lit").map(String::as_str), Some("p1"));
+ assert_eq!(t.binary.get("op:r").map(String::as_str), Some("r0"));
+ assert_eq!(t.consts.get("i:a").map(String::as_str), Some("c0"));
+
+ let m = mace4::parse_model(MACE4_MODEL, &t).expect("a readable model");
+ assert_eq!(m.domain, 2);
+ assert_eq!(m.source, "mace4");
+ assert_eq!(m.unary["c:A"], vec![true, false]);
+ assert_eq!(m.unary["lit"], vec![false, false]);
+ // ROW MAJOR: the table [0,1,0,0] is r(0,1) alone.
+ assert_eq!(m.binary["op:r"], vec![vec![false, true], vec![false, false]]);
+ assert_eq!(m.consts["i:a"], 0);
+ // The Skolem names are the reduct and are reported.
+ assert_eq!(m.dropped, vec!["c2".to_string(), "f1".to_string()]);
+ m.self_check("mace4").expect("well shaped");
+}
+
+// ── Mace4: the forgeries ────────────────────────────────────────────────────
+
+/// THE LADR VARIABLE-LETTER TRAP, caught mechanically.
+///
+/// A mangled constant that LADR read as a variable simply DISAPPEARS from the
+/// model: there is no `function(w0, …)` block for it, because there is no such
+/// symbol in the problem Mace4 solved. Measured on LADR 2009-11A, input
+/// `p0(w0). -p0(k0).` is echoed as `p0(x).` and the search reports
+/// `exit (exhausted)` with no error at all. The guard is that every symbol the
+/// TABLE issued must come back interpreted, so the disappearance is an error
+/// naming the symbol rather than a silent no-model.
+#[test]
+fn a_constant_missing_from_a_mace4_model_is_rejected() {
+ let t = mace4_table();
+ let without_c0 = MACE4_MODEL.replace("function(c0, [ 0 ]),", "");
+ let m = mace4::parse_model(&without_c0, &t).expect("the block still parses");
+ let v = vocab(&["c:A", "lit"], &["op:r"], &["i:a"]);
+ let e = m.covers(&v, "mace4").expect_err("must reject");
+ match &e {
+ IngestError::Uninterpreted { solver, symbol, arity } => {
+ assert_eq!(*solver, "mace4");
+ assert_eq!(symbol, "i:a");
+ assert_eq!(*arity, "constant");
+ }
+ other => panic!("wrong arm: {other:?}"),
+ }
+ // With the block present the same check passes, so the gate is not a
+ // constant.
+ let whole = mace4::parse_model(MACE4_MODEL, &t).expect("readable");
+ assert!(whole.covers(&v, "mace4").is_ok());
+}
+
+/// A relation table whose length is not the declared carrier.
+#[test]
+fn a_mace4_table_of_the_wrong_width_is_rejected() {
+ let t = mace4_table();
+ let forged = MACE4_MODEL.replace("relation(p0(_), [ 1, 0 ])", "relation(p0(_), [ 1, 0, 1 ])");
+ let e = mace4::parse_model(&forged, &t).expect_err("must reject");
+ match &e {
+ IngestError::BadWidth { solver, symbol, want, got } => {
+ assert_eq!(*solver, "mace4");
+ assert_eq!(symbol, "c:A");
+ assert_eq!((*want, *got), (2, 3));
+ }
+ other => panic!("wrong arm: {other:?}"),
+ }
+ // A binary table of the wrong area, separately.
+ let forged2 = MACE4_MODEL.replace("0, 1,\n\t\t\t 0, 0 ]", "0, 1, 0 ]");
+ assert!(mace4::parse_model(&forged2, &t).is_err());
+}
+
+/// A constant pointing outside the carrier.
+#[test]
+fn a_mace4_constant_outside_the_carrier_is_rejected() {
+ let t = mace4_table();
+ let forged = MACE4_MODEL.replace("function(c0, [ 0 ])", "function(c0, [ 5 ])");
+ let e = mace4::parse_model(&forged, &t).expect_err("must reject");
+ match &e {
+ IngestError::OutOfRange { solver, symbol, index, domain } => {
+ assert_eq!(*solver, "mace4");
+ assert_eq!(symbol, "i:a");
+ assert_eq!((*index, *domain), (5, 2));
+ }
+ other => panic!("wrong arm: {other:?}"),
+ }
+}
+
+/// G3.3, Mace4 half: a symbol the TABLE issued, coming back at an arity the
+/// fragment has no slot for. That is a defect in the mangler rather than a
+/// reduct, so it is named rather than dropped.
+#[test]
+fn a_mace4_symbol_at_the_wrong_arity_is_rejected() {
+ let t = mace4_table();
+ let forged = MACE4_MODEL.replace(
+ "relation(p0(_), [ 1, 0 ])",
+ "relation(p0(_,_), [ 1, 0, 0, 1 ])",
+ );
+ let e = mace4::parse_model(&forged, &t).expect_err("must reject");
+ match &e {
+ IngestError::Unsupported { solver, construct, context } => {
+ assert_eq!(*solver, "mace4");
+ assert!(construct.contains("relation of arity 2"), "{construct}");
+ assert!(context.contains("c:A"), "{context}");
+ assert!(context.contains("unary symbol"), "{context}");
+ }
+ other => panic!("wrong arm: {other:?}"),
+ }
+ // A constant coming back as a unary FUNCTION is the same failure, and it
+ // is the shape a Skolem function would take if the mangler had issued its
+ // name. Mace4's own `f1(_)` is dropped instead, because the table never
+ // issued `f1`.
+ let forged2 = MACE4_MODEL.replace("function(c0, [ 0 ])", "function(c0(_), [ 0, 1 ])");
+ assert!(mace4::parse_model(&forged2, &t).is_err());
+ // And the table is what decides that, so the unforged file still reads.
+ assert!(mace4::parse_model(MACE4_MODEL, &t).is_ok());
+}
+
+/// An exhausted or failed Mace4 run prints no interpretation block at all.
+#[test]
+fn a_mace4_run_with_no_model_is_rejected() {
+ let text = "------ process 123 exit (exhausted) ------\n\nExiting with failure.\n";
+ let e = mace4::parse_model(text, &mace4_table()).expect_err("must reject");
+ match &e {
+ IngestError::NoModel { solver, saw } => {
+ assert_eq!(*solver, "mace4");
+ assert!(saw.contains("exhausted"), "{saw}");
+ }
+ other => panic!("wrong arm: {other:?}"),
+ }
+}
+
+// ── The shared half ─────────────────────────────────────────────────────────
+
+/// `model.tsv` is written in the shape `lean/Fol/Syntax.lean` specifies:
+/// declarations before rows, dense bit strings, one `p2` row per source
+/// element, and the digest on its own line.
+#[test]
+fn the_model_file_is_written_in_the_checkers_format() {
+ let m = z3::parse_model(Z3_MODEL, &full_vocab(), 2).expect("readable");
+ let tsv = m.to_model_tsv("4403d8aaa0c422f7", &[1, 2]);
+ let lines: Vec<&str> = tsv.lines().collect();
+ assert_eq!(lines[0], "domain\t2");
+ assert_eq!(lines[1], "problem\t4403d8aaa0c422f7");
+ assert_eq!(lines[2], "source\tz3");
+ assert!(tsv.contains("decl1\tthing\n"));
+ assert!(tsv.contains("decl2\top:worksFor\n"));
+ assert!(tsv.contains("declc\ti:a\n"));
+ assert!(tsv.contains("p1\tc:Company\t01\n"), "{tsv}");
+ assert!(tsv.contains("p1\tlit\t00\n"), "{tsv}");
+ // One p2 row per source element, in order, each of width 2.
+ assert!(tsv.contains("p2\top:worksFor\t0\t11\n"), "{tsv}");
+ assert!(tsv.contains("p2\top:worksFor\t1\t11\n"), "{tsv}");
+ assert!(tsv.contains("const\ti:a\t0\n"));
+ assert!(tsv.contains("cardinality_search\t1,2\n"));
+ // A carrier with no search recorded omits the line rather than writing an
+ // empty one, which the Lean parser would read as a field of its own.
+ assert!(!m.to_model_tsv("x", &[]).contains("cardinality_search"));
+}
+
+/// `self_check` is the writer's own gate, and it fires. The Lean parser checks
+/// all of this again at exit 2, but exit 2 is "unreadable", which is not a
+/// verdict in either direction: a writer bug that produced one would look like
+/// a mysterious file rather than a named defect here.
+#[test]
+fn the_writers_own_shape_gate_fires() {
+ let mut m = z3::parse_model(Z3_MODEL, &full_vocab(), 2).expect("readable");
+ m.self_check("z3").expect("starts well shaped");
+
+ let mut short = m.clone();
+ short.unary.insert("thing".into(), vec![true]);
+ assert!(matches!(
+ short.self_check("z3"),
+ Err(IngestError::BadWidth { want: 2, got: 1, .. })
+ ));
+
+ let mut wide = m.clone();
+ wide.consts.insert("i:a".into(), 9);
+ assert!(matches!(
+ wide.self_check("z3"),
+ Err(IngestError::OutOfRange { index: 9, domain: 2, .. })
+ ));
+
+ m.domain = 0;
+ assert!(matches!(m.self_check("z3"), Err(IngestError::EmptyDomain { .. })));
+}
+
+/// A structure with no symbols at all is still a structure, and the writer
+/// says so rather than refusing. The EMPTY PROBLEM is what is refused, and it
+/// is refused by the checker at exit 2, because every structure satisfies an
+/// empty formula list and a certificate over one would say nothing.
+#[test]
+fn an_empty_signature_is_not_an_error() {
+ let m = FiniteModel {
+ domain: 1,
+ unary: Default::default(),
+ binary: Default::default(),
+ consts: Default::default(),
+ source: "hand",
+ dropped: vec![],
+ };
+ m.self_check("hand").expect("well shaped");
+ assert!(m.covers(&Vocabulary::default(), "hand").is_ok());
+ assert_eq!(m.to_model_tsv("x", &[]).lines().count(), 3);
+}
diff --git a/tests/fol_solver_verdict_test.rs b/tests/fol_solver_verdict_test.rs
new file mode 100644
index 00000000..f0dc93c1
--- /dev/null
+++ b/tests/fol_solver_verdict_test.rs
@@ -0,0 +1,689 @@
+//! G4. The verdict discipline, and the test that fails if it is ever relaxed.
+//!
+//! Decision 0006 item 4 fixes five fields and five words, and the reason the
+//! whole layer exists is that they are never collapsed into each other. This
+//! file is to `src/fol_solve.rs` what
+//! `lean_horn_certificate_test.rs::a_user_rule_never_earns_the_absolute_verdict`
+//! is to the Horn layer: the guard against laundering something unchecked into
+//! something certified.
+//!
+//! The three mechanical rules, each with its own test and each SHOWN FAILING
+//! on input built to break it:
+//!
+//! 1. **`model_checked` requires `checker_exit == 0`.** There is one branch
+//! in `src/fol_solve.rs` that writes that word and it sits immediately
+//! after reading a zero exit code off `oo-folmodel`.
+//! `an_unchecked_result_never_reports_the_certified_word` drives the
+//! pipeline with a checker that rejects, a checker that cannot read the
+//! file, and no checker at all, and none of the three may reach it.
+//! 2. **`unsatisfiable_oracle` requires a run with NO cardinality
+//! constraint.** `a_bounded_unsat_is_not_unsatisfiability` uses the
+//! decision record's own example: `∀x∃y (r(x,y) ∧ x≠y)` is unsat at
+//! carrier 1 and sat at carrier 2, so a driver that mapped the first to
+//! `unsatisfiable_oracle` would report a falsehood from correct solver
+//! output.
+//! 3. **`owl_reading` is non-null only when the CHECKER said
+//! `goal_negated_present` and the verdict is `model_checked`.** Read back
+//! out of the checker's own JSON, never from this side's intention.
+//!
+//! # The stub checkers are the point, not a shortcut
+//!
+//! Three of these tests hand the pipeline a checker that is not `oo-folmodel`:
+//! a script that always rejects, one that always fails to read, and a path
+//! that does not exist. That is the only way to exercise the branches a
+//! correct solver and a correct checker never take together, and it is exactly
+//! the shape of the mistake the rule exists to stop: a pipeline that fell back
+//! to the certified word when the checker was unavailable would report
+//! `model_checked` on every machine without Lean installed.
+//!
+//! # G6
+//!
+//! A missing solver or a missing checker SKIPS LOUDLY with the install line
+//! and never passes silently. `common::skip_unless` makes that fatal under
+//! `OO_REQUIRE_FIXTURES=1`, and `a_missing_solver_is_loud` drives the real CLI
+//! with an empty `PATH` to show the marker on stderr.
+
+mod common;
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+use open_ontologies::fol_solve::{
+ Outcome, SolveOptions, Solver, find_checker, solve, verdict_means,
+};
+use open_ontologies::tptp::{FolProblem, Form, P1, P2, Term};
+
+// ── Problems, built small so the carrier they need is known ─────────────────
+
+fn cls(a: &str, t: Term) -> Form {
+ Form::App1(P1::Cls(a.to_string()), t)
+}
+fn op(r: &str, t: Term, u: Term) -> Form {
+ Form::App2(P2::Op(r.to_string()), t, u)
+}
+fn v(n: u32) -> Term {
+ Term::Var(n)
+}
+fn k(a: &str) -> Term {
+ Term::Const(a.to_string())
+}
+fn neg(f: Form) -> Form {
+ Form::Neg(Box::new(f))
+}
+fn and(f: Form, g: Form) -> Form {
+ Form::And(Box::new(f), Box::new(g))
+}
+
+fn problem(axioms: Vec<Form>, conjecture: Option<Form>) -> FolProblem {
+ FolProblem {
+ background: vec![],
+ ind_axioms: vec![],
+ axioms: axioms
+ .into_iter()
+ .enumerate()
+ .map(|(i, f)| (format!("a{i}"), f))
+ .collect(),
+ conjecture: conjecture.map(|f| ("goal".to_string(), f)),
+ individuals: Default::default(),
+ }
+}
+
+/// Satisfiable at carrier 1.
+fn easy() -> FolProblem {
+ problem(vec![cls("A", k("a"))], None)
+}
+
+/// Decision 0006 item 4's own example. `∀x ∃y (r(x,y) ∧ ¬(x = y))` has no
+/// model of size 1, because the only element is forced equal to itself, and
+/// has one of size 2.
+fn needs_two() -> FolProblem {
+ problem(
+ vec![Form::All(
+ 0,
+ Box::new(Form::Ex(
+ 1,
+ Box::new(and(op("r", v(0), v(1)), neg(Form::Eq(v(0), v(1))))),
+ )),
+ )],
+ None,
+ )
+}
+
+/// Unsatisfiable at every cardinality.
+fn contradiction() -> FolProblem {
+ problem(vec![cls("A", k("a")), neg(cls("A", k("a")))], None)
+}
+
+/// `A(a)` does not entail `B(a)`, so a countermodel exists at carrier 1.
+fn not_entailed() -> FolProblem {
+ problem(vec![cls("A", k("a"))], Some(cls("B", k("a"))))
+}
+
+// ── Environment ─────────────────────────────────────────────────────────────
+
+fn scratch(name: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!("oo-fol-verdict-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).expect("scratch dir");
+ d
+}
+
+fn missing() -> Option<String> {
+ if !Solver::Z3.available() {
+ return Some(format!("z3, the SMT solver; {}", Solver::Z3.install_line()));
+ }
+ find_checker(None).err()
+}
+
+/// G6. Loud, and fatal under `OO_REQUIRE_FIXTURES=1`.
+fn skip() -> bool {
+ match missing() {
+ None => false,
+ Some(why) => common::skip_unless(
+ false,
+ &why,
+ "the certifying pipeline needs both a model finder and the verified checker, and \
+ certifies nothing without them",
+ ),
+ }
+}
+
+fn opts(max_domain: u32) -> SolveOptions {
+ SolveOptions {
+ solver: Solver::Z3,
+ max_domain,
+ timeout_secs: 20,
+ unbounded_probe: false,
+ checker: None,
+ }
+}
+
+/// Write an executable stub and return its path. The stubs stand in for
+/// `oo-folmodel` on the branches a correct checker never reaches.
+fn stub(dir: &Path, name: &str, body: &str) -> PathBuf {
+ let p = dir.join(name);
+ std::fs::write(&p, body).expect("write stub");
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).expect("chmod");
+ }
+ p
+}
+
+// ── Rule 1: the certified word requires a zero exit from the checker ────────
+
+/// The positive control. Without it every test below would pass on a pipeline
+/// that never certified anything.
+#[test]
+fn a_checked_model_earns_the_certified_word() {
+ if skip() {
+ return;
+ }
+ let d = scratch("certified");
+ let o = solve(&easy(), &opts(4), &d).expect("the pipeline runs");
+ assert_eq!(o.verdict, "model_checked", "{o:?}");
+ assert_eq!(o.checker_exit, Some(0));
+ assert_eq!(o.solver_verdict, "sat");
+ assert_eq!(o.theorem.as_deref(), Some("Fol.satisfiable_of_check"));
+ assert!(o.disagreement.is_none());
+ assert!(o.skipped.is_none());
+ assert!(
+ o.checker_report
+ .as_deref()
+ .unwrap_or_default()
+ .contains("\"verdict\":\"model_checked\""),
+ "the checker's own report must say so too: {o:?}"
+ );
+ assert!(verdict_means("model_checked").contains("CERTIFIED"));
+ // The files a reader would need to reproduce the run by hand are all there.
+ for f in ["problem.tsv", "model.tsv", "checker.json"] {
+ assert!(d.join(f).is_file(), "missing {f}");
+ }
+}
+
+/// THE LAUNDERING GUARD. Three ways for the check not to have happened, and
+/// none of them may report the certified word.
+///
+/// A pipeline that fell back to `model_checked` when the checker was
+/// unavailable would print the certified word on every machine without Lean,
+/// which is the exact shape of the mistake this repository exists to catch.
+#[test]
+fn an_unchecked_result_never_reports_the_certified_word() {
+ if skip() {
+ return;
+ }
+ let d = scratch("unchecked");
+
+ // (a) A checker that REJECTS. The solver said sat, so the verdict is the
+ // oracle's word and never `rejected` as though the ontology were at fault
+ // (decision 0006 item 5), and the disagreement is STOP_THE_LINE.
+ let rejecting = stub(
+ &d,
+ "reject.sh",
+ "#!/bin/sh\necho '{\"verdict\":\"rejected\",\"theorem\":\"Fol.check_complete\"}'\nexit 1\n",
+ );
+ let mut o1 = opts(4);
+ o1.checker = Some(rejecting);
+ let r1 = solve(&easy(), &o1, &d.join("a")).expect("runs");
+ assert_ne!(r1.verdict, "model_checked", "{r1:?}");
+ assert_eq!(r1.verdict, "satisfiable_oracle");
+ assert_ne!(r1.verdict, "rejected");
+ assert_eq!(r1.checker_exit, Some(1));
+ assert!(r1.theorem.is_none(), "no theorem may be named: {r1:?}");
+ assert!(r1.owl_reading.is_none());
+ let dis = r1.disagreement.as_ref().expect("a disagreement");
+ assert_eq!(dis.severity, "STOP_THE_LINE");
+ assert_eq!(dis.what, "model_not_confirmed");
+ assert!(dis.means.contains("false clean"), "{}", dis.means);
+
+ // (b) A checker that cannot READ the file. Exit 2 is "unreadable", which
+ // is not a verdict in either direction, and it must not become one.
+ let unreadable = stub(
+ &d,
+ "unreadable.sh",
+ "#!/bin/sh\necho '{\"verdict\":\"unreadable\",\"reason\":\"stub\"}'\nexit 2\n",
+ );
+ let mut o2 = opts(4);
+ o2.checker = Some(unreadable);
+ let r2 = solve(&easy(), &o2, &d.join("b")).expect("runs");
+ assert_ne!(r2.verdict, "model_checked", "{r2:?}");
+ assert_eq!(r2.checker_exit, Some(2));
+ assert!(r2.disagreement.is_some());
+
+ // (c) NO checker at all. Loud, and still not certified.
+ let mut o3 = opts(4);
+ o3.checker = Some(PathBuf::from("/nonexistent/oo-folmodel"));
+ let r3 = solve(&easy(), &o3, &d.join("c")).expect("runs");
+ assert_ne!(r3.verdict, "model_checked", "{r3:?}");
+ assert_eq!(r3.checker_exit, None);
+ assert!(r3.skipped.is_some(), "a missing checker must be reported: {r3:?}");
+
+ // And a checker that ACCEPTS does reach it, so the branch is live and the
+ // three results above are about the exit code rather than about the stub.
+ let accepting = stub(
+ &d,
+ "accept.sh",
+ "#!/bin/sh\necho '{\"verdict\":\"model_checked\",\"goal_negated_present\":false}'\nexit 0\n",
+ );
+ let mut o4 = opts(4);
+ o4.checker = Some(accepting);
+ let r4 = solve(&easy(), &o4, &d.join("d")).expect("runs");
+ assert_eq!(r4.verdict, "model_checked");
+}
+
+// ── Rule 2: a bounded unsat is not unsatisfiability ─────────────────────────
+
+/// Decision 0006 item 4's own counterexample, run for real.
+///
+/// `∀x∃y (r(x,y) ∧ x≠y)` is unsat at carrier 1 and sat at carrier 2. A driver
+/// that mapped the first to `unsatisfiable_oracle` would be reporting a
+/// falsehood from correct solver output, and it would take ten minutes to
+/// write. The same problem produces two different verdicts here and the word
+/// `unsatisfiable_oracle` appears in neither.
+#[test]
+fn a_bounded_unsat_is_not_unsatisfiability() {
+ if skip() {
+ return;
+ }
+ let d = scratch("bounded");
+ let at_one = solve(&needs_two(), &opts(1), &d.join("k1")).expect("runs");
+ assert_eq!(at_one.solver_verdict, "unsat", "{at_one:?}");
+ assert_eq!(at_one.verdict, "no_model_up_to_size_k");
+ assert_ne!(at_one.verdict, "unsatisfiable_oracle");
+ assert_eq!(at_one.encoding, "finite(1)");
+ assert_eq!(at_one.unbounded, None, "no unbounded run happened");
+ assert!(at_one.bounded_search.contains("exhausted"), "{at_one:?}");
+ assert!(verdict_means(at_one.verdict).contains("NOT"));
+
+ let at_two = solve(&needs_two(), &opts(2), &d.join("k2")).expect("runs");
+ assert_eq!(at_two.verdict, "model_checked", "{at_two:?}");
+ assert_eq!(at_two.encoding, "finite(2)");
+ assert_eq!(at_two.cardinality_search, vec![1, 2]);
+}
+
+/// `unsatisfiable_oracle` is reachable ONLY through the unbounded probe.
+///
+/// The same genuinely unsatisfiable problem gives `no_model_up_to_size_k` with
+/// the probe off and `unsatisfiable_oracle` with it on, and the second is
+/// still an ORACLE's word: nothing checked a refutation and nothing here can.
+#[test]
+fn only_an_unbounded_run_can_say_unsatisfiable() {
+ if skip() {
+ return;
+ }
+ let d = scratch("unsat");
+ let bounded = solve(&contradiction(), &opts(3), &d.join("bounded")).expect("runs");
+ assert_eq!(bounded.verdict, "no_model_up_to_size_k", "{bounded:?}");
+ assert_eq!(bounded.unbounded, None);
+
+ let mut probing = opts(3);
+ probing.unbounded_probe = true;
+ let probed = solve(&contradiction(), &probing, &d.join("probed")).expect("runs");
+ assert_eq!(probed.verdict, "unsatisfiable_oracle", "{probed:?}");
+ assert_eq!(probed.unbounded, Some("unsat"));
+ assert_eq!(probed.encoding, "unbounded");
+ assert_eq!(probed.checker_exit, None, "nothing was checked");
+ assert!(probed.theorem.is_none(), "no theorem may be named: {probed:?}");
+ assert!(verdict_means("unsatisfiable_oracle").contains("oracle opinion"));
+ // The bounded ladder's own finding survives beside it rather than being
+ // erased by the probe.
+ assert!(probed.bounded_search.contains("exhausted"), "{probed:?}");
+}
+
+// ── Rule 3: the OWL reading comes off the checker's own report ──────────────
+
+/// A checked countermodel to a negated goal carries the OWL-level word, and a
+/// run with no goal does not, even when it is certified.
+///
+/// The word is long on purpose. The OWL sentence rides on `OwlLean.adequacy`
+/// in a sibling project AND on the Rust-to-Lean correspondence that decision
+/// 0005 item 2 states is pinned by tests and NOT proved, so it must never be
+/// shortened to "not entailed".
+#[test]
+fn the_owl_reading_is_read_off_the_checkers_own_report() {
+ if skip() {
+ return;
+ }
+ let d = scratch("owl");
+ let withgoal = solve(&not_entailed(), &opts(3), &d.join("goal")).expect("runs");
+ assert_eq!(withgoal.verdict, "model_checked", "{withgoal:?}");
+ assert_eq!(
+ withgoal.owl_reading,
+ Some("not_entailed_under_unproved_translation")
+ );
+ assert!(
+ withgoal
+ .checker_report
+ .as_deref()
+ .unwrap_or_default()
+ .contains("\"goal_negated_present\":true"),
+ "the CHECKER must be the one reporting the goal: {withgoal:?}"
+ );
+
+ let nogoal = solve(&easy(), &opts(3), &d.join("nogoal")).expect("runs");
+ assert_eq!(nogoal.verdict, "model_checked");
+ assert!(nogoal.owl_reading.is_none(), "{nogoal:?}");
+
+ // A checker that reports a goal but does NOT accept gets no OWL reading
+ // either: the rule is a conjunction, and this is the half a report that
+ // read only its own intention would get wrong.
+ let lying = stub(
+ &d,
+ "goal_but_reject.sh",
+ "#!/bin/sh\necho '{\"verdict\":\"rejected\",\"goal_negated_present\":true}'\nexit 1\n",
+ );
+ let mut o = opts(3);
+ o.checker = Some(lying);
+ let r = solve(&not_entailed(), &o, &d.join("lying")).expect("runs");
+ assert!(r.owl_reading.is_none(), "{r:?}");
+
+ // THE HALF THAT MAKES THE RULE BITE. The problem HAS a conjecture and the
+ // checker ACCEPTS, but the checker reports that the file it read carried
+ // no negated goal. The checker is the authority on that, because it is the
+ // one that parsed `problem.tsv`; a report computed from this side's
+ // `conjecture.is_some()` would claim a non-entailment over a file whose
+ // goal never reached the checker, which is a writer bug reported as a
+ // result about the ontology.
+ //
+ // Without this case the rule is untestable: on every honest run the two
+ // sources agree, so swapping one for the other changes nothing and the
+ // gate would be decoration.
+ let silent = stub(
+ &d,
+ "accept_no_goal.sh",
+ "#!/bin/sh\necho '{\"verdict\":\"model_checked\",\"goal_negated_present\":false}'\nexit 0\n",
+ );
+ let mut o2 = opts(3);
+ o2.checker = Some(silent);
+ let r2 = solve(&not_entailed(), &o2, &d.join("silent")).expect("runs");
+ assert_eq!(r2.verdict, "model_checked", "{r2:?}");
+ assert!(
+ r2.owl_reading.is_none(),
+ "the CHECKER said the file carried no goal, so no OWL reading may be claimed \
+ however much this side intended one: {r2:?}"
+ );
+}
+
+// ── The five words, and the fields that are never collapsed ─────────────────
+
+/// Every word a verdict can take has a sentence, and the sentences say what
+/// rests on a theorem and what does not.
+#[test]
+fn every_verdict_word_says_what_it_rests_on() {
+ assert!(verdict_means("model_checked").contains("Fol.satisfiable_of_check"));
+ assert!(verdict_means("satisfiable_oracle").contains("nothing here checked it"));
+ assert!(verdict_means("no_model_up_to_size_k").contains("finite model property"));
+ assert!(verdict_means("unsatisfiable_oracle").contains("decision 0005"));
+ assert!(verdict_means("unknown_oracle").contains("Not evidence"));
+ // The four oracle words must not claim a theorem.
+ for w in [
+ "satisfiable_oracle",
+ "no_model_up_to_size_k",
+ "unsatisfiable_oracle",
+ "unknown_oracle",
+ ] {
+ assert!(!verdict_means(w).contains("CERTIFIED"), "{w} claims certification");
+ }
+}
+
+/// The five fields decision 0006 fixes are all present and independently
+/// readable on a real run, so a report cannot quietly drop one.
+#[test]
+fn the_five_fields_are_all_reported() {
+ if skip() {
+ return;
+ }
+ let o = solve(&not_entailed(), &opts(3), &scratch("fields")).expect("runs");
+ let j = open_ontologies::fol_solve::outcome_json(&o);
+ for field in [
+ "solver_verdict",
+ "encoding",
+ "checker_exit",
+ "verdict",
+ "owl_reading",
+ ] {
+ assert!(j.get(field).is_some(), "missing {field} in {j}");
+ }
+ assert_eq!(j["solver_verdict"], "sat");
+ assert_eq!(j["encoding"], "finite(1)");
+ assert_eq!(j["checker_exit"], 0);
+ assert_eq!(j["verdict"], "model_checked");
+ assert_eq!(j["owl_reading"], "not_entailed_under_unproved_translation");
+ assert_eq!(j["problem_digest"], o.problem_digest);
+ assert_eq!(j["disagreement"], serde_json::Value::Null);
+}
+
+// ── G6: loud skips ──────────────────────────────────────────────────────────
+
+/// A missing checker is REPORTED, not worked around.
+///
+/// A pipeline that silently dropped to an oracle verdict because Lean was not
+/// built would make every run look like a solver limitation, which is
+/// mis-attribution of exactly the kind this repository keeps finding in other
+/// people's work.
+#[test]
+fn a_missing_checker_is_loud() {
+ let e = find_checker(Some(Path::new("/nonexistent/oo-folmodel"))).expect_err("must fail");
+ assert!(e.contains("/nonexistent/oo-folmodel"), "{e}");
+ // The default search names the build line rather than shrugging.
+ if let Err(why) = find_checker(None) {
+ assert!(why.contains("lake build"), "{why}");
+ assert!(why.contains("OO_FOLMODEL"), "{why}");
+ }
+}
+
+/// A missing SOLVER skips loudly with the install line, run for real through
+/// the CLI with an empty `PATH` so that nothing on this machine can be found.
+///
+/// Driven as a subprocess rather than in-process because `PATH` is global to
+/// a process and the rest of this binary's tests need the real one.
+#[test]
+fn a_missing_solver_is_loud() {
+ let bin = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("target")
+ .join("debug")
+ .join("open-ontologies");
+ if common::skip_unless(
+ bin.is_file(),
+ "the debug CLI binary",
+ "run `cargo build` first; this test drives the real command",
+ ) {
+ return;
+ }
+ let d = scratch("nopath");
+ let out = Command::new(&bin)
+ .arg("--no-connect")
+ .arg("--data-dir")
+ .arg(d.join("store"))
+ .arg("batch")
+ .arg("-")
+ .env("PATH", "")
+ .env("OPEN_ONTOLOGIES_STORAGE_MODE", "persistent")
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn()
+ .and_then(|mut c| {
+ use std::io::Write as _;
+ let script = format!(
+ "load {}\nfol-model --out {} --solver z3 --max-domain 2\n",
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("tests/data/sample.ttl")
+ .display(),
+ d.join("solve").display()
+ );
+ c.stdin.as_mut().expect("stdin").write_all(script.as_bytes())?;
+ c.wait_with_output()
+ })
+ .expect("run the CLI");
+ let err = String::from_utf8_lossy(&out.stderr);
+ let so = String::from_utf8_lossy(&out.stdout);
+ assert!(
+ err.contains("SKIPPED_SOLVER") || err.contains("SKIPPED_CHECKER"),
+ "a missing solver must print the marker on stderr.\nstderr: {err}\nstdout: {so}"
+ );
+ assert!(
+ err.contains("brew install") || err.contains("lake build"),
+ "and the install line: {err}"
+ );
+ assert!(
+ !so.contains("\"verdict\":\"model_checked\""),
+ "nothing may be certified with no solver on PATH: {so}"
+ );
+}
+
+/// A LYING SOLVER, end to end, through the real command.
+///
+/// This is the case the whole layer exists for, and a stub checker cannot
+/// stand in for it: a model finder that answers `sat` and hands back a
+/// structure that is not a model. The fake `z3` here returns a complete,
+/// well-formed, correctly typed interpretation of every symbol
+/// `tests/data/sample.ttl` exports, over a carrier of one, in which `thing` is
+/// empty. That fails `background_2` (`∃x thing(x)`) and every `ind_typing`
+/// axiom, and no amount of reading the file would tell you so — only running
+/// the verified checker does.
+///
+/// What must happen, and all four are asserted:
+///
+/// * the verdict is `satisfiable_oracle`, because the solver said `sat` and
+/// that is a claim about the ontology this pipeline did not verify. It is
+/// NOT `rejected`, which would blame the ontology, and NOT `model_checked`;
+/// * a `disagreement` block with `severity: STOP_THE_LINE`;
+/// * the run summary counts it;
+/// * THE COMMAND EXITS NON-ZERO, in batch mode, which is the mode every tool
+/// in `tools/` uses. A pipeline in which the check never has to pass is not
+/// a pipeline with a check in it.
+#[test]
+fn a_lying_solver_stops_the_line_and_fails_the_command() {
+ if skip() {
+ return;
+ }
+ let bin = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target/debug/open-ontologies");
+ if common::skip_unless(
+ bin.is_file(),
+ "the debug CLI binary",
+ "run `cargo build` first; this test drives the real command",
+ ) {
+ return;
+ }
+ let d = scratch("lying");
+ let fake = d.join("bin");
+ std::fs::create_dir_all(&fake).expect("bin dir");
+ let ns = "http://example.org/test#";
+ let body = format!(
+ "#!/bin/sh\n echo sat\n cat <<'EOF'\n (\n (define-fun |c:{ns}Organization| ((x!0 U)) Bool true)\n (define-fun |c:{ns}Person| ((x!0 U)) Bool true)\n (define-fun lit ((x!0 U)) Bool false)\n (define-fun thing ((x!0 U)) Bool false)\n (define-fun |op:{ns}relationship| ((x!0 U) (x!1 U)) Bool true)\n (define-fun |op:{ns}worksFor| ((x!0 U) (x!1 U)) Bool true)\n (define-fun |i:{ns}AcmeCorp| () U e0)\n (define-fun |i:{ns}Alice| () U e0)\n )\n EOF\n"
+ );
+ stub(&fake, "z3", &body);
+
+ let script = format!(
+ "load {}\nfol-model --out {} --solver z3 --max-domain 1 --unbounded-probe false\n",
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("tests/data/sample.ttl")
+ .display(),
+ d.join("solve").display()
+ );
+ let out = Command::new(&bin)
+ .arg("--no-connect")
+ .arg("--data-dir")
+ .arg(d.join("store"))
+ .arg("batch")
+ .arg("-")
+ .env("PATH", format!("{}:{}", fake.display(), std::env::var("PATH").unwrap_or_default()))
+ .env("OPEN_ONTOLOGIES_STORAGE_MODE", "persistent")
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn()
+ .and_then(|mut c| {
+ use std::io::Write as _;
+ c.stdin.as_mut().expect("stdin").write_all(script.as_bytes())?;
+ c.wait_with_output()
+ })
+ .expect("run the CLI");
+ let so = String::from_utf8_lossy(&out.stdout);
+ let line = so
+ .lines()
+ .find(|l| l.contains("\"command\":\"fol-model\""))
+ .unwrap_or_else(|| panic!("no fol-model result in {so}"));
+ let v: serde_json::Value = serde_json::from_str(line).expect("json");
+ let r = &v["result"];
+ let o = &r["ontology"];
+ assert_eq!(o["solver_verdict"], "sat", "{r}");
+ assert_eq!(o["verdict"], "satisfiable_oracle", "{r}");
+ assert_ne!(o["verdict"], "model_checked", "{r}");
+ assert_ne!(o["verdict"], "rejected", "the ontology is not at fault: {r}");
+ assert_eq!(o["checker_exit"], 1, "{r}");
+ assert_eq!(o["theorem"], serde_json::Value::Null, "{r}");
+ assert_eq!(o["disagreement"]["severity"], "STOP_THE_LINE", "{r}");
+ assert_eq!(o["disagreement"]["what"], "model_not_confirmed", "{r}");
+ assert_eq!(r["stop_the_line"], 1, "{r}");
+ assert_eq!(
+ out.status.code(),
+ Some(1),
+ "a stop-the-line must FAIL the command, in batch mode, which is the mode \
+ tools/ uses. stdout: {so}"
+ );
+}
+
+/// The two finders differ in what they can be asked, and the difference is
+/// data rather than prose because the verdict rules read it.
+#[test]
+fn the_two_finders_declare_their_own_limits() {
+ // Mace4's minimum carrier is 2: `mace4 -n 1` is a FATAL error, measured on
+ // LADR 2009-11A (`parm start_size, value 1 out of range [2..2147483647]`).
+ assert_eq!(Solver::Mace4.min_domain(), 2);
+ assert_eq!(Solver::Z3.min_domain(), 1);
+ // And Mace4 has no unbounded question at all, so it can never produce
+ // `unsatisfiable_oracle`.
+ assert!(!Solver::Mace4.can_probe_unbounded());
+ assert!(Solver::Z3.can_probe_unbounded());
+ assert!(Solver::parse("mace4").is_ok());
+ assert!(Solver::parse("z3").is_ok());
+ assert!(Solver::parse("eprover").is_err(), "E is a prover, not a model finder");
+ for s in [Solver::Z3, Solver::Mace4] {
+ assert!(s.install_line().contains("install"));
+ }
+}
+
+/// Mace4 reaches the certified word too, and its reduct is visible.
+///
+/// Mace4 clausifies and Skolemises, so the structure it prints interprets
+/// names the translation never emitted. Dropping them is taking the reduct and
+/// needs no lemma, because the checker re-evaluates formulas that cannot
+/// mention them. What it does need is to be VISIBLE.
+#[test]
+fn mace4_also_earns_the_certified_word_and_names_its_reduct() {
+ if common::skip_unless(
+ Solver::Mace4.available() && find_checker(None).is_ok(),
+ "mace4 and the verified checker",
+ Solver::Mace4.install_line(),
+ ) {
+ return;
+ }
+ let d = scratch("mace4");
+ let mut o = opts(4);
+ o.solver = Solver::Mace4;
+ // A top-level existential, which Mace4 Skolemises into a constant of its
+ // own choosing.
+ let p = problem(
+ vec![
+ Form::Ex(0, Box::new(cls("A", v(0)))),
+ cls("A", k("a")),
+ ],
+ None,
+ );
+ let r: Outcome = solve(&p, &o, &d).expect("runs");
+ assert_eq!(r.verdict, "model_checked", "{r:?}");
+ assert_eq!(r.checker_exit, Some(0));
+ // The ladder starts at 2, not 1.
+ assert_eq!(r.cardinality_search.first(), Some(&2));
+ assert!(
+ !r.dropped_symbols.is_empty(),
+ "Mace4's Skolem constant must be reported as the reduct: {r:?}"
+ );
+ assert!(
+ r.checker_report.as_deref().unwrap_or_default().contains("\"source\":\"mace4\""),
+ "{r:?}"
+ );
+}
diff --git a/tests/fol_translation_correspondence_test.rs b/tests/fol_translation_correspondence_test.rs
index be1c9232..36513ae4 100644
--- a/tests/fol_translation_correspondence_test.rs
+++ b/tests/fol_translation_correspondence_test.rs
@@ -1025,6 +1025,79 @@ fn an_ontology_inside_the_fragment_does_not_set_the_flag() {
assert_eq!(v["individual_typing_axioms"], 1);
}
+/// **A punned assertion weakens the export, and the report says so.**
+///
+/// OWL 2 DL lets one IRI be a class and an individual at once.
+/// `OwlLean/Syntax.lean` does not: `Sig` gives each entity kind its own type
+/// and `Sig.Ind` is disjoint from `Sig.Cls`. So an assertion whose subject is
+/// declared a class is outside the fragment and is not exported — while its
+/// subsumptions, domains and ranges ARE, which is exactly why the omission was
+/// invisible.
+///
+/// It WAS invisible. Running the model-certificate pipeline over
+/// `case-studies/blast-furnace-ironmaking/` returned machine-checked
+/// countermodels for five of the nine triples the OWL-RL reasoner derives
+/// there: `bf:Hanging` is declared `owl:Class` and also carries
+/// `bf:hasSeverity bf:HighSeverity`, `bf:hasSeverity` has domain
+/// `bf:ProcessState`, and `rdfs2` is what the reasoner used. The exported
+/// theory really did not entail the conclusion, and the report said
+/// `exports_a_weaker_axiom_set: false`. That is the laundering shape this
+/// project keeps finding in other people's work, in its own output.
+#[test]
+fn a_punned_assertion_is_named_as_weakening_the_export() {
+ let ttl = r#"
+@prefix : <http://e/> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+:State a owl:Class .
+:Hanging a owl:Class ; rdfs:subClassOf :State ; :hasSeverity :High .
+:High a owl:Class .
+:hasSeverity a owl:ObjectProperty ; rdfs:domain :State .
+"#;
+ let graph = std::sync::Arc::new(open_ontologies::graph::GraphStore::new());
+ graph.load_turtle(ttl, None).expect("turtle parses");
+ let dir = tempfile::tempdir().expect("tempdir");
+ let report = open_ontologies::tptp::export(&graph, dir.path(), Syntax::Tptp, None, 0)
+ .expect("export");
+ let v: serde_json::Value = serde_json::from_str(&report).expect("json");
+ assert_eq!(
+ v["exports_a_weaker_axiom_set"], true,
+ "the punned assertion is not exported, so the axiom set IS weaker; got {}",
+ v["constructs_not_exported"]
+ );
+ let named: Vec<String> = v["constructs_not_exported"]
+ .as_array()
+ .expect("array")
+ .iter()
+ .map(|d| d["construct"].as_str().unwrap_or("").to_string())
+ .collect();
+ assert!(
+ named.iter().any(|n| n == "assertion on a punned entity"),
+ "got {named:?}"
+ );
+ let entry = v["constructs_not_exported"]
+ .as_array()
+ .expect("array")
+ .iter()
+ .find(|d| d["construct"] == "assertion on a punned entity")
+ .expect("the entry");
+ assert_eq!(entry["occurrences"], 1, "one assertion, on :Hanging");
+ let why = entry["why"].as_str().unwrap_or("");
+ assert!(why.contains("Sig.Ind"), "the reason must name the Lean: {why}");
+ assert!(
+ why.contains("WEAKER than the graph"),
+ "and say what it costs: {why}"
+ );
+ // The subsumption on the SAME subject is still exported, which is why the
+ // omission was invisible: the file looks complete.
+ let text = std::fs::read_to_string(dir.path().join("ontology.p")).expect("read");
+ assert!(text.contains("subClassOf"), "{text}");
+ assert!(
+ !text.contains("op:http://e/hasSeverity'(\'i:http://e/Hanging"),
+ "the assertion itself is not there"
+ );
+}
+
/// The COLORE dialect is a different SPELLING of the same text, not a
/// different translation.
///
@@ -1075,21 +1148,29 @@ fn the_colore_dialect_changes_the_spelling_and_nothing_else() {
/// that names the alternatives, rather than silently defaulting.
#[test]
fn an_unknown_syntax_or_dialect_is_refused() {
- assert!(Syntax::parse("smtlib", None, None).is_err());
+ // `smtlib` and `ladr` joined `tptp` and `clif` when the model-finding half
+ // arrived; `sexpr` never existed and still does not.
+ let e = Syntax::parse("sexpr", None, None, None).expect_err("sexpr is not a syntax");
+ assert!(
+ ["tptp", "clif", "smtlib", "ladr"].iter().all(|n| e.to_string().contains(n)),
+ "the message must name every alternative: {e}"
+ );
+ assert!(Syntax::parse("smtlib", None, None, None).is_ok());
+ assert!(Syntax::parse("ladr", None, None, None).is_ok());
let e =
- Syntax::parse("clif", Some("kif"), None).expect_err("kif is not a CLIF dialect");
+ Syntax::parse("clif", Some("kif"), None, None).expect_err("kif is not a CLIF dialect");
assert!(
e.to_string().contains("iso") && e.to_string().contains("colore"),
"got {e}"
);
- let e = Syntax::parse("clif", None, Some("inline"))
+ let e = Syntax::parse("clif", None, Some("inline"), None)
.expect_err("inline is not a comment placement");
assert!(
e.to_string().contains("standalone") && e.to_string().contains("wrapped"),
"got {e}"
);
// The defaults, and the alternatives.
- let d = Syntax::parse("clif", None, None).unwrap();
+ let d = Syntax::parse("clif", None, None, None).unwrap();
assert_eq!(d.dialect(), Some(ClifDialect::Iso));
assert_eq!(
d.comments(),
@@ -1098,12 +1179,12 @@ fn an_unknown_syntax_or_dialect_is_refused() {
available parser recovers sentences from"
);
assert_eq!(
- Syntax::parse("clif", Some("colore"), Some("wrapped"))
+ Syntax::parse("clif", Some("colore"), Some("wrapped"), None)
.unwrap()
.comments(),
Some(ClifComments::Wrapped)
);
- assert_eq!(Syntax::parse("tptp", None, None).unwrap().dialect(), None);
+ assert_eq!(Syntax::parse("tptp", None, None, None).unwrap().dialect(), None);
}
/// **Gate.** The default CLIF shape is the one a parser can recover sentences
diff --git a/tests/lean_fol_model_test.rs b/tests/lean_fol_model_test.rs
new file mode 100644
index 00000000..fd10fbf0
--- /dev/null
+++ b/tests/lean_fol_model_test.rs
@@ -0,0 +1,460 @@
+//! `oo-folmodel` end to end: the shipped fixtures, and the engine's own output.
+//!
+//! `lean/Fol/` carries the theorem. `Fol.satisfiable_of_check` says an
+//! accepted structure really is a model, so the problem it was checked against
+//! really is satisfiable, and `Fol.not_entails_of_check` turns a checked model
+//! of `¬φ :: Γ` into a machine-checked NON-ENTAILMENT — the one sentence no
+//! theorem prover can produce, because a prover answering "not a theorem" is
+//! reporting a failed search at best.
+//!
+//! Until this file existed the Lean side had never been run against anything
+//! the Rust side emitted. Decision 0006 recorded that gap in its own "Still
+//! not done": *nothing has been emitted by the engine and checked end to end*.
+//! These tests close it, in three groups:
+//!
+//! 1. **The shipped fixtures**, with the exit codes measured when they were
+//! written. Ten pairs, four of them G3 forgeries at the FILE level.
+//! 2. **The engine's own output**, from a real ontology fixture through the
+//! exporter, the SMT-LIB printer, Z3, the ingestion and back into the
+//! checker.
+//! 3. **Forging the engine's output**, one bit at a time, so that the
+//! acceptance in group 2 is shown to be a decision rather than a habit.
+//!
+//! The checker needs a Lean toolchain (`lake`) and the `oo-folmodel` target,
+//! which `lean/lakefile.toml` carries in `defaultTargets` so a bare
+//! `lake build` compiles it. Without them these tests SKIP LOUDLY through
+//! `common::skip_unless`; the CI job that installs Lean runs them with
+//! `OO_REQUIRE_FIXTURES=1`, which turns that skip into a failure.
+
+mod common;
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+use std::sync::OnceLock;
+
+use open_ontologies::fol_model::z3;
+use open_ontologies::fol_solve::{Solver, find_checker};
+use open_ontologies::tptp::{Concept, FolProblem, OwlAxiom, smtlib::SmtEncoding};
+
+fn repo() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+}
+
+fn lean_dir() -> PathBuf {
+ std::env::var("OO_LEAN_DIR")
+ .map(PathBuf::from)
+ .unwrap_or_else(|_| repo().join("lean"))
+}
+
+fn fixture(name: &str) -> PathBuf {
+ repo().join("tests/fixtures/folmodel").join(name)
+}
+
+fn lake_available() -> bool {
+ // `.current_dir(lean_dir())` is not cosmetic: elan resolves the toolchain
+ // from the working directory's `lean-toolchain`, and the crate root has
+ // none in its ancestry. The same probe as `tests/dl_model_certificate_test.rs`.
+ Command::new("lake")
+ .arg("--version")
+ .current_dir(lean_dir())
+ .output()
+ .map(|o| o.status.success())
+ .unwrap_or(false)
+}
+
+/// Build once per test binary. The PROOFS are part of the build, so a failure
+/// here is a failure and never a skip.
+fn build() -> &'static Result<PathBuf, String> {
+ static BUILT: OnceLock<Result<PathBuf, String>> = OnceLock::new();
+ BUILT.get_or_init(|| {
+ if !lake_available() {
+ return Err("lake (the Lean 4 build tool); install elan from \
+ https://github.com/leanprover/elan, and lean/lean-toolchain pins the \
+ version"
+ .to_string());
+ }
+ let out = Command::new("lake")
+ .arg("build")
+ .arg("oo-folmodel")
+ .current_dir(lean_dir())
+ .output()
+ .expect("run lake build oo-folmodel");
+ let text = format!(
+ "{}{}",
+ String::from_utf8_lossy(&out.stdout),
+ String::from_utf8_lossy(&out.stderr)
+ );
+ if !out.status.success() {
+ if text.contains("unknown target") || text.contains("no such target") {
+ return Err(format!(
+ "the `oo-folmodel` target in lean/lakefile.toml, which must also be in \
+ defaultTargets so the CI job's bare `lake build` compiles these proofs. \
+ lake said: {text}"
+ ));
+ }
+ panic!("lake build oo-folmodel failed:\n{text}");
+ }
+ let exe = lean_dir().join(".lake/build/bin/oo-folmodel");
+ if !exe.exists() {
+ panic!("checker binary missing at {}", exe.display());
+ }
+ Ok(exe)
+ })
+}
+
+fn skip() -> bool {
+ match build() {
+ Ok(_) => false,
+ Err(why) => common::skip_unless(
+ false,
+ why,
+ "the model-certificate tests check nothing without the verified checker",
+ ),
+ }
+}
+
+fn checker() -> &'static Path {
+ build().as_ref().expect("checked by skip()").as_path()
+}
+
+/// Returns (exit code, stdout).
+fn check(problem: &Path, model: &Path) -> (i32, String) {
+ let out = Command::new(checker())
+ .arg(problem)
+ .arg(model)
+ .output()
+ .expect("run oo-folmodel");
+ (
+ out.status.code().unwrap_or(-1),
+ String::from_utf8_lossy(&out.stdout).trim().to_string(),
+ )
+}
+
+fn field<'a>(json: &'a str, key: &str) -> &'a str {
+ let pat = format!("\"{key}\":\"");
+ match json.find(&pat) {
+ Some(i) => {
+ let rest = &json[i + pat.len()..];
+ &rest[..rest.find('"').expect("unterminated")]
+ }
+ None => "",
+ }
+}
+
+fn scratch(name: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!("oo-leanfol-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).expect("scratch");
+ d
+}
+
+// ── 1. The shipped fixtures ─────────────────────────────────────────────────
+
+/// The worked example of `lean/Fol/Syntax.lean`, accepted, naming both
+/// theorems because the problem carries a `goal_negated` line.
+#[test]
+fn the_worked_example_is_accepted() {
+ if skip() {
+ return;
+ }
+ let (code, out) = check(&fixture("problem.tsv"), &fixture("model.tsv"));
+ assert_eq!(code, 0, "{out}");
+ assert_eq!(field(&out, "verdict"), "model_checked", "{out}");
+ assert_eq!(field(&out, "theorem"), "Fol.satisfiable_of_check", "{out}");
+ assert_eq!(
+ field(&out, "non_entailment_theorem"),
+ "Fol.not_entails_of_check",
+ "the non-entailment is the sentence this layer exists for: {out}"
+ );
+ assert_eq!(field(&out, "problem_digest"), "4403d8aaa0c422f7", "{out}");
+ assert!(out.contains("\"goal_negated_present\":true"), "{out}");
+ assert!(out.contains("\"closed\":true"), "{out}");
+}
+
+/// G3, at the file level. Every way of lying, each on its own fixture, each
+/// with the exit code measured when the fixture was written.
+///
+/// The three exit codes are not interchangeable. `1` is a REJECTION, which by
+/// `Fol.check_complete` is a statement about the structure and not about the
+/// checker giving up. `2` is UNREADABLE, which is not a verdict in either
+/// direction. `0` is the certificate.
+#[test]
+fn every_forgery_is_rejected() {
+ if skip() {
+ return;
+ }
+ // Rejections: the structure, or the file's claim about which problem it is
+ // for, is wrong.
+ let rejected: &[(&str, &str, &str)] = &[
+ (
+ "model_no_edge.tsv",
+ "",
+ "the worksFor edge the subClassOf axiom requires was deleted",
+ ),
+ (
+ "model_undeclared.tsv",
+ "undeclared_symbol",
+ "the model does not interpret a symbol the problem uses",
+ ),
+ (
+ "model_wrong_digest.tsv",
+ "problem_digest_mismatch",
+ "the model claims to be for a different problem",
+ ),
+ ];
+ for (name, reason, why) in rejected {
+ let (code, out) = check(&fixture("problem.tsv"), &fixture(name));
+ assert_eq!(code, 1, "{name} must be REJECTED because {why}: {out}");
+ assert_eq!(field(&out, "verdict"), "rejected", "{out}");
+ if !reason.is_empty() {
+ assert_eq!(field(&out, "reason"), *reason, "{out}");
+ }
+ }
+
+ // Unreadable: the file does not describe a structure at all.
+ let unreadable: &[(&str, &str)] = &[
+ ("model_empty_domain.tsv", "a first-order structure cannot have an empty carrier"),
+ ("model_bad_arity.tsv", "a binary row for a symbol declared unary"),
+ ("model_index_out_of_range.tsv", "an index outside the declared carrier"),
+ ("model_missing_row.tsv", "a declared binary symbol with a missing row"),
+ ];
+ for (name, why) in unreadable {
+ let (code, out) = check(&fixture("problem.tsv"), &fixture(name));
+ assert_eq!(code, 2, "{name} must be UNREADABLE because {why}: {out}");
+ assert_eq!(field(&out, "verdict"), "unreadable", "{out}");
+ }
+}
+
+/// The coverage gate says ATTRIBUTION in machine-readable form, so a report
+/// cannot quietly promote it into a soundness failure.
+///
+/// Soundness holds without it: `FinModel`'s three fields are total, an
+/// undeclared symbol is still interpreted, and `check` validates the resulting
+/// structure from scratch. What the gate buys is that the structure certified
+/// is the structure the solver described rather than the solver's completed
+/// with defaults.
+#[test]
+fn the_coverage_gate_is_labelled_attribution() {
+ if skip() {
+ return;
+ }
+ let (code, out) = check(&fixture("problem.tsv"), &fixture("model_undeclared.tsv"));
+ assert_eq!(code, 1, "{out}");
+ assert_eq!(field(&out, "gate"), "attribution", "{out}");
+ assert!(!field(&out, "symbol").is_empty(), "it must name the symbol: {out}");
+ assert!(!field(&out, "arity").is_empty(), "and its arity: {out}");
+}
+
+/// G3.5: a perfectly good structure checked against a problem it was not built
+/// for. The digest is what catches it, and the rejection says so.
+#[test]
+fn a_model_of_another_problem_is_rejected() {
+ if skip() {
+ return;
+ }
+ let (code, out) = check(&fixture("problem_other.tsv"), &fixture("model.tsv"));
+ assert_eq!(code, 1, "{out}");
+ assert_eq!(field(&out, "reason"), "problem_digest_mismatch", "{out}");
+ assert_eq!(field(&out, "found"), "4403d8aaa0c422f7", "{out}");
+ assert_ne!(field(&out, "expected"), field(&out, "found"), "{out}");
+}
+
+/// An EMPTY problem is exit 2 and never a certificate.
+///
+/// Every structure satisfies the empty formula list, so a certificate over one
+/// would report `model_checked` and say nothing. An exporter bug that dropped
+/// every formula would otherwise produce a clean green run, which is the exact
+/// shape decision 0005 item 7 records happening inside this repository already.
+#[test]
+fn an_empty_problem_is_unreadable_and_never_certified() {
+ if skip() {
+ return;
+ }
+ let (code, out) = check(&fixture("problem_empty.tsv"), &fixture("model.tsv"));
+ assert_eq!(code, 2, "{out}");
+ assert_ne!(field(&out, "verdict"), "model_checked", "{out}");
+ assert_eq!(field(&out, "verdict"), "unreadable", "{out}");
+}
+
+/// A file that cannot be opened is exit 2, not a rejection. "I could not read
+/// the file" and "this is not a model" are different answers.
+#[test]
+fn an_unreadable_file_is_exit_two_not_a_rejection() {
+ if skip() {
+ return;
+ }
+ let (code, _) = check(Path::new("/nonexistent/p.tsv"), Path::new("/nonexistent/m.tsv"));
+ assert_eq!(code, 2);
+}
+
+// ── 2. The engine's own output ──────────────────────────────────────────────
+
+/// The whole chain, for real: the exporter builds the problem, the SMT-LIB
+/// printer writes it, Z3 solves it, the ingestion reads the structure back,
+/// and the VERIFIED CHECKER accepts it against the problem the exporter also
+/// wrote in its own format.
+///
+/// This is the end-to-end run decision 0006 recorded as missing. Everything
+/// before it had been measured against files written by hand.
+#[test]
+fn the_engines_own_export_is_solved_and_checked() {
+ if skip() {
+ return;
+ }
+ if common::skip_unless(Solver::Z3.available(), "z3", Solver::Z3.install_line()) {
+ return;
+ }
+ let d = scratch("engine");
+
+ // `A(a)` does not entail `B(a)`, so a countermodel exists and the run
+ // should reach the non-entailment theorem.
+ let axioms = vec![OwlAxiom::ClassAssert(
+ Concept::Atom("http://e/A".into()),
+ "http://e/a".into(),
+ )];
+ let goal = OwlAxiom::ClassAssert(Concept::Atom("http://e/B".into()), "http://e/a".into());
+ let p = FolProblem::build(&axioms, Some(&goal)).expect("freshness holds");
+
+ let (tsv, digest) = p.to_problem_tsv().expect("writable");
+ let problem_path = d.join("problem.tsv");
+ std::fs::write(&problem_path, &tsv).expect("write");
+
+ let smt = p.to_smtlib(SmtEncoding::Finite(2)).expect("writable");
+ let smt_path = d.join("problem.smt2");
+ std::fs::write(&smt_path, smt).expect("write");
+
+ let out = Command::new("z3").arg(&smt_path).output().expect("run z3");
+ let text = String::from_utf8_lossy(&out.stdout).to_string();
+ assert!(text.starts_with("sat"), "z3 must find a countermodel: {text}");
+
+ let model = z3::parse_model(&text, &p.vocabulary(), 2).expect("a readable model");
+ let model_path = d.join("model.tsv");
+ std::fs::write(&model_path, model.to_model_tsv(&digest, &[1, 2])).expect("write");
+
+ let (code, report) = check(&problem_path, &model_path);
+ assert_eq!(code, 0, "the checker must accept the engine's own model: {report}");
+ assert_eq!(field(&report, "verdict"), "model_checked", "{report}");
+ assert_eq!(
+ field(&report, "non_entailment_theorem"),
+ "Fol.not_entails_of_check",
+ "{report}"
+ );
+ // The digest the Rust computed is the digest the Lean recomputed, which is
+ // the whole point of specifying FNV-1a rather than using a library.
+ assert_eq!(field(&report, "problem_digest"), digest, "{report}");
+ // Every formula the exporter wrote reached the checker.
+ assert!(
+ report.contains(&format!("\"formulas\":{}", tsv.lines().count())),
+ "{report}"
+ );
+ assert!(report.contains("\"source\":\"z3\""), "{report}");
+}
+
+// ── 3. Forging the engine's output ──────────────────────────────────────────
+
+/// The acceptance above is a DECISION, not a habit: one bit of the model the
+/// engine wrote, flipped, and the same checker says no.
+///
+/// Three edits, three different failures. A flipped truth value is a
+/// rejection; a deleted declaration is unreadable; a digest of one character
+/// different is a rejection naming the mismatch.
+#[test]
+fn one_edit_to_the_engines_model_is_caught() {
+ if skip() {
+ return;
+ }
+ if common::skip_unless(Solver::Z3.available(), "z3", Solver::Z3.install_line()) {
+ return;
+ }
+ let d = scratch("forge");
+ // `∀x (A(x) → B(x))` and `A(a)`, so any model must put `a` in B.
+ let axioms = vec![
+ OwlAxiom::SubClass(
+ Concept::Atom("http://e/A".into()),
+ Concept::Atom("http://e/B".into()),
+ ),
+ OwlAxiom::ClassAssert(Concept::Atom("http://e/A".into()), "http://e/a".into()),
+ ];
+ let p = FolProblem::build(&axioms, None).expect("freshness holds");
+ let (tsv, digest) = p.to_problem_tsv().expect("writable");
+ let problem_path = d.join("problem.tsv");
+ std::fs::write(&problem_path, &tsv).expect("write");
+ std::fs::write(
+ d.join("p.smt2"),
+ p.to_smtlib(SmtEncoding::Finite(2)).expect("writable"),
+ )
+ .expect("write");
+ let text = String::from_utf8_lossy(
+ &Command::new("z3").arg(d.join("p.smt2")).output().expect("z3").stdout,
+ )
+ .to_string();
+ assert!(text.starts_with("sat"), "{text}");
+ let model = z3::parse_model(&text, &p.vocabulary(), 2).expect("readable");
+ let good = model.to_model_tsv(&digest, &[2]);
+ std::fs::write(d.join("model.tsv"), &good).expect("write");
+ let (code, out) = check(&problem_path, &d.join("model.tsv"));
+ assert_eq!(code, 0, "the unforged model must be accepted: {out}");
+
+ // (a) Empty the row for `c:http://e/B`, which the subsumption needs.
+ let b_row = good
+ .lines()
+ .find(|l| l.starts_with("p1\tc:http://e/B\t"))
+ .expect("a row for B")
+ .to_string();
+ let bits = b_row.rsplit('\t').next().expect("bits");
+ let forged = good.replace(&b_row, &format!("p1\tc:http://e/B\t{}", "0".repeat(bits.len())));
+ assert_ne!(forged, good, "the forgery must change something");
+ std::fs::write(d.join("forged_row.tsv"), forged).expect("write");
+ let (code, out) = check(&problem_path, &d.join("forged_row.tsv"));
+ assert_eq!(code, 1, "a flipped truth value must be rejected: {out}");
+ assert_eq!(field(&out, "verdict"), "rejected", "{out}");
+ assert_eq!(field(&out, "theorem"), "Fol.check_complete_closed", "{out}");
+ assert!(!field(&out, "label").is_empty(), "it must name the formula: {out}");
+
+ // (b) Delete a declaration, leaving its row behind.
+ let forged2: String = good
+ .lines()
+ .filter(|l| *l != "decl1\tthing")
+ .map(|l| format!("{l}\n"))
+ .collect();
+ std::fs::write(d.join("forged_decl.tsv"), forged2).expect("write");
+ let (code, out) = check(&problem_path, &d.join("forged_decl.tsv"));
+ assert_eq!(code, 2, "a row for an undeclared symbol is unreadable: {out}");
+
+ // (c) One hex digit of the digest.
+ let mut ch: Vec<char> = digest.chars().collect();
+ ch[15] = if ch[15] == '0' { '1' } else { '0' };
+ let forged3 = good.replace(
+ &format!("problem\t{digest}"),
+ &format!("problem\t{}", ch.iter().collect::<String>()),
+ );
+ std::fs::write(d.join("forged_digest.tsv"), forged3).expect("write");
+ let (code, out) = check(&problem_path, &d.join("forged_digest.tsv"));
+ assert_eq!(code, 1, "{out}");
+ assert_eq!(field(&out, "reason"), "problem_digest_mismatch", "{out}");
+ assert_eq!(field(&out, "expected"), digest, "{out}");
+}
+
+/// The checker is where `find_checker` finds it, and it is in `defaultTargets`
+/// so a bare `lake build` produces it.
+///
+/// That second half has bitten this repository once already and the lakefile
+/// comment records it: a proof outside the default set is not built by the CI
+/// job's bare `lake build`, and a proof that does not compile under a green
+/// gate is the exact failure this project exists to catch.
+#[test]
+fn the_checker_is_in_the_default_build() {
+ if skip() {
+ return;
+ }
+ let found = find_checker(None).expect("the pipeline must find the checker it just built");
+ assert!(found.is_file());
+ let lakefile =
+ std::fs::read_to_string(lean_dir().join("lakefile.toml")).expect("read lakefile");
+ let defaults = lakefile
+ .lines()
+ .find(|l| l.trim_start().starts_with("defaultTargets"))
+ .expect("a defaultTargets line");
+ assert!(defaults.contains("\"oo-folmodel\""), "{defaults}");
+ assert!(defaults.contains("\"Fol\""), "{defaults}");
+}