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
Bound the tableau by steps, not only by a clock (#212)
Fabio Rovaid8c779722192
diff --git a/src/runtime.rs b/src/runtime.rsindex 87e2f9cf..40d87f37 100644--- a/src/runtime.rs+++ b/src/runtime.rs@@ -23,6 +23,7 @@ use crate::config::{// ── Defaults match the previous hardcoded constants exactly ─────────────const DEFAULT_TABLEAUX_MAX_DEPTH: usize = 100;const DEFAULT_TABLEAUX_MAX_NODES: usize = 10_000;+const DEFAULT_TABLEAUX_MAX_STEPS: usize = 5_000_000;/// 10s per satisfiability test. Generous for well-behaved ontologies, and the/// difference between a reported Unknown and an unbounded hang for the rest.const DEFAULT_TABLEAUX_TEST_TIMEOUT_MS: usize = 10_000;@@ -43,6 +44,11 @@ const DEFAULT_WEBHOOK_TIMEOUT: u64 = 10;static TABLEAUX_MAX_DEPTH: AtomicUsize = AtomicUsize::new(DEFAULT_TABLEAUX_MAX_DEPTH);static TABLEAUX_MAX_NODES: AtomicUsize = AtomicUsize::new(DEFAULT_TABLEAUX_MAX_NODES);+/// Generous by design. It is a backstop against exponential backtracking, not a+/// working limit: every ontology in the benchmark set finishes far inside it,+/// and a run that hits it should be read as "this needs more budget" rather+/// than as an answer.+static TABLEAUX_MAX_STEPS: AtomicUsize = AtomicUsize::new(DEFAULT_TABLEAUX_MAX_STEPS);static TABLEAUX_TEST_TIMEOUT_MS: AtomicUsize =AtomicUsize::new(DEFAULT_TABLEAUX_TEST_TIMEOUT_MS);static CLASSIFY_TIMEOUT_MS: AtomicUsize = AtomicUsize::new(DEFAULT_CLASSIFY_TIMEOUT_MS);@@ -128,6 +134,23 @@ fn apply_webhook(w: &WebhookConfig) {pub fn tableaux_max_depth() -> usize { TABLEAUX_MAX_DEPTH.load(Ordering::Relaxed) }pub fn tableaux_max_nodes() -> usize { TABLEAUX_MAX_NODES.load(Ordering::Relaxed) }+/// Deterministic ceiling on the WORK one satisfiability test may do, counted in+/// expansion steps. `None` (value 0) means no step bound.+///+/// The node and depth budgets do not bound the number of BRANCHES explored, so+/// before this existed the only thing that did was a wall clock. A clock makes+/// the verdict depend on how fast the machine is, which is how a soundness test+/// came to fail about three runs in five against an unmodified baseline (#161).+/// This bounds the same work deterministically: the same ontology takes the+/// same number of steps on every machine, so a run either finishes or does not,+/// everywhere, and a budget that stops a run says which budget it was.+pub fn tableaux_max_steps() -> Option<u64> {+ match TABLEAUX_MAX_STEPS.load(Ordering::Relaxed) {+ 0 => None,+ n => Some(n as u64),+ }+}+/// Wall-clock cut-off for a single tableau satisfiability test, in/// milliseconds. `None` (value 0) means no time limit.///diff --git a/src/tableaux.rs b/src/tableaux.rsindex dccac846..4704b4c4 100644--- a/src/tableaux.rs+++ b/src/tableaux.rs@@ -56,6 +56,7 @@use std::collections::{BTreeSet, HashMap, HashSet};use std::sync::Arc;+use std::sync::atomic::{AtomicU64, Ordering};use std::time::Instant;use rayon::prelude::*;@@ -1442,18 +1443,72 @@ impl Verdict {}/// Why a tableau run stopped short of a decision.-#[derive(Debug, Clone, Copy, Default)]+// Not `Copy` any more: the step counter is an `Arc` so that the branches of one+// run share it. A `Copy` budget would hand every disjunct its own counter and+// bound nothing.+#[derive(Debug, Clone)]struct Budget {/// Wall-clock cut-off for a single satisfiability test.+ ///+ /// NONDETERMINISTIC by construction, which is why the step budget beside+ /// it exists. A run bounded only by a clock gives different answers on a+ /// fast machine and a loaded one, and `#161` is what that costs: a+ /// soundness test that failed roughly three runs in five against an+ /// unmodified baseline, which teaches a reader to discount red.deadline: Option<Instant>,+ /// Steps taken, SHARED across the branches of one run.+ ///+ /// The clock is here because the node and depth budgets do not bound the+ /// number of BRANCHES explored: a tableau can stay small and shallow while+ /// backtracking exponentially. This counts that work directly. It is an+ /// `Arc<AtomicU64>` and not a field because `Tableau` is cloned per+ /// disjunct, and a per-clone counter would reset at every branch and bound+ /// nothing at all.+ steps: Arc<AtomicU64>,+ /// The step ceiling, or `None` for no step bound.+ max_steps: Option<u64>,/// Set when any budget was hit during expansion.exhausted: bool,+ /// Which bound stopped the run, for the report. A run that ran out of+ /// steps and a run that ran out of time are different facts, and a caller+ /// deciding whether to retry with a bigger budget needs to know which.+ stopped_by: Option<&'static str>,+}++impl Default for Budget {+ fn default() -> Self {+ Budget {+ deadline: None,+ steps: Arc::new(AtomicU64::new(0)),+ max_steps: crate::runtime::tableaux_max_steps(),+ exhausted: false,+ stopped_by: None,+ }+ }}impl Budget {- fn expired(&self) -> bool {- self.deadline.is_some_and(|d| Instant::now() >= d)+ /// Charge one step and report whether any bound has been reached.+ ///+ /// Charging and testing are one call, and there is deliberately no way to+ /// do one without the other. A separate `expired()` invites a loop that+ /// tests without charging, which is how a step budget quietly stops+ /// bounding anything; this type had one and it is gone.+ fn spend(&mut self) -> bool {+ let n = self.steps.fetch_add(1, Ordering::Relaxed) + 1;+ if let Some(max) = self.max_steps+ && n >= max+ {+ self.stopped_by = Some("steps");+ return true;+ }+ if self.deadline.is_some_and(|d| Instant::now() >= d) {+ self.stopped_by = Some("time");+ return true;+ }+ false}+}#[derive(Clone)]@@ -1793,7 +1848,10 @@ impl Tableau {// Hitting a budget is NOT a clash. Record it so the caller can report// Unknown instead of asserting unsatisfiability, then unwind. The// `false` return here means only "this branch produced no model".- if depth > max_depth || self.nodes.len() > max_nodes || self.budget.expired() {+ // One step per call to `expand`, charged BEFORE the test, so the count+ // measures work attempted rather than work that happened to finish.+ let out_of_budget = self.budget.spend();+ if depth > max_depth || self.nodes.len() > max_nodes || out_of_budget {self.budget.exhausted = true;return false;}@@ -1805,7 +1863,9 @@ impl Tableau {// (every iteration re-runs blocking over every node), so a check// only at function entry lets one expansion overrun the budget// without bound.- if self.budget.expired() {+ // And one per turn of the fixpoint, which is where the expensive+ // work is: every iteration re-runs blocking over every node.+ if self.budget.spend() {self.budget.exhausted = true;return false;}@@ -1876,7 +1936,7 @@ impl Tableau {// unwind so the caller reports Unknown, not a fabricated answer.let max_nodes = crate::runtime::tableaux_max_nodes();for _ in 0..(n - matching) {- if self.nodes.len() > max_nodes || self.budget.expired() {+ if self.nodes.len() > max_nodes || self.budget.spend() {self.budget.exhausted = true;return false;}@@ -2046,6 +2106,9 @@ impl Tableau {// Carry the budget flag back: a branch that ran out// of room does not license "all merges clash".self.budget.exhausted |= branch.budget.exhausted;+ if self.budget.stopped_by.is_none() {+ self.budget.stopped_by = branch.budget.stopped_by;+ }}}return false; // All merges lead to clash@@ -2112,6 +2175,9 @@ impl Tableau {}// Same here: an exhausted disjunct is not a refuted one.self.budget.exhausted |= branch.budget.exhausted;+ if self.budget.stopped_by.is_none() {+ self.budget.stopped_by = branch.budget.stopped_by;+ }}return false; // All branches clash}@@ -3214,6 +3280,8 @@ impl DlReasoner {consistent: true,undecided: false,individuals_checked: 0,+ steps: 0,+ stopped_by: None,inferred_types: HashMap::new(),};}@@ -3256,6 +3324,8 @@ impl DlReasoner {undecided: abox_undecided,individuals_checked,inferred_types: inferred,+ steps: tableau.budget.steps.load(Ordering::Relaxed),+ stopped_by: tableau.budget.stopped_by,}}@@ -3690,6 +3760,18 @@ pub struct ABoxResult {pub undecided: bool,pub individuals_checked: usize,pub inferred_types: HashMap<u32, HashSet<u32>>,+ /// Expansion steps this run took.+ ///+ /// The same ontology takes the same number on every machine, which is what+ /// makes a step budget a budget rather than a race. A test can assert on+ /// this; a clock-bounded run has no such number.+ pub steps: u64,+ /// Which budget stopped the run, if one did: `"steps"` or `"time"`.+ ///+ /// `undecided` alone says a run was cut short and not which bound cut it.+ /// Those call for different responses, and a reader deciding whether to+ /// raise a limit needs to know which limit.+ pub stopped_by: Option<&'static str>,}pub struct ClassificationResult {diff --git a/tests/tableau_budget_determinism_test.rs b/tests/tableau_budget_determinism_test.rsnew file mode 100644index 00000000..bf28c09d--- /dev/null+++ b/tests/tableau_budget_determinism_test.rs@@ -0,0 +1,131 @@+//! **A verdict must not depend on how fast the machine is (#161).**+//!+//! `reasoner_soundness_test::direct_role_clash_is_detected_control` failed+//! about three runs in five against an unmodified baseline. The cause was that+//! the only bound on tableau BRANCHING was a wall clock: the node and depth+//! budgets cap how big and how deep a tableau gets, and cap nothing about how+//! many branches are explored, so a run that finished on an idle machine ran+//! out of time on a busy one and came back `undecided`.+//!+//! A wall-clock-dependent test in a repository that sells verification is worse+//! than a missing test, because it teaches a reader to discount red.+//!+//! The fix is a deterministic budget beside the clock: expansion steps, shared+//! across the branches of one run through an `Arc<AtomicU64>` so that cloning a+//! tableau per disjunct does not reset the count. These tests are the gate on+//! that. They assert the property directly — the same ontology takes the SAME+//! number of steps, every time — rather than running the flaky test a few more+//! times and hoping.++use open_ontologies::graph::GraphStore;+use open_ontologies::tableaux::DlReasoner;+use std::sync::Arc;++/// The same preamble `reasoner_soundness_test` uses, declarations included.+/// The first version of this file left `ex:D`, `ex:E` and `ex:r` undeclared and+/// the clash went undetected, which looked like the budget change having broken+/// the reasoner and was a broken fixture.+const PREFIXES: &str = 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:D a owl:Class . ex:E a owl:Class . ex:D owl:disjointWith ex:E .+ex:r a owl:ObjectProperty . ex:s a owl:ObjectProperty ; owl:inverseOf ex:r .+"#;++/// The ontology from the flaky test, plus disjointness so there is a real+/// clash to find and real branching on the way.+const CLASHING: &str = r#"+ex:B a owl:Class ; rdfs:subClassOf+ [ a owl:Restriction ; owl:onProperty ex:r ; owl:allValuesFrom ex:D ] .+ex:a a ex:B ; ex:r ex:b .+ex:b a ex:E .+"#;++/// Something with genuine disjunction, so the count covers backtracking rather+/// than a straight line. A budget that only ever sees deterministic expansion+/// would not be measuring the thing the clock was there to bound.+const BRANCHING: &str = r#"+ex:P1 a owl:Class . ex:P2 a owl:Class .+ex:Q1 a owl:Class . ex:Q2 a owl:Class .+ex:R1 a owl:Class . ex:R2 a owl:Class .+ex:N a owl:Class .+ex:P a owl:Class ; owl:unionOf ( ex:P1 ex:P2 ) .+ex:Q a owl:Class ; owl:unionOf ( ex:Q1 ex:Q2 ) .+ex:R a owl:Class ; owl:unionOf ( ex:R1 ex:R2 ) .+ex:N owl:disjointWith ex:P1 . ex:N owl:disjointWith ex:P2 .+ex:S a owl:Class ; rdfs:subClassOf ex:P , ex:Q , ex:R , ex:N .+ex:thing a ex:S .+"#;++fn run(body: &str) -> (bool, bool, u64) {+ let store = Arc::new(GraphStore::new());+ store+ .load_turtle(&format!("{PREFIXES}{body}"), None)+ .expect("ontology must parse");+ let r = DlReasoner::from_graph(&store).expect("reasoner");+ let a = r.check_abox();+ (a.consistent, a.undecided, a.steps)+}++#[test]+fn the_same_ontology_takes_the_same_number_of_steps_every_time() {+ for (name, body) in [("clashing", CLASHING), ("branching", BRANCHING)] {+ let runs: Vec<_> = (0..6).map(|_| run(body)).collect();+ let first = runs[0];+ assert!(+ runs.iter().all(|r| *r == first),+ "{name}: six runs of one ontology did not agree. A verdict that moves between \+ runs of the same input is the defect #161 recorded, and the step count is what \+ makes it visible: {runs:?}"+ );+ assert!(+ first.2 > 0,+ "{name}: the run took zero steps, so this test is measuring nothing"+ );+ }+}++/// The counter has to survive branching. It lives in an `Arc` because `Tableau`+/// is cloned per disjunct, and a per-clone counter would reset at every branch+/// and bound nothing at all. If that regresses, the branching ontology stops+/// costing more than the straight-line one.+#[test]+fn branching_costs_more_steps_than_a_straight_line() {+ let (_, _, straight) = run(CLASHING);+ let (_, _, branching) = run(BRANCHING);+ assert!(+ branching > straight,+ "a disjunctive ontology took {branching} steps against {straight} for a \+ straight-line one. The counter is not surviving the per-disjunct clone, so it \+ bounds nothing."+ );+}++/// The clash is still found. A deterministic budget that made the reasoner stop+/// answering would be a worse bug than the one it fixes.+#[test]+fn the_clash_is_still_detected_and_the_run_is_not_cut_short() {+ let (consistent, undecided, steps) = run(CLASHING);+ assert!(!undecided, "the run was cut short after {steps} steps");+ assert!(+ !consistent,+ "the direct-role clash was not found, so the budget change broke the reasoner"+ );+}++/// The corpus fits far inside the default, and the number is here so a future+/// reader can see the headroom rather than take 5,000,000 on trust.+#[test]+fn the_default_step_budget_has_real_headroom() {+ let (_, _, a) = run(CLASHING);+ let (_, _, b) = run(BRANCHING);+ let worst = a.max(b);+ assert!(+ worst < 50_000,+ "the worst ontology here now takes {worst} steps. The default is a backstop \+ against exponential backtracking, not a working limit; if real work is \+ approaching it, raise the default deliberately rather than letting runs start \+ coming back undecided."+ );+}