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
feat(temporal): close the transaction interval with recordedUntil (#115)
Nicolas2077305fbf28
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d85f8aae..70916905 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,25 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]### Fixed+- **`temporal:recordedUntil` closes the transaction interval, so `as_of`+ answers what was believed then.** The recorded axis only ever narrowed+ forward: with no upper bound, `as_of = now` returned the union of every+ version ever recorded rather than the current belief, and after the first+ correction a snapshot showed an assertion beside the one that replaced it.+ `validities()` now reads the predicate as a fourth UNION branch and+ `recorded_by` is two-sided, half-open like `[validFrom, validTo)`.++ Exclusions are reported on the side they fall: a graph recorded after the+ audit instant still says `not yet recorded then`, one whose recorded interval+ has closed says `no longer recorded then`. Those are opposite facts and a+ single reason string flattened them.++ Additive. A store that does not write `recordedUntil` is unchanged, including+ its cap arithmetic — the validity scan counts ROWS, so only a graph that+ actually carries the fourth predicate costs a fourth row. For stores that do,+ the 20,000-row cap covers roughly 5,000 fully described graphs where it+ covered roughly 6,700 with three predicates; there is a test that proves the+ cost rather than asserting it in a comment.- **`open-ontologies-lite` no longer installs an MCP server with the library**(released as 0.5.0). `mcp` was a core dependency of a package that imports itin exactly one module, `server.py`, so every consumer of the library APIdiff --git a/CLAUDE.md b/CLAUDE.mdindex 2cd696fd..b12ac399 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -95,7 +95,7 @@ Claude dynamically decides the next tool call based on what the previous tool re| `onto_support_report` | To summarise provenance quality: unsourced-claim rate over the graph, support rate across the claims judged so far || `onto_pack` | To write the loaded graph and its verification evidence to a portable versioned artifact: sorted N-Triples, a manifest (name, version, counts, timestamp, tool version, sha256) and the lint/enforce results recorded at pack time. What you promote between environments is then a graph that has already passed its checks, with the evidence attached || `onto_unpack` | To load a pack, refusing it if the checksum does not match. `verify_only` inspects the manifest and evidence without loading |-| `onto_temporal_snapshot` | To see which named graphs are in scope at a point in time. Two independent clocks: `valid_at` asks what was TRUE then, `as_of` asks what was KNOWN then. Graphs without validity metadata are timeless and always in scope, so the vocabulary is additive to an existing store |+| `onto_temporal_snapshot` | To see which named graphs are in scope at a point in time. Two independent clocks: `valid_at` asks what was TRUE then, `as_of` asks what was KNOWN then. Both intervals are half-open — `temporal:recordedUntil` closes the recorded one, so `as_of` answers what was believed then rather than everything recorded by then. Graphs without validity metadata are timeless and always in scope, so the vocabulary is additive to an existing store || `onto_temporal_query` | To run a SPARQL graph pattern against only the graphs in temporal scope: what the graph said at a given valid time, as known at a given recorded time || `onto_temporal_conflicts` | To separate genuine contradictions from corrections. A disjointness violation only counts when the two assertions claim OVERLAPPING validity; where one period ends as the other begins, the pair is superseded history, not a conflict || `onto_lineage` | To view the session's lineage trail (plan → enforce → apply → monitor → drift) |diff --git a/src/inputs.rs b/src/inputs.rsindex 5b06f829..0334dabc 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -1168,7 +1168,9 @@ pub struct OntoReasonIncrementalInput {pub struct OntoTemporalSnapshotInput {/// Instant to evaluate validity at, e.g. "2026-03-01". Omit for any time.pub valid_at: Option<String>,- /// Only consider what was recorded by this instant. Omit for everything known.+ /// Only consider what was BELIEVED at this instant: recorded by then and not+ /// retired by then. An assertion whose temporal:recordedUntil has passed is+ /// excluded rather than carried forward. Omit for everything known.pub as_of: Option<String>,}@@ -1178,6 +1180,7 @@ pub struct OntoTemporalQueryInput {pub pattern: String,/// Instant to evaluate validity atpub valid_at: Option<String>,- /// Only consider what was recorded by this instant+ /// Only consider what was BELIEVED at this instant: recorded by then and not+ /// retired by then (temporal:recordedUntil closes the interval)pub as_of: Option<String>,}diff --git a/src/server.rs b/src/server.rsindex eb025a37..f23f5950 100644--- a/src/server.rs+++ b/src/server.rs@@ -1010,7 +1010,7 @@ impl OpenOntologiesServer {}}- #[tool(name = "onto_temporal_snapshot", description = "Which named graphs are in scope at a point in time, and which are excluded and why. Two independent clocks: valid_at asks what was TRUE then, as_of asks what was KNOWN then. Assertions live in named graphs described in the default graph with temporal:validFrom, validTo and recordedAt; a graph with no description is timeless and always in scope. The scans are capped: `complete` says whether they finished, and a run that was cut short also carries `truncated` and a `warning`, because a truncated validity scan makes this partition wrong rather than merely short.")]+ #[tool(name = "onto_temporal_snapshot", description = "Which named graphs are in scope at a point in time, and which are excluded and why. Two independent clocks: valid_at asks what was TRUE then, as_of asks what was KNOWN then. Assertions live in named graphs described in the default graph with temporal:validFrom, validTo, recordedAt and recordedUntil; a graph with no description is timeless and always in scope. Both intervals are half-open, so an assertion whose recordedUntil has passed is excluded as no longer believed instead of being carried forward beside the correction that replaced it. The scans are capped: `complete` says whether they finished, and a run that was cut short also carries `truncated` and a `warning`, because a truncated validity scan makes this partition wrong rather than merely short.")]async fn onto_temporal_snapshot(&self, Parameters(input): Parameters<OntoTemporalSnapshotInput>) -> String {use crate::temporal::Temporal;match Temporal::new(self.graph.clone()).snapshot(input.valid_at.as_deref(), input.as_of.as_deref()) {diff --git a/src/temporal.rs b/src/temporal.rsindex 34c771ae..7aec84fc 100644--- a/src/temporal.rs+++ b/src/temporal.rs@@ -25,20 +25,30 @@//! {//! :g1 t:validFrom "2024-01-01"^^xsd:date ;//! t:validTo "2026-05-01"^^xsd:date ;-//! t:recordedAt "2024-01-05"^^xsd:dateTime .+//! t:recordedAt "2024-01-05"^^xsd:dateTime ;+//! t:recordedUntil "2026-05-02"^^xsd:dateTime .//! :g2 t:validFrom "2026-05-01"^^xsd:date ;//! t:recordedAt "2026-05-02"^^xsd:dateTime .//! }//! ```//!//! An absent `validFrom` means "since always", an absent `validTo` means-//! "still true", and a graph with no temporal description at all is timeless:-//! it is in scope for every snapshot, so adding this vocabulary to an-//! existing store changes nothing until it is used.+//! "still true", an absent `recordedUntil` means "still believed", and a graph+//! with no temporal description at all is timeless: it is in scope for every+//! snapshot, so adding this vocabulary to an existing store changes nothing+//! until it is used.//!-//! Intervals are half-open, `[validFrom, validTo)`. Two facts that meet at a-//! boundary do not overlap, which is what makes "adherent until May,-//! suspension from May" a correction rather than a contradiction.+//! Intervals are half-open on both axes, `[validFrom, validTo)` and+//! `[recordedAt, recordedUntil)`. Two facts that meet at a boundary do not+//! overlap, which is what makes "adherent until May, suspension from May" a+//! correction rather than a contradiction.+//!+//! Closing the recorded interval is what lets `as_of` answer "what did we+//! believe THEN" instead of "everything we had ever recorded by then". With no+//! upper bound the transaction axis only narrows forward, so a corrected+//! assertion keeps turning up in every later snapshot beside the correction+//! that replaced it, and the audit question this module exists to answer stops+//! being answerable after the first correction.//!//! ## Bounded scans//!@@ -64,9 +74,11 @@ pub struct Temporal {limits: Limits,}-/// Validity ROWS, not graphs. The query is a three-way UNION, so a graph-/// carrying validFrom, validTo and recordedAt costs three rows: the cap is-/// reached at roughly 6,700 fully described graphs.+/// Validity ROWS, not graphs. The query is a four-way UNION, so a graph+/// carrying validFrom, validTo, recordedAt and recordedUntil costs four rows:+/// the cap is reached at roughly 5,000 fully described graphs, where a+/// three-predicate store still reaches it at roughly 6,700. A store that never+/// writes recordedUntil pays nothing for it — the cap counts rows, not graphs.const VALIDITY_SCAN_LIMIT: usize = 20_000;/// Distinct named graphs holding assertions.const GRAPH_SCAN_LIMIT: usize = 20_000;@@ -193,6 +205,7 @@ pub struct Validity {pub valid_from: Option<String>,pub valid_to: Option<String>,pub recorded_at: Option<String>,+ pub recorded_until: Option<String>,}impl Validity {@@ -202,9 +215,22 @@ impl Validity {&& self.valid_to.as_deref().is_none_or(|t| instant < t)}- /// Had we recorded it by `instant`.- fn recorded_by(&self, instant: &str) -> bool {- self.recorded_at.as_deref().is_none_or(|r| r <= instant)+ /// Was this believed at `instant`, on the half-open recorded interval+ /// `[recordedAt, recordedUntil)` — and if not, on which side it fell.+ ///+ /// This is the two-sided form of what used to be `recorded_by`. Adding the+ /// closing bound gives the predicate a second way to fail, and the two are+ /// opposite facts about the assertion: one has not been recorded yet, the+ /// other is no longer believed. A bool would flatten them back together at+ /// the only place that has to tell them apart, so it returns the reason.+ fn not_recorded_at(&self, instant: &str) -> Option<&'static str> {+ if self.recorded_at.as_deref().is_some_and(|r| instant < r) {+ return Some("not yet recorded then");+ }+ if self.recorded_until.as_deref().is_some_and(|u| u <= instant) {+ return Some("no longer recorded then");+ }+ None}/// Do two validity periods share any instant. Half-open, so touching@@ -290,9 +316,10 @@ impl Temporal {/// found them was complete.fn validities(&self) -> anyhow::Result<(BTreeMap<String, Validity>, Capped)> {let query = format!(- "SELECT ?g ?from ?to ?rec WHERE {{ \+ "SELECT ?g ?from ?to ?rec ?until WHERE {{ \{{ ?g <{NS}validFrom> ?from }} UNION {{ ?g <{NS}validTo> ?to }} \- UNION {{ ?g <{NS}recordedAt> ?rec }} }}"+ UNION {{ ?g <{NS}recordedAt> ?rec }} \+ UNION {{ ?g <{NS}recordedUntil> ?until }} }}");let scan = self.rows(&query, self.limits.validity_scan)?;let mut out: BTreeMap<String, Validity> = BTreeMap::new();@@ -305,6 +332,7 @@ impl Temporal {valid_from: None,valid_to: None,recorded_at: None,+ recorded_until: None,});if let Some(v) = row.get("from").and_then(|v| v.as_str()) {entry.valid_from = Some(plain(v));@@ -315,6 +343,9 @@ impl Temporal {if let Some(v) = row.get("rec").and_then(|v| v.as_str()) {entry.recorded_at = Some(plain(v));}+ if let Some(v) = row.get("until").and_then(|v| v.as_str()) {+ entry.recorded_until = Some(plain(v));+ }}Ok((out, scan.capped))}@@ -357,15 +388,22 @@ impl Temporal {}Some(v) => {let valid_ok = valid_at.is_none_or(|t| v.valid_at(t));- let recorded_ok = as_of.is_none_or(|t| v.recorded_by(t));- if valid_ok && recorded_ok {+ // Which side of the recorded interval `as_of` fell on, not+ // merely that it fell outside: "recorded later" and "no+ // longer believed" are opposite facts about the assertion.+ let recorded_miss = as_of.and_then(|t| v.not_recorded_at(t));+ if valid_ok && recorded_miss.is_none() {in_scope.push(serde_json::json!({"graph": g, "valid": v.describe()}));names.push(g.clone());} else {excluded.push(serde_json::json!({"graph": g,"valid": v.describe(),- "reason": if !valid_ok { "not true at that instant" } else { "not yet recorded then" },+ "reason": if !valid_ok {+ "not true at that instant"+ } else {+ recorded_miss.unwrap_or("not yet recorded then")+ },}));}}@@ -519,6 +557,7 @@ impl Temporal {valid_from: None,valid_to: None,recorded_at: None,+ recorded_until: None,};let va = validities.get(&ga).unwrap_or(&timeless);let vb = validities.get(&gb).unwrap_or(&timeless);@@ -607,6 +646,20 @@ ex:g3 { ex:X ex:p ex:three . }ex:g2 t:validFrom "2025-01-01" .ex:g3 t:validFrom "2026-01-01" .}+"#;++ /// One graph carrying all four predicates. The scan cap is denominated in+ /// ROWS, so this is what a fully described graph costs.+ const FULLY_DESCRIBED: &str = r#"+@prefix ex: <http://example.org/> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g1 { ex:X ex:p ex:one . }++{+ ex:g1 t:validFrom "2024-01-01" ; t:validTo "2026-01-01" ;+ t:recordedAt "2024-01-05" ; t:recordedUntil "2026-01-06" .+}"#;/// A correction: one type up to a boundary, a disjoint one from it.@@ -697,6 +750,37 @@ ex:g_after { ex:X a ex:Suspension . }assert!(snap.get("truncated").is_none(), "{snap}");}+ /// The row cost of the fourth predicate, proved rather than documented.+ /// A fully described graph used to fit in three rows and now needs four,+ /// which is the whole of what `recordedUntil` does to the cap: 20,000 rows+ /// covers roughly 5,000 such graphs instead of roughly 6,700. A store that+ /// never writes the predicate is untouched — nothing here counts graphs.+ #[test]+ fn a_fully_described_graph_costs_four_validity_rows() {+ let cut = Temporal::with_limits(+ store(FULLY_DESCRIBED),+ Limits {+ validity_scan: 3,+ ..Limits::default()+ },+ );+ let snap = json(cut.snapshot(None, None).unwrap());+ assert_eq!(+ snap["complete"], false,+ "three rows no longer cover one four-predicate graph: {snap}"+ );++ let whole = Temporal::with_limits(+ store(FULLY_DESCRIBED),+ Limits {+ validity_scan: 4,+ ..Limits::default()+ },+ );+ let snap = json(whole.snapshot(None, None).unwrap());+ assert_eq!(snap["complete"], true, "four rows do: {snap}");+ }+/// The case that has to be loud. Every graph in the fixture is described,/// so a graph the snapshot calls timeless is provably a misclassification.#[test]diff --git a/tests/temporal_conformance_test.rs b/tests/temporal_conformance_test.rsindex 8c44d88d..431e768b 100644--- a/tests/temporal_conformance_test.rs+++ b/tests/temporal_conformance_test.rs@@ -55,6 +55,22 @@ fn snapshot(t: &Temporal, valid_at: Option<&str>, as_of: Option<&str>) -> serde_serde_json::from_str(&t.snapshot(valid_at, as_of).unwrap()).unwrap()}+/// The reason a snapshot gives for excluding one graph, named by its local+/// part. Panics rather than returning an Option: every caller is asserting on+/// the reason, so a missing row is a failed test, not an empty string.+fn reason(snapshot: &serde_json::Value, local: &str) -> String {+ let row = snapshot["excluded"]+ .as_array()+ .unwrap_or_else(|| panic!("snapshot has no array `excluded`: {snapshot}"))+ .iter()+ .find(|row| row["graph"].as_str().is_some_and(|g| g.ends_with(local)))+ .unwrap_or_else(|| panic!("`{local}` is not excluded: {snapshot}"));+ row["reason"]+ .as_str()+ .unwrap_or_else(|| panic!("`{local}` carries no reason: {row}"))+ .to_string()+}+fn set(items: &[&str]) -> BTreeSet<String> {items.iter().map(|s| s.to_string()).collect()}@@ -159,6 +175,104 @@ fn as_of_hides_a_fact_recorded_after_the_cutoff() {assert!(graphs(&after, "in_scope").contains("g_adherent"));}+/// A correction on the recorded axis alone: both graphs claim the same valid+/// period, and the first was believed only until the second replaced it. This+/// is the shape `as_of` exists for, and it needs a closing bound to work — with+/// an open transaction interval both graphs answer every later audit.+const CORRECTED: &str = r#"+@prefix ex: <http://example.org/> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g_first { ex:HEK293 a ex:AdherentCellLine . }+ex:g_fix { ex:HEK293 a ex:SuspensionCellLine . }++{+ ex:g_first t:validFrom "2024-01-01" ; t:recordedAt "2024-01-05" ; t:recordedUntil "2026-05-02" .+ ex:g_fix t:validFrom "2024-01-01" ; t:recordedAt "2026-05-02" .+}+"#;++#[test]+fn as_of_before_a_correction_sees_what_was_believed_then() {+ let t = temporal(CORRECTED);+ let snap = snapshot(&t, None, Some("2025-06-01"));+ assert_eq!(graphs(&snap, "in_scope"), set(&["g_first"]));+ assert_eq!(graphs(&snap, "excluded"), set(&["g_fix"]));+ assert_eq!(+ reason(&snap, "g_fix"),+ "not yet recorded then",+ "the successor had not been recorded at that instant"+ );+}++#[test]+fn as_of_after_a_correction_drops_the_assertion_it_replaced() {+ let t = temporal(CORRECTED);+ let snap = snapshot(&t, None, Some("2026-06-01"));+ // Without recordedUntil both graphs answer here, because `as_of` only ever+ // narrowed forward: the audit would show the corpus asserting two disjoint+ // types of the same subject and no way to tell which one was believed.+ assert_eq!(graphs(&snap, "in_scope"), set(&["g_fix"]));+ assert_eq!(graphs(&snap, "excluded"), set(&["g_first"]));+ assert_eq!(+ reason(&snap, "g_first"),+ "no longer recorded then",+ "an assertion whose recorded interval has closed is not merely \+ unrecorded yet — the two exclusions are opposite facts"+ );+}++#[test]+fn recorded_interval_is_half_open_at_the_upper_bound() {+ let t = temporal(CORRECTED);+ // Exactly at the bound. Half-open on both axes, so the predecessor is+ // already out and the successor is already in, and the handover leaves no+ // instant where both are believed or neither is.+ let snap = snapshot(&t, None, Some("2026-05-02"));+ assert_eq!(graphs(&snap, "in_scope"), set(&["g_fix"]));+ assert_eq!(graphs(&snap, "excluded"), set(&["g_first"]));++ // One instant earlier, the other way round.+ let before = snapshot(&t, None, Some("2026-05-01"));+ assert_eq!(graphs(&before, "in_scope"), set(&["g_first"]));+}++/// The failure this has to catch is not a wrong answer, it is a graph quietly+/// reclassified as timeless. `validities()` builds its map from the predicates+/// it queries, and `scope()` puts anything absent from that map into `in_scope`+/// as "no validity recorded, timeless" — that is, ALWAYS TRUE. So a predicate+/// added to the vocabulary and not added to the UNION does not merely go+/// unread: it turns the assertion it describes into an eternal one, which is+/// the worst available default for a bound that exists to withdraw something.+///+/// This test fails on `recordedUntil` before the UNION carries it, and it will+/// fail the same way for the fifth predicate someone adds without wiring.+#[test]+fn every_temporal_predicate_takes_its_graph_out_of_the_timeless_bucket() {+ for predicate in ["validFrom", "validTo", "recordedAt", "recordedUntil"] {+ let trig = format!(+ "@prefix ex: <http://example.org/> .\n\+ @prefix t: <https://open-ontologies.org/temporal#> .\n\+ ex:g_only {{ ex:HEK293 a ex:AdherentCellLine . }}\n\+ {{ ex:g_only t:{predicate} \"2024-01-01\" . }}\n"+ );+ let snap = snapshot(&temporal(&trig), None, None);+ let row = snap["in_scope"]+ .as_array()+ .unwrap()+ .iter()+ .chain(snap["excluded"].as_array().unwrap().iter())+ .find(|row| row["graph"].as_str().is_some_and(|g| g.ends_with("g_only")))+ .unwrap_or_else(|| panic!("g_only is in neither bucket for `{predicate}`: {snap}"));+ assert_ne!(+ row["reason"].as_str(),+ Some("no validity recorded, timeless"),+ "`{predicate}` does not populate the validity map, so a graph \+ described only by it reads as timeless and always in scope"+ );+ }+}+/// A described graph with an open start: no `validFrom`, only a `validTo`.const OPEN_START: &str = r#"@prefix ex: <http://example.org/> .@@ -459,7 +573,7 @@ ex:g_multi { ex:X a ex:A . }fn accidental_multi_valued_bound_resolves_to_one_row_instead_of_failing() {let t = temporal(MULTI_VALUED_BOUND);// ACCIDENTAL: `validities()` overwrites the field on every row of the- // 3-way UNION, so one of the two values wins and the other vanishes. Which+ // 4-way UNION, so one of the two values wins and the other vanishes. Which// one is whichever the UNION yields last — today that is 2024-01-01, but// nothing in the query contracts that order, which is the defect.// AFTER item 4: the graph is INVALID, both values are listed in the reason,