Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
wip: engine defects (dead classification budget, realize_definitions, CI skip sweep), interrupted by a session limit
FABIOTESS838445c1181c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex aa7d6715..61acd40c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -247,22 +247,75 @@ jobs:# Kept in CI rather than bolted onto the release workflow: a test that only# runs at publish time tells you about the defect after the artefact is# public.+ # The job used to install the `dev` extra and nothing else: pytest, and the one+ # base dependency. No cargo build, so no Rust engine. No elan, so no oo-horn.+ # The three-way differential — the Rust engine, the Python engine and the Lean+ # checker over the same documents — ran its preflight, found neither of the two+ # it needs, and skipped every test in the file. `pytest -q` printed an `s` per+ # skip and exited 0, so a green tick on this job said nothing whatsoever about+ # the differential. That is a gate that passes by not running, which is the+ # failure this repository exists to attack, and it was in this repository's own+ # CI.+ #+ # Two things had to change and both are here. The job now BUILDS what the+ # tests need, and `python/tests/conftest.py` makes `OO_REQUIRE_FIXTURES=1` mean+ # on this side what it has meant on the Rust side since `tests/common/mod.rs`:+ # a skip is a failure. The strict leg below names the files whose dependencies+ # this job actually provides, exactly as the `lean` job names its fifteen.python:- timeout-minutes: 15+ # 15 was enough for `pytest -q` on a pure-Python suite. This job now builds+ # `lean/` and a release binary, which is what the `lean` job budgets 45 for.+ timeout-minutes: 45name: python (open-ontologies-lite)runs-on: ubuntu-latest+ env:+ CARGO_INCREMENTAL: 0steps:- uses: actions/checkout@v4- uses: astral-sh/setup-uv@v5- uses: actions/setup-python@v5with:python-version: '3.10' # the floor declared by requires-python- - name: Install with dev extras+ # The Lean checker. Same action and same inputs as the `lean` job; building+ # `lean/` is itself the proof check, and it is what puts `oo-horn` at+ # lean/.lake/build/bin/oo-horn, which is where `find_checker` looks.+ - uses: leanprover/lean-action@v1+ with:+ lake-package-directory: lean+ build: true+ test: false+ lint: false+ use-github-cache: true+ - uses: dtolnay/rust-toolchain@stable+ - uses: Swatinem/rust-cache@v2+ # --release, not debug: tools/horn_differential.py looks for+ # target/release/open-ontologies and falls back only to PATH.+ - name: Build the Rust engine the differential compares against+ run: cargo build --release --bin open-ontologies+ # shacl and align as well as dev. Those two extras are the whole reason+ # three more files skipped here, and they are small.+ - name: Install with the extras the tests needworking-directory: python- run: uv pip install --system -e ".[dev]"+ run: uv pip install --system -e ".[dev,shacl,align]"- name: Testworking-directory: pythonrun: python -m pytest -q+ # The legs this job now provides the toolchain for. OO_REQUIRE_FIXTURES=1+ # turns any skip in them into a failure, so the job can no longer go green+ # by not running them. `fenic` is in no extra and no dependency list, so+ # test_dataframe.py is deliberately NOT here; it still skips loudly above.+ - name: The differential legs, where a skip is a failure+ working-directory: python+ run: |+ OO_REQUIRE_FIXTURES=1 python -m pytest -q \+ tests/test_horn_three_way_differential.py \+ tests/test_horn_differential.py \+ tests/test_horn_checked.py \+ tests/test_horn_rule_table.py \+ tests/test_shacl.py \+ tests/test_shacl_vacuous.py \+ tests/test_align.py \+ tests/test_vocab_check.py# Nothing built, type-checked or linted `studio/` before this, so a green tick# on a PR that only touched Studio said nothing whatsoever about it (#64 is@@ -431,6 +484,22 @@ jobs:# built to trip it and PRINTS what the tool said, so the evidence is in# the job log rather than in a doc.run: OO_REQUIRE_FIXTURES=1 cargo test --test gate_demonstration_test -- --nocapture+ # Four files that need nothing this job does not already have.+ #+ # Each of them calls `common::skip_unless` on lake, lake is installed+ # above, and no leg invoked any of them — so in the only job that could+ # have run them they were not run, and in every job that ran them+ # (`build`, with no lake) they skipped. A file that skips wherever it runs+ # and is not run where it would not skip is a gate in name only.+ # docs/ci-gates.md is the table this came out of.+ - name: The certificate boundary, against the real Lean parser+ run: OO_REQUIRE_FIXTURES=1 cargo test --test certificate_boundary_proptest -- --nocapture+ - name: OWL RL rule coverage against the checker's own table+ run: OO_REQUIRE_FIXTURES=1 cargo test --test reason_rl_coverage_test -- --nocapture+ - name: The SWRL and RIF front ends, through the checker+ run: OO_REQUIRE_FIXTURES=1 cargo test --test rule_syntax_frontend_test -- --nocapture+ - name: The emitted Horn rule table, round-tripped through oo-horn+ run: OO_REQUIRE_FIXTURES=1 cargo test --test reason_horn_emit_test -- --nocapture# The official W3C SHACL test suite, as a ratchet.#diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f58e7e55..7aee3995 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -648,15 +648,73 @@ All notable changes to Open Ontologies are documented here.wall clock goes from ~10s to 30-40s, since four tableau phases now each get theconfigured per-test budget instead of four sharing one already-expired instant.No verdict changed on any of the twenty.+- **`classify_timeout_ms` had never bounded a real run, and now bounds one or+ says it does not.** It defaults to 180 000 ms and its own documentation called+ it "the budget that actually bounds the run". Two separate reasons it was+ neither. It COULD NOT FIRE: five phases — consistency, satisfiability,+ subsumption, ABox, explanation — each open a `tableaux_test_timeout_ms` budget+ of 10 000 ms, and five times ten is fifty, which is less than a hundred and+ eighty, so the ceiling was dead arithmetic. And it DID NOT COVER THE RUN: the+ setting was read inside `classify_parallel` and nowhere else, so the three+ phases around classification each opened a fresh budget outside it and a run+ could exceed its own ceiling by three further phase budgets. The explanation+ loop had no wall clock at all — `Tableau::new_with_tracing` leaves+ `Budget::deadline` at `None` — and `run` performs one such tableau per+ unsatisfiable class, in a loop, straight after a classification that may have+ just been cut short for want of exactly that budget.+ The ceiling is now enforced over every phase, by intersecting it with each+ phase's own deadline rather than by minting a fifth budget beside them. That+ costs nothing measurable: a tableau already checks one deadline inside its+ expansion loop, and it is now handed the earlier of the two. Minting a deadline+ per TABLEAU is what would make 180 000 ms the bound that fires, and it is what+ took the corpus from 67s to over 600s with no verdict changing; it is still not+ done. What is done instead is the part that was missing, which is SAYING SO:+ every `owl-dl` run now carries a `budget` block naming both settings, the five+ phases, the worst case the phase budgets permit, which of the two bounds+ actually stops the run — `global`, `phase`, or `none` — and a sentence of prose+ saying why. A knob that reads as a safety limit may not enforce nothing; where+ it cannot be the binding one, the output says that in words rather than leaving+ a reader to do the arithmetic from two settings and a phase count.+ And the knob is now a knob. Neither budget appeared in `ReasonerConfig`, so+ neither could be set from `config.toml` at all — `apply_reasoner` wrote the+ depth cap, the node cap and the iteration cap and touched neither clock —+ while three comments in `src/tableaux.rs` referred to+ "`[reasoner] classify_timeout_ms`" as though it were a setting. The only way+ to move either was a setter that exists for tests: `set_tableaux_test_timeout_ms`+ was documented as "used by the CLI `--reason-timeout-ms` flag", and there is no+ such flag anywhere in `src/` — grep for it and the only hit is the sentence+ claiming it. Neither reasoner clock had a user-reachable setting of any kind,+ and both were documented as though they did. A ceiling nobody can lower is the+ strongest form of a limit that enforces nothing, and the note this now prints+ tells a reader to lower it. `[reasoner] classify_timeout_ms` and+ `[reasoner] tableaux_test_timeout_ms` are real keys; `0` means OFF for both,+ not "use the default", which is the opposite of the three caps beside them and+ is documented where they are declared.+ Corpus cost, measured with the new and reproducible+ `tests/reasoner_budget_corpus_bench.rs` over two corpora, the two builds run+ back to back under the same machine load: the twenty case-study ontologies,+ none of which reaches a budget, 0.10s before and 0.10s after; ten from+ `benchmark/` that do, two of them exhausting one, 64.53s before and 63.84s+ after. Unchanged, and it has to be, because at the shipped settings the+ intersection produces the same instant the phase budget alone did. Pinned by+ `tests/reasoner_global_budget_test.rs`.+- **Definition realization skipped every individual without a named+ `rdf:type`.** `realize_definitions` iterated `individual_types`, so an+ individual with no `rdf:type` at all — named only by its own role assertions —+ and an individual typed ONLY by an anonymous class expression were never+ realized into a defined class, however completely they met the definition.+ `build_abox_tableau` has given both a node for some time, because `rdfs:domain`+ binds them and a disjointness axiom can refute them: the consistency check saw+ them and the realizer did not. A false NEGATIVE rather than a false clean,+ which is why it survived. Realization now runs over the same individual+ universe the ABox tableau is built from, so the two cannot drift, and a+ conjunct of an anonymous `rdf:type` discharges the definition conjunct it is+ spelled the same as, because `x : C ⊓ D` entails `x : C`. Widening the universe+ cannot widen what matches: `satisfies` declines everything outside its+ fragment, so an empty named-type set can only fail. Pinned by three tests in+ `tests/abox_realization_test.rs`, one of them a negative control.### Known defects-- **`classify_timeout_ms` has never bounded a real run.** It defaults to 180s,- but until the phase-budget fix above, the single shared per-test deadline- expired 10s into the run and made every later tableau bail on entry, so the- 180s budget never governed anything. It still does not: phase budgets are- scoped per phase, which keeps the cost of the fix at 3-4x rather than the 18x- measured when each tableau was given its own. The setting is therefore still- not the bound it claims to be, and reconciling the two budgets is open.- **`owl:AsymmetricProperty` is not modelled.** It is now DECLARED, in`unmodelled_constructs`, alongside `owl:ReflexiveProperty` and`owl:IrreflexiveProperty`. Asymmetry constrains a PAIR of edges rather than adiff --git a/Cargo.toml b/Cargo.tomlindex 231f60dd..0f492418 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -106,6 +106,11 @@ unexpected_cfgs = { level = "warn", check-cfg = ['cfg(kani)'] }[dev-dependencies]tempfile = "3"wat = "1.256.0"+# Already a normal dependency; repeated here so a test can assert that a+# `config.toml` section really does carry the key it claims to. A setting that+# only a setter can move is not a setting, and two reasoner budgets were in that+# position. No new crate enters the tree.+toml = "0.8"# Property testing for the certificate boundary (docs/trusted-computing-base.md).# The Lean proofs are conditional on the Rust writing down the truth, and that# boundary is a tab-separated format carrying arbitrary RDF terms: exactly thediff --git a/docs/ci-gates.md b/docs/ci-gates.mdnew file mode 100644index 00000000..14064967--- /dev/null+++ b/docs/ci-gates.md@@ -0,0 +1,133 @@+# Which gates actually run in CI++A test that skips reports `ok`. A job full of them reports success. This+repository exists to attack exactly that shape of claim, and it had the shape in+its own suite: the CI `python` job installed one extra and nothing else, so the+three-way differential — the Rust engine, the Python engine and the Lean checker+over the same documents — ran its preflight, found neither of the two tools it+needs, skipped every test in the file, and exited 0.++This page is the answer to "does a green tick mean this ran?", so that nobody has+to work it out again from six workflow files and the thirty-three test files that+can skip — twenty-four Rust, nine Python. It is a statement about CI+configuration, which changes; the date it was last checked is at the bottom, and+the way to re-check it is at the bottom too.++## The convention++`tests/common/mod.rs` defines `skip_unless(available, what, how_to_get_it)`.+When the thing is missing it prints `SKIPPED_FIXTURE: …` and returns `true`, and+when `OO_REQUIRE_FIXTURES` is exactly `"1"` it panics instead. Any job that is+supposed to PROVIDE a toolchain sets that variable, and the suite can then no+longer quietly shrink inside it.++`python/tests/conftest.py` does the same for the Python suite, and does it+globally: every skip is caught, whatever raised it — `pytest.skip`, a `skipif`+marker, a module-level `pytest.importorskip` — because in Python a skip needs no+helper to be written and a per-call-site rule would miss the next one. A skip+that is deliberate rather than missing (there is one, the twelve-minute+full-corpus differential) carries `@pytest.mark.oo_opt_in` and is exempt. The+marker is greppable; a reason string is not.++Two tool scripts mirror the variable under their own names because they are CLIs+rather than test suites, and say so where they define it:+`HORN_DIFF_REQUIRE_TOOLS=1` in `tools/horn_differential.py` and+`FOL_DIFF_REQUIRE_ATP=1` in `tools/fol_differential.py`. Both exit 2 rather than+panicking.++## The table++**strict** means the leg runs under `OO_REQUIRE_FIXTURES=1` in a job that+provides its toolchain, so a missing tool fails the job. **skips** means the+toolchain is not provided and the test does nothing, loudly. **not run** means no+job invokes the file at all.++### Rust — `tests/*.rs`++| test file | needs | provided by | in CI |+|---|---|---|---|+| `lean_certificate_test.rs` | lake | `lean` job | **strict** |+| `shacl_core_verified_test.rs` | lake + vendored W3C SHACL suite | `lean` job | **strict** |+| `dl_model_certificate_test.rs` | lake + `oo-dlmodel` | `lean` job | **strict** |+| `lean_refutation_test.rs` | lake + `oo-refute` | `lean` job | **strict** |+| `lean_refutation_producer_test.rs` | lake + `oo-refute` | `lean` job | **strict** |+| `lean_mixed_certificate_test.rs` | lake | `lean` job | **strict** |+| `lean_horn_certificate_test.rs` | lake | `lean` job | **strict** |+| `lean_fol_model_test.rs` | lake + `oo-folmodel` + z3 | `lean` job | **strict** |+| `fol_solver_verdict_test.rs` | z3 + `oo-folmodel` + the debug CLI | `lean` job | **strict** |+| `lean_projection_entailment_test.rs` | lake | `lean` job | **strict** |+| `closure_diff_test.rs` | lake | `lean` job | **strict** |+| `projection_monotonicity_corpus_test.rs` | lake | `lean` job | **strict** |+| `preserve_cli_test.rs` | lake | `lean` job | **strict** |+| `gate_demonstration_test.rs` | lake | `lean` job | **strict** |+| `w3c_shacl_conformance_test.rs` | vendored W3C SHACL suite (in tree) | `w3c-shacl` job | **strict** |+| `certificate_boundary_proptest.rs` | lake | `lean` job | **strict** |+| `reason_rl_coverage_test.rs` | lake | `lean` job | **strict** |+| `rule_syntax_frontend_test.rs` | lake | `lean` job | **strict** |+| `reason_horn_emit_test.rs` | lake + `tests/fixtures/horn/` (in tree) | `lean` job | **strict** |+| `cross_kernel_differential_test.rs` | lake **and** Isabelle2025-2 + Poly/ML | lake only | **skips** — the Isabelle half is installed by no job; it cannot be made strict without an Isabelle step |+| `clinical_test.rs` | `data/crosswalks.parquet` | nothing — `data/` is gitignored | **skips** |+| `embed_test.rs` | ONNX model in `~/.open-ontologies/models/` | `features/depth` compiles it; no job runs `open-ontologies init` | **skips** |+| `embedding_e2e_test.rs` | same ONNX model + tokenizer | same | **skips** |+| `claimcheck_pizza_bench.rs` | `/tmp/pizza_compiled.json` from `CompileOntology.java` | only `benchmark.yml` has a JDK, it is `workflow_dispatch` and does not produce the file | **skips** |++`fol_model_ingest_test.rs` runs in the `lean` job under the same variable and has+no skip path at all, which is why it is not in the table.++### Python — `python/tests/*.py`++| test file | needs | provided by | in CI |+|---|---|---|---|+| `test_horn_three_way_differential.py` | Rust engine + `oo-horn` + corpus | `python` job builds both | **strict** |+| `test_horn_differential.py` | Rust engine + `oo-horn` + `demo/` corpus | `python` job | **strict** |+| `test_horn_checked.py` | `oo-horn` + `tests/fixtures/horn/` | `python` job | **strict** |+| `test_horn_rule_table.py` | `tests/fixtures/horn/` + git | `python` job | **strict** |+| `test_shacl.py` | `pyshacl` (the `shacl` extra) | `python` job installs it | **strict** |+| `test_shacl_vacuous.py` | `pyshacl` | `python` job | **strict** |+| `test_align.py` | `hnswlib` (the `align` extra) | `python` job installs it | **strict** |+| `test_vocab_check.py` | `pyoxigraph` (a base dependency) | always present | **strict** |+| `test_dataframe.py` | `fenic` | **nothing** — `fenic` is in no extra and no dependency list | **skips** |++The other seven files under `python/tests/` have no skip path.++## What is still open, and why++- **`cross_kernel_differential_test.rs`.** No job installs Isabelle, so the+ second kernel is never exercised in CI. Making this strict means adding an+ Isabelle2025-2 step, which is a large download; it has not been done, and until+ it is, the Isabelle half of the cross-kernel claim rests on local runs.+- **`clinical_test.rs`, `embed_test.rs`, `embedding_e2e_test.rs`.** All three+ want an artefact the repository deliberately does not carry: a licensed+ crosswalk table and a model download. Closing them means a job that fetches+ those, which is a cost and a licence question rather than a CI oversight.+- **`claimcheck_pizza_bench.rs`.** Needs a Java compile step that exists only in+ the dispatch-only benchmark workflow. Its skip at least goes through+ `skip_unless` now; before, it printed `SKIP:` and was invisible both to the+ `build` job's skip counter and to `OO_REQUIRE_FIXTURES`.+- **`test_dataframe.py`.** `fenic` is an undeclared optional test dependency.+ Declaring it as an extra and installing it in the `python` job is the fix; it+ was not made here because the dependency has not been assessed.+- **The `features/breadth` job runs no tests** (`test: false`); it is+ `cargo check` plus clippy across all features. That is deliberate and is not a+ skip, but it does mean an all-features build is type-checked and never run.+- **Kani.** `make verify` runs three bounded-model-checking harnesses. No job+ installs Kani, so none of them runs in CI. `docs/trusted-computing-base.md`+ says so where it reports their results.+- **The Makefile and CI have drifted.** No workflow invokes `make`. `make check`+ is `lint test audit`, and its `test` is a bare `cargo test` with no+ `OO_REQUIRE_FIXTURES`, so a local `make check` is the permissive run whatever+ is installed.++## Re-checking this page++```bash+# every Rust file that can skip+grep -ln 'skip_unless\|SKIPPED_FIXTURE' tests/*.rs+# every Python file that can skip+grep -rln 'pytest.skip\|importorskip\|skipif' python/tests/*.py+# every leg CI makes strict+grep -rn 'OO_REQUIRE_FIXTURES=1' .github/workflows/+```++The three lists have to reconcile against the table above. Last checked against+`.github/workflows/` on 14 September 2026.diff --git a/python/tests/conftest.py b/python/tests/conftest.pynew file mode 100644index 00000000..df2af9e3--- /dev/null+++ b/python/tests/conftest.py@@ -0,0 +1,95 @@+"""`OO_REQUIRE_FIXTURES=1` turns a skip into a failure here too.++The Rust suite has had this since `tests/common/mod.rs` was written: a test that+skips for want of a toolchain prints a `SKIPPED_FIXTURE:` marker, and any job+that is supposed to PROVIDE that toolchain sets `OO_REQUIRE_FIXTURES=1`, which+makes the skip fatal. The `lean` job runs fifteen legs that way, and+`w3c-shacl` one more. The Python suite had no equivalent of any kind: no+`conftest.py` existed, no test read the variable, and every `pytest.skip` and+`pytest.importorskip` in `python/tests/` was unconditional and unpromotable.++That mattered most where it hurt most. `test_horn_three_way_differential.py` is+the three-way differential — the Rust engine, this Python engine and the Lean+checker over the same documents — and the CI `python` job installed the `dev`+extra and nothing else: no `cargo build`, so no Rust engine; no elan, so no+`oo-horn`. The file's own preflight found neither and skipped every test in it.+A green tick on that job said nothing whatsoever about the differential, which+is the precise shape of failure this repository exists to attack: a gate that+passes by not running. Setting `OO_REQUIRE_FIXTURES=1` on the job would not have+helped, because nothing on this side read it.++The rule is deliberately GLOBAL rather than per-call-site. In Rust a skip has to+be written through `common::skip_unless` to be catchable, so a new one added by+hand is invisible to the convention; here every skip is caught, whatever raised+it — `pytest.skip`, a `skipif` marker, a module-level `pytest.importorskip` —+and a new one cannot be added without either providing the dependency or+declaring the skip deliberate.++DELIBERATE SKIPS. A test skipped because it is SLOW rather than because+something is missing is a different thing, and marking it `@pytest.mark.oo_opt_in`+exempts it. There is exactly one: the full-corpus differential, which takes+twelve minutes. The marker is greppable, which a reason string is not.+"""++import os++import pytest++# Same spelling and same semantics as tests/common/mod.rs:22 — the string must+# be exactly "1". Anything else, including "true" and "yes", is not set.+STRICT = os.environ.get("OO_REQUIRE_FIXTURES") == "1"++# Same marker the Rust helper prints, so one grep counts skips across both+# suites and the `build` job's existing counter needs no second pattern.+MARKER = "SKIPPED_FIXTURE"++OPT_IN = "oo_opt_in"+++def pytest_configure(config):+ config.addinivalue_line(+ "markers",+ f"{OPT_IN}: this test is skipped by choice (cost, not a missing "+ f"dependency), so OO_REQUIRE_FIXTURES=1 leaves it skipped.",+ )+++def _reason(report):+ """The skip reason, however pytest happens to have packed it."""+ longrepr = getattr(report, "longrepr", None)+ if isinstance(longrepr, tuple) and len(longrepr) == 3:+ return str(longrepr[2]).removeprefix("Skipped: ")+ return str(longrepr) if longrepr else "no reason given"+++def _fail(report, nodeid, reason):+ print(f"{MARKER}: {nodeid}: {reason}", flush=True)+ if not STRICT:+ return+ report.outcome = "failed"+ report.longrepr = (+ f"{nodeid} skipped: {reason}\n"+ f"OO_REQUIRE_FIXTURES=1, so this is a failure, not a skip. This job is "+ f"supposed to provide what the test needs; provide it, or stop claiming "+ f"the test ran."+ )++[email protected](wrapper=True, trylast=True)+def pytest_runtest_makereport(item, call):+ report = yield+ if report.skipped and not hasattr(report, "wasxfail"):+ if item.get_closest_marker(OPT_IN) is None:+ _fail(report, item.nodeid, _reason(report))+ return report+++def pytest_collectreport(report):+ """A module-level `importorskip` skips at COLLECTION, not at run time.++ `pytest_runtest_makereport` never sees those, so three of this suite's files+ — the two pyshacl ones and the hnswlib one — would have stayed exempt from a+ rule written only there.+ """+ if report.skipped:+ _fail(report, report.nodeid, _reason(report))diff --git a/python/tests/test_horn_three_way_differential.py b/python/tests/test_horn_three_way_differential.pyindex 12ebcf0f..d312c85f 100644--- a/python/tests/test_horn_three_way_differential.py+++ b/python/tests/test_horn_three_way_differential.py@@ -359,6 +359,9 @@ def test_the_seven_rules_the_corpus_cannot_reach_are_covered_by_fixtures(capsys))+# Skipped because it is SLOW, not because anything is missing, which is the one+# kind of skip `OO_REQUIRE_FIXTURES=1` must leave alone. See python/tests/conftest.py.[email protected]_opt_in@pytest.mark.skipif(os.environ.get("HORN_DIFF_FULL") != "1",reason="the full corpus takes twelve minutes. HORN_DIFF_FULL=1 to run it here, or run "diff --git a/src/config.rs b/src/config.rsindex b9e08f97..b5045f3f 100644--- a/src/config.rs+++ b/src/config.rs@@ -476,6 +476,32 @@ pub struct ReasonerConfig {/// RDFS / OWL-RL fixpoint guard. Maximum number of expansion iterations/// before the reasoner returns the partial closure. Default 64.pub max_iterations: usize,+ /// Tableaux DL reasoner: wall-clock budget for one PHASE of a run, in+ /// milliseconds. Default 10 000. **`0` means no limit**, unlike the three+ /// caps above, where 0 means "unset, use the default": a depth cap of zero+ /// is not a configuration anybody wants and a timeout of zero is.+ ///+ /// This is the budget that actually expires on a hard ontology. A run has+ /// five phases — consistency, satisfiability, subsumption, ABox, explanation+ /// — and each opens one of these, so the worst case for a run is five times+ /// this number or `classify_timeout_ms`, whichever is smaller.+ pub tableaux_test_timeout_ms: usize,+ /// Tableaux DL reasoner: wall-clock CEILING for a whole run, in+ /// milliseconds. Default 180 000, the ORE competition convention. **`0`+ /// means no ceiling.**+ ///+ /// Enforced over every phase, and at the default it cannot be the bound that+ /// fires, because five phases at 10 000 ms cap a run at 50 000 ms first. Set+ /// it below that to make it the binding one. Every `owl-dl` run reports which+ /// of the two is binding in its `budget` block, so this does not have to be+ /// worked out from these two numbers.+ ///+ /// NEITHER of these two existed here until the budget was audited. They were+ /// process-wide statics with setters for tests and, for the phase budget, one+ /// CLI flag; three comments in `src/tableaux.rs` referred to+ /// "`[reasoner] classify_timeout_ms`" as though it were a setting. A ceiling+ /// nobody can lower is the strongest form of a limit that enforces nothing.+ pub classify_timeout_ms: usize,}impl Default for ReasonerConfig {fn default() -> Self {@@ -483,6 +509,8 @@ impl Default for ReasonerConfig {tableaux_max_depth: 100,tableaux_max_nodes: 10_000,max_iterations: 64,+ tableaux_test_timeout_ms: 10_000,+ classify_timeout_ms: 180_000,}}}diff --git a/src/runtime.rs b/src/runtime.rsindex 02587a99..efb782e7 100644--- a/src/runtime.rs+++ b/src/runtime.rs@@ -87,6 +87,14 @@ fn apply_reasoner(r: &ReasonerConfig) {TABLEAUX_MAX_DEPTH.store(depth, Ordering::Relaxed);TABLEAUX_MAX_NODES.store(nodes, Ordering::Relaxed);REASONER_MAX_ITER.store(iters, Ordering::Relaxed);+ // Stored VERBATIM, with no `if x == 0 { DEFAULT }` rewrite, because for a+ // clock zero is a configuration and not an omission: `0` means no limit, and+ // both accessors read it that way. An omitted key does not arrive here as 0+ // — `#[serde(default)]` fills it from `ReasonerConfig::default`, which is+ // 10 000 and 180 000 — so the two cases are distinguishable, which is+ // exactly what the three caps above cannot do.+ TABLEAUX_TEST_TIMEOUT_MS.store(r.tableaux_test_timeout_ms, Ordering::Relaxed);+ CLASSIFY_TIMEOUT_MS.store(r.classify_timeout_ms, Ordering::Relaxed);}fn apply_cache(hash_prefix: usize) {@@ -135,19 +143,39 @@ pub fn tableaux_test_timeout_ms() -> Option<u64> {}}-/// Override the per-test timeout. Used by the CLI `--reason-timeout-ms` flag-/// and by tests.+/// Override the per-phase timeout, for tests.+///+/// This used to say "used by the CLI `--reason-timeout-ms` flag and by tests".+/// There is no such flag anywhere in `src/`; grep for it and the only hit is+/// the sentence that claimed it. With `[reasoner] tableaux_test_timeout_ms`+/// also absent from `ReasonerConfig` until it was added beside+/// `classify_timeout_ms`, neither reasoner clock had ANY user-reachable+/// setting at all, and both were documented as though they did.pub fn set_tableaux_test_timeout_ms(ms: usize) {TABLEAUX_TEST_TIMEOUT_MS.store(ms, Ordering::Relaxed);}-/// Wall-clock cut-off for an ENTIRE classification run, in milliseconds.-/// `None` (value 0) means no limit.+/// Wall-clock CEILING for an entire reasoning run, in milliseconds. `None`+/// (value 0) means no ceiling.////// Distinct from the per-test timeout, which bounds one satisfiability check./// Classification performs one check per class plus one per ordered pair, so-/// the per-test budget multiplied by the pair count is the real worst case and-/// it is enormous. This is the budget that actually bounds the run.+/// the per-test budget multiplied by the pair count is the enormous number this+/// exists to cut off.+///+/// READ THIS BEFORE QUOTING IT AS THE BOUND. It is a ceiling over every phase of+/// a run — consistency, satisfiability, subsumption, ABox, explanation — and it+/// is enforced: `DlReasoner::phase_deadline_within` intersects it with each+/// phase's own deadline, so no phase can outlive it. At the SHIPPED DEFAULTS it+/// nonetheless cannot be the bound that fires, because those five phases each+/// open a `tableaux_test_timeout_ms` budget of 10 000 ms and five times ten is+/// fifty, which is less than a hundred and eighty. Making it the binding bound+/// means minting a deadline per tableau rather than per phase, which was+/// measured: a 20-ontology corpus went from 67s to over 600s with no verdict+/// changing. The engine therefore reports, in `budget.binding_bound` and+/// `budget.note` on every `owl-dl` run, which of the two bounds actually stops+/// the run — including "neither" — rather than leaving a reader to do this+/// arithmetic from two settings and a phase count.////// Default matches the ORE competition convention of 180s.pub fn classify_timeout_ms() -> Option<u64> {diff --git a/src/tableaux.rs b/src/tableaux.rsindex b7b01e8c..09cdd2c1 100644--- a/src/tableaux.rs+++ b/src/tableaux.rs@@ -2253,11 +2253,12 @@ pub struct DlReasoner {/// that classification was what spent it.////// Each phase now opens its own from this duration, and no cap was raised:- /// the number is unchanged, `classify_timeout_ms` still bounds the whole- /// classification, and the node and depth caps are untouched. Which phase ran- /// out is reported in `budget_exhausted_in`. See `phase_deadline` for why the- /// unit is a phase rather than a single test, which is what the setting's own- /// name says.+ /// the number is unchanged and the node and depth caps are untouched. Which+ /// phase ran out is reported in `budget_exhausted_in`. See `phase_deadline`+ /// for why the unit is a phase rather than a single test, which is what the+ /// setting's own name says, and `phase_deadline_within` for how+ /// `classify_timeout_ms` is intersected into it so that no phase can outlive+ /// the run's ceiling.budget_ms: Option<u64>,/// The axioms as the OWL parser read them, before `ProcessedTBox` absorbed,/// rewrote and folded them. A model certificate is written against these, so@@ -2371,25 +2372,62 @@ impl DlReasoner {/// rather than a reading of the setting's name. `tableaux_test_timeout_ms`/// does say "a single tableau satisfiability test", and minting it per/// tableau is the literal reading — but the two sweeps run one tableau per- /// class and one per ORDERED PAIR of classes, and they are already bounded as- /// a whole by `classify_timeout_ms`, which defaults to 180s. Because the old- /// shared instant expired 10s into the run and made every later tableau bail- /// on entry, that 180s budget had never actually governed anything. Minting- /// per tableau hands it the run for the first time, and it costs what it says+ /// class and one per ORDERED PAIR of classes, and the shape that bounds them+ /// as a whole is a budget per sweep rather than one per test. Minting per+ /// tableau is also what would make `classify_timeout_ms` the bound that+ /// fires, since with 10s per tableau a sweep runs until the 180s ceiling+ /// stops it — and it costs what it says/// it costs: MEASURED on this machine, a 20-ontology corpus went from 67s to/// over 600s, with the five ontologies that hit the cap moving from ~10s each/// to ~180s each and NO change in any verdict — the same classes stayed/// undetermined, just after eighteen times the work. Per phase fixes the/// defect that was reported (the ABox check inheriting a spent clock) and- /// bounds the change at 3x the old worst case instead of 18x.+ /// bounds the change at 3x the old worst case instead of 18x. The cost of+ /// that choice is that the ceiling cannot be the bound that fires, and every+ /// `owl-dl` run now says so in its `budget` block rather than leaving a+ /// reader to infer it from two settings and a phase count.///- /// That `classify_timeout_ms` has never bounded a real run is a separate- /// finding and is not fixed here.+ /// `classify_timeout_ms` is now a CEILING over every phase, not a fifth+ /// budget beside them: see `phase_deadline_within`, which is what every+ /// phase inside a run actually calls. A bare `phase_deadline` is for a+ /// caller running one phase on its own with no run around it.fn phase_deadline(&self) -> Option<Instant> {self.budget_ms.map(|ms| Instant::now() + std::time::Duration::from_millis(ms))}+ /// A phase budget under a run's global ceiling: whichever expires first.+ ///+ /// This is the whole of the cheap half of making `classify_timeout_ms` real.+ /// A tableau already checks ONE deadline inside its expansion loop, so+ /// handing it the earlier of the two costs nothing at all — no second clock+ /// read, no extra branch — while making it impossible for any phase to+ /// outlive the global budget. The expensive half, minting a fresh budget per+ /// TABLEAU so that the global one is what eventually stops the sweep, is what+ /// took the corpus from 67s to over 600s and is not what this does.+ ///+ /// `None` on either side means "that one imposes nothing", so with the global+ /// budget switched off this is the phase budget unchanged, and with the phase+ /// budget switched off it is the global deadline, which is the case that used+ /// to leave a sweep with no clock at all.+ fn phase_deadline_within(&self, global: Option<Instant>) -> Option<Instant> {+ match (self.phase_deadline(), global) {+ (Some(phase), Some(global)) => Some(phase.min(global)),+ (Some(phase), None) => Some(phase),+ (None, global) => global,+ }+ }++ /// The ceiling for one whole run, opened now from `classify_timeout_ms`.+ ///+ /// Open it ONCE per run and pass it down. Opening it per phase is what made+ /// the setting vacuous: four phases each opening a fresh 180s meant a run+ /// could take 720s under a budget that says 180.+ fn global_deadline() -> Option<Instant> {+ crate::runtime::classify_timeout_ms()+ .map(|ms| Instant::now() + std::time::Duration::from_millis(ms))+ }+/// Three-valued satisfiability test — each call creates its own Tableau.////// Returns `Unknown` when a resource budget was hit before a decision was@@ -2450,13 +2488,42 @@ impl DlReasoner {/// Check TBox consistency. An undecided run reports consistent, which is/// the safe direction: we do not condemn an ontology we failed to refute.pub fn is_consistent(&self) -> bool {- !self.decide_satisfiable(&Concept::Top).is_unsat()+ self.is_consistent_within(Self::global_deadline())+ }++ /// `is_consistent` under a ceiling the caller already opened. This is the+ /// first phase of a run and used to be outside the global budget entirely.+ pub fn is_consistent_within(&self, global: Option<Instant>) -> bool {+ !self+ .decide_satisfiable_within(&Concept::Top, self.phase_deadline_within(global))+ .is_unsat()}/// Explain why a class is unsatisfiable. Returns None if satisfiable.pub fn explain_unsatisfiable(&self, class_id: u32) -> Option<Vec<String>> {+ self.explain_unsatisfiable_within(class_id, self.phase_deadline())+ }++ /// `explain_unsatisfiable` against a deadline the caller already opened.+ ///+ /// `Tableau::new_with_tracing` left `Budget::deadline` at `None`, so an+ /// explanation was the one tableau in this engine that ran under no+ /// wall-clock budget at all — and `run` performs one per unsatisfiable+ /// class, in a loop, immediately after a classification that may have been+ /// cut short for want of exactly that budget. The node and depth caps still+ /// applied; nothing stopped the branching.+ ///+ /// An expired deadline yields `None`, which is the honest degradation: the+ /// tableau returns `Unknown`, and `Unknown` is not a proof of+ /// unsatisfiability, so there is no clash trace to report.+ pub fn explain_unsatisfiable_within(+ &self,+ class_id: u32,+ deadline: Option<Instant>,+ ) -> Option<Vec<String>> {let concept = Concept::Atom(class_id);let mut tableau = Tableau::new_with_tracing(Arc::clone(&self.tbox));+ tableau.budget.deadline = deadline;if !tableau.decide(&concept).is_unsat() {return None;}@@ -2518,6 +2585,16 @@ impl DlReasoner {/// Phase 2 — Subsumption Agent: parallel pairwise subsumption with told-pruning./// Phase 3 — Equivalence detection from mutual subsumptions.pub fn classify_parallel(&self) -> AgentClassificationResult {+ self.classify_parallel_within(Self::global_deadline())+ }++ /// `classify_parallel` under a ceiling the caller already opened, so that+ /// classification and the phases around it share ONE global budget instead+ /// of opening one each.+ pub fn classify_parallel_within(+ &self,+ global_deadline: Option<Instant>,+ ) -> AgentClassificationResult {let start = Instant::now();// Sorted for the same reason as the node traversals: `named_classes` is a@@ -2533,15 +2610,19 @@ impl DlReasoner {.collect();classes.sort_unstable();- // Global budget for the WHOLE classification.+ // The ceiling for the whole run, opened by the caller.//// The per-test deadline bounds one satisfiability check. It does not// bound classification, which runs one check per class plus one per// ordered pair of classes. On the Pizza ontology that is ~100 classes// and ~10,000 pairs; at the 10s per-test budget the worst case is over// a day. A global deadline is what actually stops that.- let global_deadline = crate::runtime::classify_timeout_ms()- .map(|ms| Instant::now() + std::time::Duration::from_millis(ms));+ //+ // Checked here at the head of each task, which is the cheap place, AND+ // folded into every tableau's own deadline below, which is the place+ // that makes it a ceiling rather than a suggestion: without the fold, a+ // single tableau that started inside the budget could run for a further+ // phase-budget's worth of time past it.let out_of_time = || global_deadline.is_some_and(|d| Instant::now() >= d);// ── Satisfiability Agent ─────────────────────────────────────@@ -2552,7 +2633,7 @@ impl DlReasoner {// constructed, so whichever phase ran first spent the clock and the ABox// check — which runs last and is the one a user reads for their own data// — routinely reported `undecided` on an ABox it decides in microseconds.- let sat_deadline = self.phase_deadline();+ let sat_deadline = self.phase_deadline_within(global_deadline);let sat_results: Vec<(u32, Verdict)> = classes.par_iter().map(|&cls| {@@ -2616,7 +2697,7 @@ impl DlReasoner {let subsumption_cut_short = std::sync::atomic::AtomicBool::new(false);// This phase's own budget, opened now rather than inherited from the// satisfiability sweep that just finished.- let sub_deadline = self.phase_deadline();+ let sub_deadline = self.phase_deadline_within(global_deadline);let inferred: Vec<(u32, u32)> = pairs.par_iter().filter(|(sub, sup)| {@@ -2738,12 +2819,69 @@ impl DlReasoner {by_subject.entry(a).or_default().push((r, b));}- for (&ind, types) in &self.individual_types {+ // Every individual, not only the ones carrying a NAMED rdf:type.+ //+ // This used to iterate `individual_types`, which is keyed by exactly+ // those. An individual with no rdf:type at all — named only by its own+ // role assertions — and an individual typed ONLY by an anonymous class+ // expression both have no entry there, so neither was ever realized into+ // a defined class however completely it met the definition.+ // `build_abox_tableau` has given both a node for some time, because a+ // domain constraint binds them and a disjointness axiom can refute them:+ // the consistency check saw them and the realizer did not.+ //+ // The universe is built the same way `build_abox_tableau` builds its+ // node set, so the individuals realization considers and the individuals+ // the consistency check ran on are one set rather than two that can+ // drift. Widening it cannot widen what counts as a match: `satisfies`+ // declines everything outside its fragment, so an empty named-type set+ // can only fail to match.+ let mut individuals: Vec<u32> = self.individual_types.keys().copied().collect();+ for &ind in self.individual_anon_types.keys() {+ if !self.individual_types.contains_key(&ind) {+ individuals.push(ind);+ }+ }+ for &(a, _, b) in &self.role_assertions {+ individuals.push(a);+ individuals.push(b);+ }+ individuals.sort_unstable();+ individuals.dedup();++ let empty: HashSet<u32> = HashSet::new();+ for ind in individuals {+ // Conjuncts of an anonymous rdf:type are assertions in their own+ // right, and the atomic ones are named types this individual has+ // exactly as if they had been written as an ordinary rdf:type.+ let asserted = self.asserted_concepts(ind);+ let declared = self.individual_types.get(&ind).unwrap_or(&empty);+ // Borrowed unless an anonymous type actually contributes a named+ // one. Widening the universe to every individual means this runs+ // once per individual rather than once per TYPED individual, and a+ // SKOS vocabulary is tens of thousands of individuals with no+ // anonymous type at all; a HashSet clone each would be a real cost+ // for nothing.+ let types: std::borrow::Cow<'_, HashSet<u32>> =+ if asserted.iter().any(|c| matches!(c, Concept::Atom(_))) {+ std::borrow::Cow::Owned(+ declared+ .iter()+ .copied()+ .chain(asserted.iter().filter_map(|c| match c {+ Concept::Atom(a) => Some(*a),+ _ => None,+ }))+ .collect(),+ )+ } else {+ std::borrow::Cow::Borrowed(declared)+ };for (&cls, def) in &self.definitions {if types.contains(&cls) {continue;}- if self.satisfies(ind, types, def, &by_subject) {+ if self.satisfies(ind, &types, &asserted, def, &by_subject) {out.entry(ind).or_default().insert(cls);}}@@ -2751,20 +2889,57 @@ impl DlReasoner {out}+ /// Every concept `ind` is DIRECTLY asserted to belong to by an anonymous+ /// `rdf:type`, flattened through conjunction.+ ///+ /// `x rdf:type C ⊓ D` entails `x rdf:type C` and `x rdf:type D`, so each+ /// conjunct is an assertion on its own. Nothing else is unfolded: no axiom is+ /// applied and no subsumption is followed here, so this stays a reading of+ /// what the graph SAYS rather than an inference from it, which is the same+ /// discipline the rest of this function keeps.+ fn asserted_concepts(&self, ind: u32) -> Vec<Concept> {+ let mut out = Vec::new();+ let Some(anon) = self.individual_anon_types.get(&ind) else {+ return out;+ };+ let mut stack: Vec<Concept> = anon.clone();+ while let Some(c) = stack.pop() {+ match c {+ Concept::And(parts) => stack.extend(parts),+ other => out.push(other),+ }+ }+ out+ }+/// True when the asserted facts about `ind` entail `concept`, for the accepted fragment./// Returns false for anything outside it, which keeps unsupported definitions empty/// rather than unsound.+ ///+ /// `types` is the individual's named types, `asserted` the conjuncts of its+ /// anonymous ones. Either may be empty; an individual with neither is decided+ /// entirely on its role assertions, which is the whole point of considering it.fn satisfies(&self,ind: u32,types: &HashSet<u32>,+ asserted: &[Concept],concept: &Concept,by_subject: &HashMap<u32, Vec<(u32, u32)>>,) -> bool {+ // An assertion discharges the conjunct it is spelled the same as. Both+ // sides are in NNF and come from the same interner, so structural+ // equality here is concept identity, and `x : C` entails `C` for any `C`+ // whatever — including the shapes the match below declines.+ if asserted.iter().any(|a| a == concept) {+ return true;+ }match concept {Concept::Top => true,Concept::Atom(c) => self.has_type(types, *c),- Concept::And(parts) => parts.iter().all(|p| self.satisfies(ind, types, p, by_subject)),+ Concept::And(parts) => parts+ .iter()+ .all(|p| self.satisfies(ind, types, asserted, p, by_subject)),Concept::Exists(role, filler) => {let Concept::Atom(target) = **filler else {return false;@@ -2826,14 +3001,15 @@ impl DlReasoner {/// role assertion is a node that a domain constraint binds and a disjointness/// axiom can refute, and reporting `individuals_checked: 0` for an ABox made/// entirely of those also suppressed the whole `abox` block from the output.- fn build_abox_tableau(&self) -> (Tableau, HashMap<u32, u32>, usize) {+ fn build_abox_tableau(&self, global: Option<Instant>) -> (Tableau, HashMap<u32, u32>, usize) {// The ABox check builds ONE tableau containing every named individual,// so it is the largest single expansion the reasoner ever performs and it// must be under a budget, or it is an unbounded hole in one. It opens its// OWN, which is the point of `phase_deadline`: sharing an instant with// classification is what had this phase reporting `undecided` on ABoxes// it decides in microseconds, because classification had already spent it.- let mut tableau = Tableau::with_deadline(Arc::clone(&self.tbox), self.phase_deadline());+ let mut tableau =+ Tableau::with_deadline(Arc::clone(&self.tbox), self.phase_deadline_within(global));let mut ind_to_node: HashMap<u32, u32> = HashMap::new();// Create nodes for each individual carrying a named-class OR an anonymous@@ -2941,6 +3117,16 @@ impl DlReasoner {}pub fn check_abox(&self) -> ABoxResult {+ self.check_abox_within(Self::global_deadline())+ }++ /// `check_abox` under a ceiling the caller already opened.+ ///+ /// This phase used to be outside `classify_timeout_ms` entirely: the setting+ /// was read inside `classify_parallel` and nowhere else, so a run that spent+ /// the whole global budget classifying went on to open a fresh phase budget+ /// here. A knob a run can exceed is not a ceiling.+ pub fn check_abox_within(&self, global: Option<Instant>) -> ABoxResult {// "No ABox" has to mean no ABox, and a role assertion is ABox. An// ontology whose entire instance data is untyped individuals related by// a property with a domain still states something refutable, and this@@ -2959,7 +3145,7 @@ impl DlReasoner {};}- let (mut tableau, ind_to_node, individuals_checked) = self.build_abox_tableau();+ let (mut tableau, ind_to_node, individuals_checked) = self.build_abox_tableau(global);// Same three-valued discipline as everywhere else: exhausting the// budget is not a proof of inconsistency. Declaring an ABox@@ -3005,9 +3191,19 @@ impl DlReasoner {let reasoner = Self::from_graph(graph)?;let initial_triples = graph.triple_count();- let tbox_consistent = reasoner.is_consistent();- let result = reasoner.classify_parallel();- let abox_result = reasoner.check_abox();+ // ONE ceiling for the whole run, opened here and passed to every phase.+ //+ // `classify_timeout_ms` used to be read inside `classify_parallel` and+ // nowhere else, so the three phases around it — the consistency check+ // before, the ABox check after, the explanation loop after that — each+ // opened a budget of their own and none of them was under it. A run+ // could exceed the ceiling it was given by three further phase budgets,+ // and the explanation loop had no wall clock at all.+ let global_deadline = Self::global_deadline();++ let tbox_consistent = reasoner.is_consistent_within(global_deadline);+ let result = reasoner.classify_parallel_within(global_deadline);+ let abox_result = reasoner.check_abox_within(global_deadline);// The headline flag answers for the whole knowledge base. Reporting the TBox alone// while the ABox check has PROVEN an inconsistency in the same output is a false@@ -3015,10 +3211,12 @@ impl DlReasoner {// defaults to consistent inside check_abox.let consistent = tbox_consistent && abox_result.consistent;- // Collect explanations for unsatisfiable classes+ // Collect explanations for unsatisfiable classes. One phase, one budget,+ // under the same ceiling as the three before it.+ let explain_deadline = reasoner.phase_deadline_within(global_deadline);let mut explanations: Vec<serde_json::Value> = Vec::new();for &cls in &result.unsatisfiable {- if let Some(steps) = reasoner.explain_unsatisfiable(cls) {+ if let Some(steps) = reasoner.explain_unsatisfiable_within(cls, explain_deadline) {explanations.push(serde_json::json!({"class": reasoner.interner.resolve(cls),"trace": steps,@@ -3047,12 +3245,13 @@ impl DlReasoner {// WHICH phase ran out, not merely THAT something did.//// `complete: false` says the run is not a proof. It does not say which of- // the three phases to give more room, and they do not draw on the same- // settings: the satisfiability and subsumption sweeps are bounded by- // `[reasoner] classify_timeout_ms` across the whole classification as well- // as by their own `tableaux_test_timeout_ms` phase budget, while the ABox- // check is one tableau under that phase budget alone. A reader who is told- // only "incomplete" cannot act, and before each phase got its own budget+ // the three phases to give more room. Every phase now draws on the same+ // two settings — its own `tableaux_test_timeout_ms` budget, under the+ // `[reasoner] classify_timeout_ms` ceiling for the whole run — and the+ // `budget` block below says which of the two is the one that fires. The+ // ABox check used to be under the phase budget ALONE, outside the ceiling+ // entirely. A reader who is told only "incomplete" cannot act, and before+ // each phase got its own budget// the phase that hit the wall was usually not the phase that spent the// time — classification would eat the clock and the ABox check would be// the one reporting `undecided`. Naming the phases makes that visible@@ -3068,6 +3267,83 @@ impl DlReasoner {budget_exhausted_in.push("abox");}+ // WHICH budget was in force, in words, in the output.+ //+ // `classify_timeout_ms` defaults to 180 000 ms and its own documentation+ // called it "the budget that actually bounds the run". It had never+ // bounded one. Each phase opens its own deadline from+ // `tableaux_test_timeout_ms`, which defaults to 10 000 ms; five phases is+ // a worst case of 50 000 ms, so the 180 000 ms ceiling is dead+ // arithmetic and cannot fire. Handing the global budget the run instead+ // means minting a deadline per TABLEAU, which was measured and took a+ // 20-ontology corpus from 67s to over 600s, and was abandoned.+ //+ // What is left is the thing that was missing: SAYING SO. A knob that+ // reads as a safety limit may not enforce nothing, and the arithmetic+ // that decides whether it can fire is two settings and a phase count,+ // which is not something a reader of the output can be expected to do.+ // The ceiling is now genuinely enforced over every phase — see+ // `phase_deadline_within` — and this block says which of the two bounds+ // is the one that actually stops the run, including when the answer is+ // neither.+ let phase_names = ["consistency", "satisfiability", "subsumption", "abox", "explanation"];+ let global_ms = crate::runtime::classify_timeout_ms();+ let phase_ms = crate::runtime::tableaux_test_timeout_ms();+ let phase_worst_case_ms = phase_ms.map(|ms| ms * phase_names.len() as u64);+ let (binding_bound, note) = match (global_ms, phase_worst_case_ms) {+ (None, None) => (+ "none",+ format!(+ "no wall-clock bound of any kind is in force: classify_timeout_ms and \+ tableaux_test_timeout_ms are both 0. The only limits left are the node \+ cap ({}) and the depth cap ({}), and neither bounds the number of \+ BRANCHES a tableau explores.",+ crate::runtime::tableaux_max_nodes(),+ crate::runtime::tableaux_max_depth()+ ),+ ),+ (None, Some(worst)) => (+ "phase",+ format!(+ "no global bound is in force: classify_timeout_ms is 0. Each of the {} \+ phases opens its own {} ms budget, so the worst case for this run is \+ {worst} ms.",+ phase_names.len(),+ phase_ms.unwrap_or(0)+ ),+ ),+ (Some(g), None) => (+ "global",+ format!(+ "classify_timeout_ms ({g} ms) is the only wall-clock bound: \+ tableaux_test_timeout_ms is 0, so no phase budget can expire before it \+ and every tableau runs to the global deadline."+ ),+ ),+ (Some(g), Some(worst)) if g <= worst => (+ "global",+ format!(+ "classify_timeout_ms ({g} ms) is at or below the worst case the phase \+ budgets permit ({} phases x {} ms = {worst} ms), so it is the bound that \+ stops this run.",+ phase_names.len(),+ phase_ms.unwrap_or(0)+ ),+ ),+ (Some(g), Some(worst)) => (+ "phase",+ format!(+ "classify_timeout_ms ({g} ms) cannot be the bound that stops this run: \+ {} phases at {} ms each cap it at {worst} ms. It is enforced as a ceiling \+ over every phase and will not fire at this setting. The bound in force is \+ the phase budget; lower classify_timeout_ms below {worst} to make it the \+ binding one.",+ phase_names.len(),+ phase_ms.unwrap_or(0)+ ),+ ),+ };+let mut hierarchy_json: Vec<serde_json::Value> = Vec::new();for (&cls, supers) in &result.hierarchy {let cls_name = reasoner.interner.resolve(cls);@@ -3147,6 +3423,14 @@ impl DlReasoner {"unsatisfiable_classes": unsat_names,"complete": complete,"budget_exhausted_in": budget_exhausted_in,+ "budget": {+ "classify_timeout_ms": global_ms,+ "phase_timeout_ms": phase_ms,+ "phases": phase_names,+ "phase_worst_case_ms": phase_worst_case_ms,+ "binding_bound": binding_bound,+ "note": note,+ },"undetermined_classes": undetermined_names,"subsumption_sweep_cut_short": result.subsumption_cut_short,"inferred_subsumptions": result.inferred_subsumptions,@@ -4234,6 +4518,18 @@ impl DlReasoner {/// The named classes, in the interner's order, so a caller can certify each/// one. `run` uses it because TBox consistency alone is witnessed by a/// single point with empty extensions, which is honest and uninformative.+ /// The internal id of a named class, by IRI, for callers that hold a name+ /// and need the id `explain_unsatisfiable` takes. Matches the spelling+ /// `named_class_names` returns, angle brackets and all, and also the bare+ /// IRI, because a caller that has one rarely has the other.+ pub fn named_class_id(&self, iri: &str) -> Option<u32> {+ let bare = iri.trim_start_matches('<').trim_end_matches('>');+ self.named_classes+ .iter()+ .copied()+ .find(|&id| self.interner.resolve(id).trim_start_matches('<').trim_end_matches('>') == bare)+ }+pub fn named_class_names(&self) -> Vec<String> {let mut v: Vec<String> = self.named_classes@@ -4324,7 +4620,7 @@ impl DlReasoner {.to_string(),));}- let (mut tableau, ind_to_node, _) = self.build_abox_tableau();+ let (mut tableau, ind_to_node, _) = self.build_abox_tableau(Self::global_deadline());tableau.capture = true;if !tableau.expand(0) {return Ok(if tableau.budget.exhausted {diff --git a/tests/abox_realization_test.rs b/tests/abox_realization_test.rsindex 54989b9a..5452c02d 100644--- a/tests/abox_realization_test.rs+++ b/tests/abox_realization_test.rs@@ -127,3 +127,92 @@ fn a_subclass_typed_individual_satisfies_a_superclass_conjunct() {"asserted subclass must satisfy a superclass conjunct");}++// ── Individuals the realizer never looked at ────────────────────────────────+//+// `realize_definitions` iterated `individual_types`, which is keyed by+// individuals carrying at least one NAMED `rdf:type`. Two kinds of individual+// have no entry there and were therefore never realized into any defined class,+// however completely they met the definition:+//+// 1. an individual with no `rdf:type` at all, named only by its own role+// assertions — `build_abox_tableau` already gives these a node, precisely+// because `rdfs:domain` binds them and a disjointness axiom can refute+// them, so the consistency check saw them and the realizer did not;+// 2. an individual typed ONLY by an anonymous class expression, which lands in+// `individual_anon_types` and never in `individual_types`.+//+// This is a false NEGATIVE, not a false clean, which is why it survived. It is+// still an incompleteness with nothing behind it: `satisfies` declines anything+// outside its fragment, so handing it an empty named-type set can only fail to+// match, never match wrongly.++const UNTYPED: &str = r#"+@prefix : <http://ex.org/> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .++:Term a owl:Class .+:Status a owl:Class .+:Dead a owl:NamedIndividual, :Status .++:status a owl:ObjectProperty .+:usedBy a owl:ObjectProperty .++# Defined by restrictions alone. Nothing in the definition asks for an+# rdf:type, so an individual needs none to be a member.+:Haunted a owl:Class ; owl:equivalentClass [ a owl:Class ; owl:intersectionOf (+ [ a owl:Restriction ; owl:onProperty :status ; owl:hasValue :Dead ]+ [ a owl:Restriction ; owl:onProperty :usedBy ; owl:someValuesFrom :Term ] ) ] .++:host a owl:NamedIndividual, :Term .++# No rdf:type whatsoever. Meets both conjuncts.+:ghost :status :Dead ; :usedBy :host .++# No rdf:type, and meets only one conjunct. Must NOT be realized.+:echo :usedBy :host .++# Typed ONLY by an anonymous class expression. The :status conjunct comes from+# that expression, the :usedBy conjunct from an asserted edge.+:wraith a [ a owl:Class ; owl:intersectionOf (+ :Term+ [ a owl:Restriction ; owl:onProperty :status ; owl:hasValue :Dead ] ) ] ;+ :usedBy :host .+"#;++#[test]+fn an_individual_with_no_rdf_type_is_realized() {+ let v = realized(UNTYPED);+ assert!(+ types_of(&v, "/ghost").contains(&"Haunted".to_string()),+ "an untyped individual meeting every conjunct must be realized; the realizer \+ iterated individual_types, so it never saw this individual at all. got {:?} \+ from {v}",+ types_of(&v, "/ghost")+ );+}++#[test]+fn an_untyped_individual_missing_a_conjunct_is_not_realized() {+ let v = realized(UNTYPED);+ assert!(+ !types_of(&v, "/echo").contains(&"Haunted".to_string()),+ "widening the realizer to untyped individuals must not widen what counts as \+ a match; got {:?}",+ types_of(&v, "/echo")+ );+}++#[test]+fn an_individual_typed_only_by_an_anonymous_class_is_realized() {+ let v = realized(UNTYPED);+ assert!(+ types_of(&v, "/wraith").contains(&"Haunted".to_string()),+ "an anonymous rdf:type asserts a class expression, and a conjunct of that \+ expression is entailed of the individual just as an asserted edge is; got {:?} \+ from {v}",+ types_of(&v, "/wraith")+ );+}diff --git a/tests/claimcheck_pizza_bench.rs b/tests/claimcheck_pizza_bench.rsindex c9ee39b2..faad7ff1 100644--- a/tests/claimcheck_pizza_bench.rs+++ b/tests/claimcheck_pizza_bench.rs@@ -7,6 +7,17 @@//!//! Regenerate with://! java -cp ".:lib/*" CompileOntology /tmp/pizza_real.owl /tmp/pizza_compiled.json+//!+//! The skip goes through `common::skip_unless`, like every other skip in this+//! suite. It used to be a bare `eprintln!("SKIP: …")`, which printed a marker+//! the `build` job's skip COUNTER does not match and which `OO_REQUIRE_FIXTURES=1`+//! could not promote to a failure — so this file was the one skip in the Rust+//! suite that was invisible to both halves of the convention. Nothing in CI+//! provides the Java compile step today (only `benchmark.yml` installs a JDK,+//! and it is `workflow_dispatch` only and does not produce this file), so it+//! still skips everywhere; it now says so in the shape everything else uses.++mod common;use std::path::Path;@@ -21,8 +32,12 @@ fn iri(l: &str) -> String {}fn load() -> Option<CompiledOntology> {- if !Path::new(COMPILED).exists() {- eprintln!("SKIP: {COMPILED} not present; run CompileOntology first");+ if common::skip_unless(+ Path::new(COMPILED).exists(),+ COMPILED,+ "regenerate it with `java -cp \".:lib/*\" CompileOntology /tmp/pizza_real.owl \+ /tmp/pizza_compiled.json` from benchmark/reasoner.",+ ) {return None;}let v: Value = serde_json::from_str(&std::fs::read_to_string(COMPILED).ok()?).ok()?;diff --git a/tests/reasoner_budget_corpus_bench.rs b/tests/reasoner_budget_corpus_bench.rsnew file mode 100644index 00000000..23b915af--- /dev/null+++ b/tests/reasoner_budget_corpus_bench.rs@@ -0,0 +1,160 @@+//! What a change to the reasoner's budgets costs, measured rather than asserted.+//!+//! `src/tableaux.rs` carries a cost measurement in a doc comment — "a+//! 20-ontology corpus went from 67s to over 600s" — and until this file there+//! was no way to reproduce it. A number in a comment that nobody can re-run is a+//! number that goes stale silently, and the budget it justifies is exactly the+//! kind of setting that gets changed by someone who cannot check what it costs.+//!+//! The corpus is fixed and is in the repository: every `*.ttl` under a+//! `case-studies/**/ontology/` directory, plus the two core ontologies that live+//! one level up, minus `occupational-map.ttl`, which is 5.7 MB and is already+//! excluded from the certificate corpus for the same reason. That is twenty+//! files.+//!+//! IGNORED by default, because it takes minutes and measures wall clock, which+//! is not a thing an assertion should be built on. Run it deliberately:+//!+//! ```text+//! cargo test --release --test reasoner_budget_corpus_bench -- --ignored --nocapture+//! ```+//!+//! It prints per-ontology wall time, the phases that ran out of budget, and the+//! total. Compare two totals; do not compare a total against a number in a+//! comment written on a different machine.+//!+//! MEASURED, 14 September 2026, `cargo test` debug profile, this machine,+//! running the two builds back to back so they share whatever load the machine+//! was under — which matters more than it sounds: an earlier pair of runs+//! differed by a factor of four purely because a release build was competing+//! with one of them. The change under test is `phase_deadline_within`, which+//! puts every phase under the `classify_timeout_ms` ceiling, plus the widening+//! of definition realization to untyped individuals.+//!+//! | corpus | before | after |+//! |---|---|---|+//! | twenty case-study ontologies, none reaching a budget | 0.10s | 0.10s |+//! | ten that do, two of them exhausting one | 64.53s | 63.84s |+//!+//! Unchanged, and it has to be: at the shipped settings+//! `min(now + 10 000 ms, now + 180 000 ms)` is the same instant the phase+//! budget alone produced, so the intersection is arithmetic and not work. The+//! difference shows up only when `classify_timeout_ms` is set below five times+//! `tableaux_test_timeout_ms`, which is when it is meant to.++mod common;++use std::sync::Arc;+use std::time::Instant;++use open_ontologies::graph::GraphStore;+use open_ontologies::reason::Reasoner;++/// The ontologies in this repository that actually exhaust a reasoner budget.+///+/// The case-study corpus below is broad and EASY: measured here it runs in under+/// three seconds and not one of the twenty hits a cap, so a change to the budget+/// logic is invisible in it. A cost measurement over a corpus that never reaches+/// the thing being measured is the shape of number this project exists to+/// refuse, so this second list exists and is the one that answers the question.+/// `nominals_blowup.ttl` is in `benchmark/reasoner/regressions/` for exactly this+/// reason: `owl:hasValue` is approximated by an atomic concept named after the+/// individual, and a class defined by one per department is what makes the+/// tableau branch.+const HARD: &[&str] = &[+ "benchmark/reasoner/regressions/nominals_blowup.ttl",+ "benchmark/generated/pizza-ai.ttl",+ "benchmark/generated/boro-building-ai.ttl",+ "benchmark/generated/ies-building-extension.ttl",+ "benchmark/reference/ies4.ttl",+ "benchmark/reference/ies-core.ttl",+ "benchmark/reference/ies-top.ttl",+ "benchmark/reference/boro-building-handcrafted.ttl",+ "benchmark/epc/iris-building.ttl",+ "benchmark/mushroom/mushroom-ontology.ttl",+];++const CORPUS: &[&str] = &[+ "case-studies/foundry-owl-crosswalk/ontology/foundry-crosswalk.ttl",+ "case-studies/heritage-aerial/extensions/commerce/ontology/naph-commerce-shapes.ttl",+ "case-studies/heritage-aerial/extensions/commerce/ontology/naph-commerce.ttl",+ "case-studies/heritage-aerial/ontology/naph-core.ttl",+ "case-studies/heritage-aerial/ontology/naph-ric-o-crosswalk.ttl",+ "case-studies/heritage-aerial/ontology/naph-shapes.ttl",+ "case-studies/insurance-register-ontology/iro-core.ttl",+ "case-studies/investment-fund-ontology/ifo-core.ttl",+ "case-studies/modip-plastics-kg/ontology/colours.ttl",+ "case-studies/modip-plastics-kg/ontology/domains.ttl",+ "case-studies/modip-plastics-kg/ontology/facets.ttl",+ "case-studies/modip-plastics-kg/ontology/materials.ttl",+ "case-studies/modip-plastics-kg/ontology/objectnames.ttl",+ "case-studies/modip-plastics-kg/ontology/processes.ttl",+ "case-studies/nature-governance-graph/ontology/ngg.ttl",+ "case-studies/robot-safety-security-crosswalk/ontology/rssc.ttl",+ "case-studies/skills-england-occupational-maps/ontology/seom-vocabulary.ttl",+ "case-studies/skills-england-occupational-maps/ontology/shapes.ttl",+ "case-studies/skills-mobility/ontology/skills-mobility-scheme.ttl",+ "case-studies/zero-emission-aviation/ontology/zef.ttl",+];++fn sweep(label: &str, files: &[&str]) {+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));+ let present = files.iter().all(|rel| root.join(rel).is_file());+ if common::skip_unless(+ present,+ label,+ "it is tracked in this repository; run from a full checkout.",+ ) {+ return;+ }++ println!("── {label} ──");+ let mut total = std::time::Duration::ZERO;+ let mut capped = 0usize;+ for rel in files {+ let path = root.join(rel);+ let ttl = std::fs::read_to_string(&path).expect("corpus file must read");+ let store = Arc::new(GraphStore::new());+ if store.load_turtle(&ttl, None).is_err() {+ println!("{rel:>78} DID NOT PARSE");+ continue;+ }+ let start = Instant::now();+ let out = Reasoner::run(&store, "owl-dl", false).expect("owl-dl must run");+ let took = start.elapsed();+ total += took;+ let v: serde_json::Value = serde_json::from_str(&out).unwrap();+ let phases = v["budget_exhausted_in"].to_string();+ if phases != "[]" {+ capped += 1;+ }+ println!(+ "{:>78} {:>8.2}s exhausted={} bound={}",+ rel,+ took.as_secs_f64(),+ phases,+ v["budget"]["binding_bound"]+ );+ }+ println!(+ "TOTAL {:.2}s over {} ontologies, {} of them hit a budget\n",+ total.as_secs_f64(),+ files.len(),+ capped+ );+}++#[test]+#[ignore = "wall-clock measurement over thirty ontologies; run it deliberately"]+fn owl_dl_over_the_shipped_corpora() {+ println!(+ "phase budget (tableaux_test_timeout_ms): {:?}",+ open_ontologies::runtime::tableaux_test_timeout_ms()+ );+ println!(+ "global budget (classify_timeout_ms): {:?}\n",+ open_ontologies::runtime::classify_timeout_ms()+ );+ sweep("the twenty case-study ontologies", CORPUS);+ sweep("the ten that exhaust a budget", HARD);+}diff --git a/tests/reasoner_global_budget_test.rs b/tests/reasoner_global_budget_test.rsnew file mode 100644index 00000000..caf08732--- /dev/null+++ b/tests/reasoner_global_budget_test.rs@@ -0,0 +1,256 @@+//! `classify_timeout_ms` bounds a real run, or the run says that it does not.+//!+//! The setting defaults to 180 000 ms and its own documentation calls it "the+//! budget that actually bounds the run". It has never bounded one. Two separate+//! reasons, and both are here:+//!+//! 1. **It could not fire.** Each phase of a classification opens its own+//! deadline from `tableaux_test_timeout_ms`, which defaults to 10 000 ms.+//! Four phases — consistency, satisfiability, subsumption, ABox — is a+//! worst case of 40 000 ms, so a 180 000 ms global deadline is dead+//! arithmetic. An earlier attempt to fix this by minting a deadline per+//! TABLEAU did hand the global budget the run, and took a 20-ontology+//! corpus from 67s to over 600s. It was abandoned, correctly, and the knob+//! stayed.+//! 2. **It did not cover the run.** `classify_timeout_ms` was read inside+//! `classify_parallel` and nowhere else, so the TBox consistency check+//! before it, the ABox check after it and the explanation loop after that+//! each opened a fresh budget of their own. A run could therefore exceed+//! `classify_timeout_ms` outright, which is the opposite of a ceiling. The+//! explanation loop had no wall-clock budget at all: `Tableau::+//! new_with_tracing` left `Budget::deadline` at `None`.+//!+//! What a knob that reads as a safety limit may not do is enforce nothing. It+//! now enforces a ceiling over every phase, at no cost, because a phase deadline+//! is intersected with the global one rather than minted beside it — and where+//! the arithmetic means the ceiling cannot be what stops the run, the output+//! SAYS which bound is in force instead of leaving a reader to infer it from two+//! settings and a phase count.+//!+//! This file lives on its own and holds ONE test, for the reason+//! `reasoner_phase_budget_test.rs` gives: it moves process-wide budget settings,+//! and `cargo test` runs the tests inside one binary on a shared thread pool.++use std::sync::Arc;++use open_ontologies::graph::GraphStore;+use open_ontologies::reason::Reasoner;+use open_ontologies::runtime;++/// Decided in microseconds under any budget, including none at all.+const TRIVIAL: &str = r#"+@prefix owl: <http://www.w3.org/2002/07/owl#> .+@prefix ex: <http://example.org/> .+ex:A a owl:Class .+ex:B a owl:Class .+ex:a a ex:A .+"#;++/// Enough classes that a classification sweep cannot finish inside a+/// millisecond, so a 1 ms global deadline is provably spent before the ABox+/// check is reached. 80 classes is 6320 ordered pairs.+fn wide() -> String {+ let mut ttl = String::from(+ "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n\+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\+ @prefix ex: <http://example.org/> .\n",+ );+ for i in 0..80 {+ ttl.push_str(&format!("ex:C{i} a owl:Class .\n"));+ if i > 0 {+ ttl.push_str(&format!("ex:C{i} rdfs:subClassOf ex:C{}.\n", i - 1));+ }+ }+ ttl.push_str("ex:a a ex:C79 .\n");+ ttl+}++fn run(ttl: &str) -> serde_json::Value {+ let store = Arc::new(GraphStore::new());+ store.load_turtle(ttl, None).unwrap();+ let out = Reasoner::run(&store, "owl-dl", false).expect("owl-dl must run");+ serde_json::from_str(&out).unwrap()+}++fn exhausted(v: &serde_json::Value) -> Vec<String> {+ v["budget_exhausted_in"]+ .as_array()+ .map(|a| {+ a.iter()+ .filter_map(|x| x.as_str().map(str::to_string))+ .collect()+ })+ .unwrap_or_default()+}++#[test]+fn the_classification_budget_bounds_the_run_or_the_run_says_it_does_not() {+ let restore_global = runtime::classify_timeout_ms().unwrap_or(0) as usize;+ let restore_phase = runtime::tableaux_test_timeout_ms().unwrap_or(0) as usize;++ // ── 1. The shipped defaults. The global budget cannot fire, and the run+ // has to say so rather than present 180s as the bound.+ runtime::set_classify_timeout_ms(180_000);+ runtime::set_tableaux_test_timeout_ms(10_000);+ let v = run(TRIVIAL);+ let b = v["budget"].clone();+ assert!(+ b.is_object(),+ "a run has to report which budget was in force. Two settings and a phase \+ count is not a report; it is a puzzle. got {v}"+ );+ assert_eq!(b["classify_timeout_ms"], 180_000, "{b}");+ assert_eq!(b["phase_timeout_ms"], 10_000, "{b}");+ assert_eq!(+ b["phases"].as_array().map(Vec::len),+ Some(5),+ "consistency, satisfiability, subsumption, ABox and explanation each \+ open a phase budget, and the worst case is their sum: {b}"+ );+ assert_eq!(b["phase_worst_case_ms"], 50_000, "{b}");+ assert_eq!(+ b["binding_bound"], "phase",+ "50 000 ms of phase budget under a 180 000 ms ceiling means the ceiling \+ is not what stops the run: {b}"+ );+ let note = b["note"].as_str().unwrap_or_default().to_string();+ assert!(+ note.contains("cannot"),+ "the note has to state plainly that the global bound cannot be the one \+ that fires, got {note:?}"+ );++ // ── 2. A global budget smaller than a phase budget is the bound, and it+ // covers the WHOLE run. The ABox check used to open a fresh deadline+ // of its own after classification had spent the global one, so a run+ // could outlast the ceiling it was given.+ runtime::set_classify_timeout_ms(1);+ runtime::set_tableaux_test_timeout_ms(10_000);+ let v = run(&wide());+ assert_eq!(v["budget"]["binding_bound"], "global", "{v}");+ let ms = v["agents"]["total_time_ms"].as_u64().unwrap_or(0);+ assert!(+ ms >= 1,+ "this test needs classification to outlast a 1 ms deadline, and it took \+ {ms} ms. Widen the ontology."+ );+ assert!(+ exhausted(&v).contains(&"abox".to_string()),+ "the global deadline was spent before the ABox check began, so the ABox \+ check ran outside the budget that is supposed to bound the run: {v}"+ );++ // ── 3. The global budget switched off. Say so; do not report a bound.+ runtime::set_classify_timeout_ms(0);+ runtime::set_tableaux_test_timeout_ms(10_000);+ let v = run(TRIVIAL);+ assert_eq!(v["budget"]["classify_timeout_ms"], serde_json::Value::Null, "{v}");+ assert_eq!(v["budget"]["binding_bound"], "phase", "{v}");+ let note = v["budget"]["note"].as_str().unwrap_or_default().to_string();+ assert!(+ note.contains("no global bound"),+ "with classify_timeout_ms off, the output must state in words that no \+ global bound is in force, got {note:?}"+ );++ // ── 4. No wall-clock bound at all. That is a legitimate configuration and+ // the least excusable one to leave a reader guessing about.+ runtime::set_classify_timeout_ms(0);+ runtime::set_tableaux_test_timeout_ms(0);+ let v = run(TRIVIAL);+ assert_eq!(v["budget"]["binding_bound"], "none", "{v}");+ let note = v["budget"]["note"].as_str().unwrap_or_default().to_string();+ assert!(+ note.contains("node") && note.contains("depth"),+ "with both clocks off the only bounds left are the node and depth caps, \+ and the note has to name them, got {note:?}"+ );++ // ── 5. The explanation loop is a phase like any other, and it had no clock+ // at all. `Tableau::new_with_tracing` leaves `Budget::deadline` at+ // `None`, and `run` performs one such tableau per unsatisfiable class+ // in a loop, immediately after a classification that may have just+ // been cut short for want of exactly that budget.+ runtime::set_classify_timeout_ms(0);+ runtime::set_tableaux_test_timeout_ms(10_000);+ let store = Arc::new(GraphStore::new());+ store+ .load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <http://example.org/> .+ ex:A a owl:Class . ex:B a owl:Class .+ ex:A owl:disjointWith ex:B .+ ex:Bad a owl:Class ; rdfs:subClassOf ex:A , ex:B .+ "#,+ None,+ )+ .unwrap();+ let reasoner =+ open_ontologies::tableaux::DlReasoner::from_graph(&store).expect("reasoner builds");+ let bad = reasoner+ .named_class_id("http://example.org/Bad")+ .expect("ex:Bad is a named class");+ assert!(+ reasoner.explain_unsatisfiable(bad).is_some(),+ "ex:Bad is a subclass of two disjoint classes and this engine explains it"+ );+ let spent = std::time::Instant::now() + std::time::Duration::from_millis(1);+ std::thread::sleep(std::time::Duration::from_millis(5));+ assert!(+ reasoner.explain_unsatisfiable_within(bad, Some(spent)).is_none(),+ "an explanation is a tableau expansion, and an expired deadline has to \+ stop it. A tableau that ran out of budget returns Unknown, and Unknown \+ is not a proof of unsatisfiability, so there is no clash trace to report."+ );++ // ── 6. The knob has to BE a knob. Neither budget appeared in+ // `ReasonerConfig`, so neither could be set from `config.toml` at+ // all: `apply_reasoner` wrote the depth cap, the node cap and the+ // iteration cap and touched neither clock. Three comments in+ // `src/tableaux.rs` referred to "`[reasoner] classify_timeout_ms`" as+ // though it were a setting. The only ways to move either were the+ // `--reason-timeout-ms` flag, which moves the per-test one only, and+ // the setters above, which exist for tests. A ceiling nobody can lower+ // is the strongest form of a limit that enforces nothing, and the note+ // this run now prints tells a reader to lower it.+ let toml = r#"+ [reasoner]+ classify_timeout_ms = 4321+ tableaux_test_timeout_ms = 1234+ "#;+ let cfg: open_ontologies::config::Config =+ toml::from_str(toml).expect("[reasoner] must accept both budgets");+ runtime::init_from_config(&cfg);+ assert_eq!(+ runtime::classify_timeout_ms(),+ Some(4321),+ "config.toml has to be able to set the ceiling"+ );+ assert_eq!(+ runtime::tableaux_test_timeout_ms(),+ Some(1234),+ "and the phase budget"+ );++ // Zero means OFF for a clock, not "use the default". The other three+ // `[reasoner]` numbers read 0 as "unset, use the default", because a depth+ // cap of zero is not a configuration anyone wants; a timeout of zero is.+ let cfg: open_ontologies::config::Config = toml::from_str(+ "[reasoner]\nclassify_timeout_ms = 0\ntableaux_test_timeout_ms = 0\n",+ )+ .unwrap();+ runtime::init_from_config(&cfg);+ assert_eq!(runtime::classify_timeout_ms(), None, "0 is off, not default");+ assert_eq!(runtime::tableaux_test_timeout_ms(), None, "0 is off, not default");++ // And an omitted section leaves the shipped defaults, not zero.+ let cfg: open_ontologies::config::Config = toml::from_str("").unwrap();+ runtime::init_from_config(&cfg);+ assert_eq!(runtime::classify_timeout_ms(), Some(180_000));+ assert_eq!(runtime::tableaux_test_timeout_ms(), Some(10_000));++ runtime::set_classify_timeout_ms(restore_global);+ runtime::set_tableaux_test_timeout_ms(restore_phase);+}