Skip to content

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

fix(temporal): a period that holds at no instant overlaps nothing (#124)

Nicolase8ac378e91a1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2d4804b2..03f3bde4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -147,6 +147,39 @@ All notable changes to Open Ontologies are documented here.
behind no flag, carrying exactly the same rows until 2.0. Deprecated, not
renamed: when lineage-backed supersession arrives it takes a new key, so no
key ever names a different set on either side of a major version.
+- **A period that holds at no instant no longer overlaps anything** (#118).
+ `Period::overlaps` answered true for `[t, t)` against any period containing
+ `t`, and unconditionally against an open one, while `valid_at` was false at
+ every instant for it, so `onto_temporal_conflicts` filed such a graph as a
+ live contradiction where `onto_temporal_snapshot` excluded it everywhere; an
+ inverted `[t2, t1)` with `t2 > t1` was filed as `non_overlapping`, a graph
+ that holds nowhere presented beside a live one. The case that made it worth
+ fixing is the one parsing created: `validFrom "2024"^^xsd:gYear` beside
+ `validTo "2024-01-01"^^xsd:date` is two careful assertions from two systems
+ writing at different precision, invisible on inspection, and it resolved as
+ sound. The classification now happens once, where the bounds are read:
+ `Bounds::resolve` yields a third `GraphValidity` beside sound and
+ unreadable, the snapshot answers from the variant, `overlaps` from the flag
+ the period carries, `valid_at` is never asked about such a period, and the
+ two tools agree by construction. With no `valid_at` such a graph is in scope
+ like any other, because no instant was asked about and narrowing an
+ atemporal query silently is worse than answering it, so `onto_temporal_query`
+ with no `valid_at` still reads it; at any instant asked about it is excluded.
+ Validity is checked before the recorded side: with a `valid_at` given,
+ "holds at no instant" beats "not yet recorded then" whatever `as_of` is
+ passed, since only the first is a fact about the data rather than about the
+ query; with none given, the recorded reason is the only one that can apply.
+
+ Not `invalid`: both bounds parsed, and every reason in that array says a
+ bound could not be read. The graph is EXCLUDED at every instant asked about,
+ with a reason that says it holds at no instant and names which of the two it
+ is, since validFrom equalling validTo is sometimes intended and validTo
+ preceding validFrom almost never is. In
+ `conflicts` the pair lands in `non_overlapping`, a true statement that since
+ the rename above claims no correction, and the `note` says the bucket can
+ hold such a period. The recorded axis is not classified this way here:
+ `recordedUntil` before `recordedAt` is out-of-order recording (#109) and
+ lands separately.
- **`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 it
diff --git a/src/server.rs b/src/server.rs
index 1239faa4..ff3699b9 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, 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. Bounds on all four axes are read as instants on the UTC timeline from xsd:date, xsd:dateTime, xsd:gYearMonth or xsd:gYear; a less precise bound names the FIRST instant of its period, and a value with no timezone offset is UTC. A bound matching none of those, or two different instants on one axis, makes the graph INVALID: reported in `invalid` with a reason, never in scope and never timeless. 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. Bounds on all four axes are read as instants on the UTC timeline from xsd:date, xsd:dateTime, xsd:gYearMonth or xsd:gYear; a less precise bound names the FIRST instant of its period, and a value with no timezone offset is UTC. A bound matching none of those, or two different instants on one axis, makes the graph INVALID: reported in `invalid` with a reason, never in scope and never timeless. A graph whose validFrom and validTo both read but together hold at no instant (the same instant twice, or validTo before validFrom) is not invalid: it is excluded at every instant asked about, with a reason naming which of the two it is; with no valid_at it is in scope like any other graph. 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()) {
@@ -1024,7 +1024,7 @@ impl OpenOntologiesServer {
}
}
- #[tool(name = "onto_temporal_query", description = "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. Pass the body of a WHERE clause as `pattern`. valid_at and as_of are read as instants on the UTC timeline (xsd:date, xsd:dateTime, xsd:gYearMonth or xsd:gYear; no offset means UTC) and an unreadable one is refused rather than ignored. Graphs whose own bounds could not be read are out of scope and listed in `invalid`. `complete` is false when the result list was cut at its cap or when the scope it ran over was, and `truncated` says which; only the second case is a wrong answer, and it carries a `warning`.")]
+ #[tool(name = "onto_temporal_query", description = "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. Pass the body of a WHERE clause as `pattern`. valid_at and as_of are read as instants on the UTC timeline (xsd:date, xsd:dateTime, xsd:gYearMonth or xsd:gYear; no offset means UTC) and an unreadable one is refused rather than ignored. Graphs whose own bounds could not be read are out of scope and listed in `invalid`. A graph whose bounds read but hold at no instant (validFrom and validTo the same instant, or validTo before validFrom) is out of scope at any valid_at, as at every other instant, and onto_temporal_snapshot at that instant reports it under `excluded` with a reason naming which; with no valid_at it is read like any other graph, since no instant was asked about. `complete` is false when the result list was cut at its cap or when the scope it ran over was, and `truncated` says which; only the second case is a wrong answer, and it carries a `warning`.")]
async fn onto_temporal_query(&self, Parameters(input): Parameters<OntoTemporalQueryInput>) -> String {
use crate::temporal::Temporal;
match Temporal::new(self.graph.clone()).query_at(
@@ -1040,7 +1040,7 @@ impl OpenOntologiesServer {
}
}
- #[tool(name = "onto_temporal_conflicts", description = "Disjointness violations that claim OVERLAPPING validity, separated from those that do not. Without valid time a correction reads as a contradiction: an entity recorded one way until May and another after trips every check. This reports genuine disagreement about the same period as contradictions, and everything else as non_overlapping: pairs with no instant in common, judged on their bounds read as instants on the UTC timeline, so a timezone offset is honoured. That is all that is checked -- it is not evidence that one assertion replaced another, and the bucket also holds pairs separated by a GAP, which is missing coverage rather than history. The `superseded` key carries the same set under a name that claimed more than was proven; it is deprecated and will be dropped at 2.0. A pair whose graph has temporal metadata that could not be read is in neither bucket: it goes to `undecided`, because an unreadable period is not an open one and treating it as timeless would make it overlap everything. The scans are capped: `complete` says whether they finished, and if the validity scan was cut a `warning` marks the classification unsound, because a pair compared without its periods can appear here as a contradiction when it is a correction.")]
+ #[tool(name = "onto_temporal_conflicts", description = "Disjointness violations that claim OVERLAPPING validity, separated from those that do not. Without valid time a correction reads as a contradiction: an entity recorded one way until May and another after trips every check. This reports genuine disagreement about the same period as contradictions, and everything else as non_overlapping: pairs with no instant in common, judged on their bounds read as instants on the UTC timeline, so a timezone offset is honoured. That is all that is checked -- it is not evidence that one assertion replaced another, and the bucket also holds pairs separated by a GAP, which is missing coverage rather than history, and pairs where one period holds at no instant (empty or inverted), which onto_temporal_snapshot reports once with a reason naming which. The `superseded` key carries the same set under a name that claimed more than was proven; it is deprecated and will be dropped at 2.0. A pair whose graph has temporal metadata that could not be read is in neither bucket: it goes to `undecided`, because an unreadable period is not an open one and treating it as timeless would make it overlap everything. The scans are capped: `complete` says whether they finished, and if the validity scan was cut a `warning` marks the classification unsound, because a pair compared without its periods can appear here as a contradiction when it is a correction.")]
async fn onto_temporal_conflicts(&self) -> String {
use crate::temporal::Temporal;
match Temporal::new(self.graph.clone()).conflicts() {
diff --git a/src/temporal.rs b/src/temporal.rs
index 5350352a..b2ed1022 100644
--- a/src/temporal.rs
+++ b/src/temporal.rs
@@ -68,6 +68,17 @@
//! because "we hold no valid-time claim about this" and "the claim is garbage"
//! are different answers.
//!
+//! Two readable bounds can still name no instant: `validFrom` and `validTo`
+//! naming the same instant is an empty period, `validTo` before `validFrom`
+//! an inverted one. Neither is unreadable, and neither is a period something
+//! can overlap. The classification is made once, when the bounds are read,
+//! and every comparison answers from it, so a graph the snapshot excludes at
+//! every instant asked about is never a contradiction partner in `conflicts`.
+//! It is excluded with a reason naming which of the two it is: an empty period
+//! is sometimes intended, and an inverted one almost never is, and the text is
+//! the only place that distinction can survive. With no `valid_at` it is read
+//! like any other graph, because no instant was asked about.
+//!
//! ## Bounded scans
//!
//! Every query behind these tools is capped so a pathological store cannot
@@ -83,6 +94,7 @@
use crate::graph::GraphStore;
use chrono::{DateTime, Utc};
+use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
@@ -91,7 +103,9 @@ pub const NS: &str = "https://open-ontologies.org/temporal#";
/// Which comparison semantics produced an answer.
///
/// `temporal/1` was lexical string comparison of the bounds as written.
-/// `temporal/2` reads every bound as an instant on the UTC timeline. The same
+/// `temporal/2` reads every bound as an instant on the UTC timeline, and a
+/// period whose two bounds name no instant holds nowhere under it, in scope
+/// at no instant and overlapping nothing, where it used to overlap. The same
/// store answers differently under the two, so anything that replays or
/// records an answer, a snapshot manifest above all, has to carry this, or
/// two answers that cannot both be right hash identically.
@@ -263,6 +277,40 @@ struct Period {
to: Option<DateTime<Utc>>,
recorded: Option<DateTime<Utc>>,
until: Option<DateTime<Utc>>,
+ /// `Some` when the valid interval holds at no instant. Set once, where
+ /// the bounds are read, and consulted by every comparison: `overlaps`
+ /// compares two periods without seeing the `GraphValidity` each came
+ /// from, so the verdict has to travel on the period itself.
+ degenerate: Option<Degenerate>,
+}
+
+/// Why a period with two readable bounds holds at no instant.
+///
+/// Two variants rather than one, because the two are different facts about
+/// the data: an empty period is sometimes written on purpose, an inverted one
+/// almost never is, and the reason text is the only place that survives.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Degenerate {
+ /// `validFrom` and `validTo` name the same instant: `[t, t)` is empty.
+ Empty,
+ /// `validTo` names an instant before `validFrom`.
+ Inverted,
+}
+
+impl Degenerate {
+ /// The exclusion reason. Deliberately not the generic "not true at that
+ /// instant": that is accurate for a period that holds nowhere and useless,
+ /// because it reads as a period that holds somewhere else.
+ fn reason(self) -> &'static str {
+ match self {
+ Degenerate::Empty => {
+ "holds at no instant: validFrom and validTo name the same instant, an empty period"
+ }
+ Degenerate::Inverted => {
+ "holds at no instant: validTo precedes validFrom, an inverted period"
+ }
+ }
+ }
}
impl Period {
@@ -293,8 +341,17 @@ impl Period {
}
/// Do two validity periods share any instant. Half-open, so touching
- /// intervals do not overlap.
+ /// intervals do not overlap, and a period that holds at no instant shares
+ /// none with anything: the bound test below would answer true for `[t, t)`
+ /// against any period containing `t`, and unconditionally against an open
+ /// one, while `valid_at` is false everywhere for it. The classification is
+ /// made when the bounds are read: `scope` answers from the variant, this
+ /// answers from the flag the period carries, and `valid_at` is never asked
+ /// about a period that holds nowhere, so the two cannot disagree.
fn overlaps(&self, other: &Period) -> bool {
+ if self.degenerate.is_some() || other.degenerate.is_some() {
+ return false;
+ }
let start_before_end = |a: Option<DateTime<Utc>>, b: Option<DateTime<Utc>>| match (a, b) {
(Some(start), Some(end)) => start < end,
_ => true, // an open end never closes the interval
@@ -311,8 +368,15 @@ impl Period {
/// exactly how that happens.
#[derive(Clone, Debug)]
enum GraphValidity {
- /// Every bound the graph asserts was readable.
+ /// Every bound the graph asserts was readable, and the period holds
+ /// somewhere.
Sound(Period),
+ /// Every bound was readable, and together the valid bounds name no
+ /// instant. Not `Unreadable`: every reason in that bucket says a bound
+ /// could not be read, and a readable claim there would give the bucket a
+ /// second meaning. The period is kept so a row still shows the asserted
+ /// bounds; `kind` says which of the two shapes it is.
+ Degenerate { period: Period, kind: Degenerate },
/// At least one bound was not. "We hold no valid-time claim about this"
/// and "the claim is garbage" are different answers, and only the first
/// one is timeless.
@@ -359,6 +423,15 @@ impl Bounds {
/// it is a bound, and a bound that stayed a string beside three parsed
/// ones would close the interval where its text sorts rather than where
/// its instant falls.
+ ///
+ /// Then classify the valid interval, here and nowhere else. Two readable
+ /// bounds that name no instant between them make the graph `Degenerate`,
+ /// and every consumer answers from that verdict rather than rediscovering
+ /// it: a guard inside `overlaps` would be the same `None`-means-open
+ /// mistake the enum exists to prevent, one precision down. The recorded
+ /// axis is NOT classified this way: `recordedUntil` before `recordedAt`
+ /// is out-of-order recording (#109), which is a different question and
+ /// lands separately.
fn resolve(self, graph: String) -> GraphValidity {
let mut faults = Vec::new();
let from = settle("validFrom", self.from, &mut faults);
@@ -368,7 +441,15 @@ impl Bounds {
if !faults.is_empty() {
return GraphValidity::Unreadable(faults);
}
- GraphValidity::Sound(Period {
+ let degenerate = match (&from, &to) {
+ (Some(f), Some(t)) => match f.instant.cmp(&t.instant) {
+ Ordering::Equal => Some(Degenerate::Empty),
+ Ordering::Greater => Some(Degenerate::Inverted),
+ Ordering::Less => None,
+ },
+ _ => None, // an open end always leaves instants inside
+ };
+ let period = Period {
shown: Validity {
graph,
valid_from: from.as_ref().map(|b| b.lexical.clone()),
@@ -380,7 +461,12 @@ impl Bounds {
to: to.map(|b| b.instant),
recorded: recorded.map(|b| b.instant),
until: until.map(|b| b.instant),
- })
+ degenerate,
+ };
+ match degenerate {
+ Some(kind) => GraphValidity::Degenerate { period, kind },
+ None => GraphValidity::Sound(period),
+ }
}
}
@@ -1020,7 +1106,9 @@ impl Temporal {
let mut invalid = Vec::new();
let mut names = Vec::new();
for g in &graphs {
- match validities.get(g) {
+ // The readable period, and which shape it is when it holds at no
+ // instant. The two verdicts that are not a period answer here.
+ let (p, kind) = match validities.get(g) {
// Undescribed graphs are timeless and always in scope, so
// this vocabulary is additive to an existing store.
None => {
@@ -1028,35 +1116,60 @@ impl Temporal {
serde_json::json!({"graph": g, "reason": "no validity recorded, timeless"}),
);
names.push(g.clone());
+ continue;
}
// Described, but the description could not be read. Never in
// scope and never timeless: "we hold no valid-time claim about
// this" and "the claim is garbage" are different answers.
- Some(GraphValidity::Unreadable(faults)) => invalid.push(serde_json::json!({
+ Some(GraphValidity::Unreadable(faults)) => {
+ invalid.push(serde_json::json!({
+ "graph": g,
+ "reason": GraphValidity::fault_reason(faults),
+ }));
+ continue;
+ }
+ Some(GraphValidity::Sound(p)) => (p, None),
+ // Readable, and holds at no instant. With no valid_at it is
+ // read like any other graph: no instant was asked about, and
+ // narrowing an atemporal query silently is worse than
+ // answering it. At any instant asked about it is excluded,
+ // with a reason naming which of the two shapes it is, since
+ // the row's `valid` shows bounds that can look perfectly
+ // ordinary at a glance; so onto_temporal_snapshot at any
+ // valid_at reports it once. From here on it takes the sound
+ // graph's path, validity first and the recorded side second:
+ // with a valid_at given, "holds at no instant" beats "not yet
+ // recorded then", because the first is a fact about the data
+ // and the second a fact about the query, and only the first
+ // is the thing to fix; with none given, the recorded side is
+ // the only question asked, and its reason the only one that
+ // can apply. `conflicts` is unaffected: `overlaps` answers
+ // false for such a period regardless.
+ Some(GraphValidity::Degenerate { period, kind }) => (period, Some(*kind)),
+ };
+ // A period that holds at no instant is never valid at one, and
+ // `valid_at` is not asked about it: the half-open test already
+ // answers false for `from >= to`, and the guard keeps that so
+ // even if a `<=` slip there let such a period hold for one
+ // instant.
+ let valid_ok = valid_at.is_none_or(|t| kind.is_none() && p.valid_at(t));
+ // 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| p.not_recorded_at(t));
+ if valid_ok && recorded_miss.is_none() {
+ in_scope.push(serde_json::json!({"graph": g, "valid": p.shown.describe()}));
+ names.push(g.clone());
+ } else {
+ excluded.push(serde_json::json!({
"graph": g,
- "reason": GraphValidity::fault_reason(faults),
- })),
- Some(GraphValidity::Sound(p)) => {
- let valid_ok = valid_at.is_none_or(|t| p.valid_at(t));
- // 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| p.not_recorded_at(t));
- if valid_ok && recorded_miss.is_none() {
- in_scope.push(serde_json::json!({"graph": g, "valid": p.shown.describe()}));
- names.push(g.clone());
+ "valid": p.shown.describe(),
+ "reason": if !valid_ok {
+ kind.map_or("not true at that instant", Degenerate::reason)
} else {
- excluded.push(serde_json::json!({
- "graph": g,
- "valid": p.shown.describe(),
- "reason": if !valid_ok {
- "not true at that instant"
- } else {
- recorded_miss.unwrap_or("not yet recorded then")
- },
- }));
- }
- }
+ recorded_miss.unwrap_or("not yet recorded then")
+ },
+ }));
}
}
@@ -1223,11 +1336,16 @@ impl Temporal {
// open ends. An UNREADABLE one is not a period at all, and handing it
// this value would make it overlap everything: the false
// contradiction the truncation warning below is about, arriving
- // through the data instead of through a cap.
+ // through the data instead of through a cap. A DEGENERATE one is a
+ // real period that holds at no instant: it is compared, and
+ // `overlaps` answers false for it, so the pair lands in
+ // non_overlapping, which is true and since #116 claims no correction.
let timeless = Period::default();
let period = |graph: &str| match validities.get(graph) {
None => Some(&timeless),
- Some(GraphValidity::Sound(p)) => Some(p),
+ Some(GraphValidity::Sound(p)) | Some(GraphValidity::Degenerate { period: p, .. }) => {
+ Some(p)
+ }
Some(GraphValidity::Unreadable(_)) => None,
};
@@ -1292,7 +1410,9 @@ impl Temporal {
read as instants on the UTC timeline, so a timezone offset is honoured; \
that is all that has been checked: it is not evidence that one replaced \
the other, and the bucket also holds pairs separated by a GAP (missing \
- coverage rather than history). undecided holds pairs where a graph's \
+ coverage rather than history) and pairs where one period holds at no \
+ instant, empty or inverted, which onto_temporal_snapshot reports once \
+ with a reason naming which. undecided holds pairs where a graph's \
temporal metadata could not be read: an unreadable period is never \
treated as an open one, so such a pair is classified neither way. \
superseded is the same set as non_overlapping under a name that claimed \
@@ -1407,6 +1527,56 @@ ex:g_after { ex:X a ex:Suspension . }
serde_json::from_str(&raw).expect("tool output is JSON")
}
+ /// Two raw valid bounds, as the validity scan would hand them over.
+ fn valid(from: &str, to: &str) -> Bounds {
+ Bounds {
+ from: vec![format!("\"{from}\"")],
+ to: vec![format!("\"{to}\"")],
+ ..Bounds::default()
+ }
+ }
+
+ /// The classification is made where the bounds are read, and nowhere
+ /// else: equal instants are an empty period, a `validTo` before its
+ /// `validFrom` an inverted one, and everything with an instant inside it
+ /// is sound. The period travels with the verdict, and carries it too, so
+ /// `overlaps` can answer from it without seeing the enum.
+ #[test]
+ fn resolve_classifies_a_period_that_holds_nowhere_once_when_it_is_read() {
+ for (from, to, kind) in [
+ ("2024-01-01", "2024-01-01", Degenerate::Empty),
+ // Two precisions naming one instant: the case parsing created.
+ ("2024", "2024-01-01", Degenerate::Empty),
+ ("2026-01-01", "2020-01-01", Degenerate::Inverted),
+ ] {
+ match valid(from, to).resolve("g".into()) {
+ GraphValidity::Degenerate { period, kind: k } => {
+ assert_eq!(k, kind, "[{from}, {to})");
+ assert_eq!(period.degenerate, Some(kind), "[{from}, {to})");
+ }
+ other => panic!("[{from}, {to}) should hold nowhere: {other:?}"),
+ }
+ }
+ for (from, to) in [("2024-01-01", "2025-01-01"), ("2024-01-01", "2024-01-02")] {
+ match valid(from, to).resolve("g".into()) {
+ GraphValidity::Sound(period) => assert_eq!(period.degenerate, None),
+ other => panic!("[{from}, {to}) holds somewhere: {other:?}"),
+ }
+ }
+ // The recorded axis is not classified here: a recordedUntil before
+ // its recordedAt is out-of-order recording (#109), a different
+ // question, and pinning it as sound makes that change deliberate.
+ let recorded = Bounds {
+ recorded: vec!["\"2026-01-01\"".to_string()],
+ until: vec!["\"2020-01-01\"".to_string()],
+ ..Bounds::default()
+ };
+ assert!(matches!(
+ recorded.resolve("g".into()),
+ GraphValidity::Sound(_)
+ ));
+ }
+
/// The overrides below are for tests. If one ever became the shipped
/// value, this is the line that says so.
#[test]
diff --git a/tests/temporal_conformance_test.rs b/tests/temporal_conformance_test.rs
index ef3313d0..d08a1ea6 100644
--- a/tests/temporal_conformance_test.rs
+++ b/tests/temporal_conformance_test.rs
@@ -10,7 +10,7 @@
//! anchors, not aspirations: a later change to the temporal semantics has to
//! move a line here on purpose rather than drift silently.
//!
-//! The file has three sections. The first pins semantics that are **intended**;
+//! The file has four sections. The first pins semantics that are **intended**;
//! most of it uses a single lexical date form, since that is the shape those
//! assertions are about, and none of it moved when bounds started being parsed.
//! The second pinned what the code did for mixed-precision and malformed bounds
@@ -20,6 +20,9 @@
//! so those tests now hold the new answer on the same lines, which is what the
//! section was for. The third covers what parsing adds and could not be
//! expressed before: coarse bounds, offsets, and bounds that must be refused.
+//! The fourth covers periods that hold at no instant (#118), led by the case
+//! parsing created: two readable bounds at different precisions naming one
+//! instant.
//!
//! Deliberately not feature-gated: a `#![cfg(feature = ...)]` on a test file
//! that CI runs without that feature prints `running 0 tests` and reads as
@@ -555,6 +558,11 @@ fn the_note_claims_only_what_the_code_checks() {
note.contains("undecided") && note.contains("could not be read"),
"and must say why a pair can be in neither bucket: {note}"
);
+ assert!(
+ note.contains("holds at no instant") && note.contains("empty or inverted"),
+ "and must say the bucket holds a period with no instant inside it, and name \
+ both shapes, since the snapshot's reason is the only place they differ: {note}"
+ );
assert!(
!note.contains("one period ends where the other begins"),
"adjacency is never established by `!overlaps`: {note}"
@@ -1122,3 +1130,485 @@ fn every_answer_names_the_semantics_that_produced_it() {
assert_eq!(out["semantics_version"], "temporal/2", "{out}");
}
}
+
+// ---------------------------------------------------------------------------
+// Section 4: periods that hold at no instant (#118)
+//
+// Two bounds that both read, and together name no instant: validFrom and
+// validTo naming the same instant is an empty period, validTo before validFrom
+// an inverted one. Neither is unreadable, so neither belongs in `invalid`,
+// whose every reason says a bound could not be read. `valid_at` was already
+// false everywhere for both; `overlaps` was not, so the snapshot excluded such
+// a graph at every instant while conflicts filed it as a contradiction partner.
+// The classification is now made once, where the bounds are read, and both
+// tools answer from it: excluded at every instant asked about, with a reason
+// naming the shape, and read like any other graph when no valid_at is given,
+// since no instant was asked about. The mixed-precision fixture leads because
+// it is the case parsing created: two careful assertions from two systems,
+// invisible on inspection.
+// ---------------------------------------------------------------------------
+
+/// "Valid for 2024" beside "until 1 January 2024". Each bound is what a
+/// careful system writes at its own precision, and the two together name one
+/// instant, so the period is empty. Nothing on the page says so.
+const EMPTY_MIXED_PRECISION: &str = r#"
+@prefix ex: <http://example.org/> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+
+ex:g_empty { ex:X a ex:Adherent . }
+ex:g_live { ex:X a ex:Suspension . }
+
+{
+ ex:Adherent owl:disjointWith ex:Suspension .
+ ex:g_empty t:validFrom "2024"^^xsd:gYear ; t:validTo "2024-01-01"^^xsd:date .
+ ex:g_live t:validFrom "2023-01-01" ; t:validTo "2025-01-01" .
+}
+"#;
+
+/// The same literal on both bounds: the shape that was visible before parsing.
+const EMPTY_SAME_LITERAL: &str = r#"
+@prefix ex: <http://example.org/> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+
+ex:g_empty { ex:X a ex:Adherent . }
+ex:g_live { ex:X a ex:Suspension . }
+
+{
+ ex:Adherent owl:disjointWith ex:Suspension .
+ ex:g_empty t:validFrom "2024-06-01" ; t:validTo "2024-06-01" .
+ ex:g_live t:validFrom "2023-01-01" ; t:validTo "2025-01-01" .
+}
+"#;
+
+/// validTo six years before validFrom, beside a graph still true. Nothing
+/// checked `from < to`, so this read as a period ending in 2020 that a 2023
+/// assertion then corrected.
+const INVERTED: &str = r#"
+@prefix ex: <http://example.org/> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+
+ex:g_inverted { ex:X a ex:Adherent . }
+ex:g_live { ex:X a ex:Suspension . }
+
+{
+ ex:Adherent owl:disjointWith ex:Suspension .
+ ex:g_inverted t:validFrom "2026-01-01" ; t:validTo "2020-01-01" .
+ ex:g_live t:validFrom "2023-01-01" .
+}
+"#;
+
+fn conflicts(t: &Temporal) -> serde_json::Value {
+ serde_json::from_str(&t.conflicts().unwrap()).unwrap()
+}
+
+/// The local parts of every graph named in any row of one conflicts bucket.
+fn partners(out: &serde_json::Value, bucket: &str) -> BTreeSet<String> {
+ out[bucket]
+ .as_array()
+ .unwrap_or_else(|| panic!("conflicts has no array `{bucket}`: {out}"))
+ .iter()
+ .flat_map(|row| row["graphs"].as_array().unwrap().iter())
+ .map(|g| {
+ let g = g.as_str().unwrap();
+ g.rsplit(['#', '/']).next().unwrap_or(g).to_string()
+ })
+ .collect()
+}
+
+#[test]
+fn an_empty_period_is_excluded_at_every_instant_with_a_reason_naming_it_empty() {
+ // The instant both bounds name, where a `<=` slip on either side would
+ // let the period hold for exactly one instant.
+ for (fixture, boundary) in [
+ (EMPTY_MIXED_PRECISION, "2024-01-01"),
+ (EMPTY_SAME_LITERAL, "2024-06-01"),
+ ] {
+ let t = temporal(fixture);
+ for valid_at in [Some("2023-06-01"), Some(boundary), Some("2030-01-01")] {
+ let snap = snapshot(&t, valid_at, None);
+ assert!(
+ !graphs(&snap, "in_scope").contains("g_empty"),
+ "a period with no instant inside it is in scope at none \
+ (valid_at {valid_at:?}): {snap}"
+ );
+ assert!(
+ invalid_reason(&snap, "g_empty").is_none(),
+ "both bounds read, so nothing about it is unreadable: {snap}"
+ );
+ let why = reason(&snap, "g_empty");
+ assert!(
+ why.contains("holds at no instant") && why.contains("empty"),
+ "the reason says it holds nowhere and names the shape: {why}"
+ );
+ assert!(
+ !why.contains("inverted"),
+ "and does not name the other shape: {why}"
+ );
+ }
+ // With no valid_at no instant was asked about, and the graph is read
+ // like any other: in scope, excluded nowhere, unreadable nowhere.
+ let open = snapshot(&t, None, None);
+ assert!(
+ graphs(&open, "in_scope").contains("g_empty"),
+ "no instant asked about, so nothing for it to fail: {open}"
+ );
+ assert!(!graphs(&open, "excluded").contains("g_empty"), "{open}");
+ assert!(invalid_reason(&open, "g_empty").is_none(), "{open}");
+ // The live graph is unaffected either way.
+ let mid = snapshot(&t, Some("2024-01-01"), None);
+ assert!(graphs(&mid, "in_scope").contains("g_live"), "{mid}");
+ let late = snapshot(&t, Some("2030-01-01"), None);
+ assert_eq!(
+ reason(&late, "g_live"),
+ "not true at that instant",
+ "a sound period outside its interval keeps the generic reason: {late}"
+ );
+ }
+}
+
+#[test]
+fn an_inverted_period_is_named_inverted_and_is_not_a_correction() {
+ let t = temporal(INVERTED);
+ // 2022-06-01 lies between the two bounds: a reading that silently swapped
+ // them would put the graph in scope here.
+ for valid_at in [Some("2020-01-01"), Some("2022-06-01"), Some("2026-01-01")] {
+ let snap = snapshot(&t, valid_at, None);
+ assert!(
+ !graphs(&snap, "in_scope").contains("g_inverted"),
+ "valid_at {valid_at:?}: {snap}"
+ );
+ assert!(invalid_reason(&snap, "g_inverted").is_none(), "{snap}");
+ let why = reason(&snap, "g_inverted");
+ assert!(
+ why.contains("holds at no instant") && why.contains("inverted"),
+ "the reason names the shape that is almost always a mistake: {why}"
+ );
+ assert!(!why.contains("empty"), "{why}");
+ }
+ // With no valid_at no instant was asked about, and the graph is in scope
+ // like any other, the shape notwithstanding.
+ let open = snapshot(&t, None, None);
+ assert!(graphs(&open, "in_scope").contains("g_inverted"), "{open}");
+ assert!(!graphs(&open, "excluded").contains("g_inverted"), "{open}");
+ assert!(invalid_reason(&open, "g_inverted").is_none(), "{open}");
+ // In conflicts the pair shares no instant, which is true, and lands in
+ // the bucket that since #116 claims nothing more than that. It was filed
+ // there before this fix too; what changed is that the snapshot now says
+ // the graph holds nowhere instead of "not true at that instant", so the
+ // row cannot be read as a period ending in 2020 that 2023 corrected.
+ let out = conflicts(&t);
+ assert_eq!(out["contradiction_count"], 0, "{out}");
+ assert_eq!(out["non_overlapping_count"], 1, "{out}");
+ assert!(
+ partners(&out, "non_overlapping").contains("g_inverted"),
+ "{out}"
+ );
+ assert!(out.get("undecided_count").is_none(), "{out}");
+}
+
+#[test]
+fn a_period_that_holds_nowhere_is_never_a_contradiction_partner() {
+ let t = temporal(EMPTY_MIXED_PRECISION);
+ let out = conflicts(&t);
+ // `[2024-01-01, 2024-01-01)` lies inside `[2023-01-01, 2025-01-01)`, so a
+ // bound test alone answers "overlaps" and filed this as a live
+ // contradiction. A period with no instant inside it shares none.
+ assert_eq!(out["contradiction_count"], 0, "{out}");
+ assert_eq!(out["non_overlapping_count"], 1, "{out}");
+ assert_eq!(out["superseded_count"], 1, "{out}");
+ assert!(
+ out.get("undecided_count").is_none(),
+ "both bounds read, so the pair is classified: {out}"
+ );
+ assert!(
+ out["non_overlapping"][0]["periods"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|p| p == "2024 to 2024-01-01"),
+ "the row shows the bounds as asserted: {out}"
+ );
+ let note = out["note"].as_str().unwrap();
+ assert!(
+ note.contains("holds at no instant") && note.contains("onto_temporal_snapshot"),
+ "the note says the bucket can hold such a period, and where it is explained: {note}"
+ );
+}
+
+/// The defect in one assertion: the snapshot said the graph holds nowhere
+/// while conflicts said it overlapped a live one. Both outputs on the same
+/// store, for all three shapes.
+#[test]
+fn snapshot_and_conflicts_agree_about_a_period_that_holds_nowhere() {
+ for (fixture, graph, inside) in [
+ (EMPTY_MIXED_PRECISION, "g_empty", "2024-01-01"),
+ (EMPTY_SAME_LITERAL, "g_empty", "2024-06-01"),
+ (INVERTED, "g_inverted", "2024-01-01"),
+ ] {
+ let t = temporal(fixture);
+ let snap = snapshot(&t, Some(inside), None);
+ assert!(
+ reason(&snap, graph).contains("holds at no instant"),
+ "{fixture}: {snap}"
+ );
+ assert!(graphs(&snap, "in_scope").contains("g_live"), "{snap}");
+ let out = conflicts(&t);
+ assert_eq!(out["contradiction_count"], 0, "{fixture}: {out}");
+ assert!(
+ !partners(&out, "contradictions").contains(graph),
+ "a graph the snapshot excludes everywhere cannot disagree with anything: {out}"
+ );
+ assert!(partners(&out, "non_overlapping").contains(graph), "{out}");
+ }
+}
+
+/// The guard against over-eager classification: a touching pair has one
+/// bound in common ACROSS the two graphs, which is nothing like a period with
+/// no instant inside it, and a sound period is still in scope inside its
+/// interval and excluded outside it with the generic reason.
+#[test]
+fn a_sound_period_and_a_touching_pair_are_not_degenerate() {
+ let t = temporal(CONFLICT_SUPERSEDED);
+ let inside = snapshot(&t, Some("2025-01-01"), None);
+ assert!(graphs(&inside, "in_scope").contains("g_a"), "{inside}");
+ assert_eq!(
+ reason(&inside, "g_b"),
+ "not true at that instant",
+ "a sound period outside its interval keeps the generic reason: {inside}"
+ );
+ let at_bound = snapshot(&t, Some("2026-05-01"), None);
+ assert_eq!(reason(&at_bound, "g_a"), "not true at that instant");
+ assert!(graphs(&at_bound, "in_scope").contains("g_b"), "{at_bound}");
+ let out = conflicts(&t);
+ assert_eq!(out["contradiction_count"], 0, "{out}");
+ assert_eq!(out["non_overlapping_count"], 1, "{out}");
+ // And nothing in a store with no degenerate period says one holds nowhere.
+ for fixture in [
+ CELL_LINE,
+ CONFLICT_SUPERSEDED,
+ CONFLICT_OVERLAP,
+ COARSE_BOUNDS,
+ ] {
+ let snap = snapshot(&temporal(fixture), None, None);
+ assert!(
+ graphs(&snap, "excluded").is_empty(),
+ "every sound period is in scope with no valid_at: {snap}"
+ );
+ }
+}
+
+/// `query_at` runs over the snapshot's scope. With no valid_at no instant was
+/// asked about, so a graph that holds at no instant is read like any other:
+/// the query's output has no key that could say it was left out, and
+/// narrowing an atemporal query silently is the failure its reporting exists
+/// to remove. At any valid_at the graph is out of scope, and
+/// onto_temporal_snapshot at that instant is where the reason is.
+#[test]
+fn query_at_with_no_valid_at_reads_a_period_that_holds_nowhere_like_any_other() {
+ let t = temporal(EMPTY_MIXED_PRECISION);
+ let raw = t.query_at("{ ?s a ?type }", None, None).unwrap();
+ let out: serde_json::Value = serde_json::from_str(&raw).unwrap();
+ assert!(
+ raw.contains("Adherent"),
+ "no instant asked about, so the graph that holds nowhere is read: {raw}"
+ );
+ assert!(
+ raw.contains("Suspension"),
+ "and so is the live graph beside it: {raw}"
+ );
+ assert_eq!(
+ out["graphs_in_scope"], 2,
+ "both graphs are in scope with no valid_at: {out}"
+ );
+ assert!(
+ out.get("invalid").is_none(),
+ "both of its bounds read, so it is not listed as unreadable either: {out}"
+ );
+ // At an instant the live graph holds at, the boundary instant included,
+ // the graph that holds nowhere is left out and the live one alone is read.
+ for valid_at in ["2023-06-01", "2024-01-01"] {
+ let raw = t.query_at("{ ?s a ?type }", Some(valid_at), None).unwrap();
+ let out: serde_json::Value = serde_json::from_str(&raw).unwrap();
+ assert!(
+ !raw.contains("Adherent"),
+ "valid_at {valid_at}: the graph that holds nowhere is not queried: {raw}"
+ );
+ assert!(raw.contains("Suspension"), "valid_at {valid_at}: {raw}");
+ assert_eq!(
+ out["graphs_in_scope"], 1,
+ "valid_at {valid_at}: g_live alone is in scope: {out}"
+ );
+ }
+}
+
+/// An empty period whose graph also carries a recordedAt, beside a live graph
+/// recorded at the same time. An `as_of` before that instant fails both on
+/// the recorded axis, and only one of them holds nowhere.
+const EMPTY_RECORDED_LATER: &str = r#"
+@prefix ex: <http://example.org/> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+
+ex:g_empty { ex:X a ex:Adherent . }
+ex:g_live { ex:X a ex:Suspension . }
+
+{
+ ex:Adherent owl:disjointWith ex:Suspension .
+ ex:g_empty t:validFrom "2024-06-01" ; t:validTo "2024-06-01" ; t:recordedAt "2024-07-01" .
+ ex:g_live t:validFrom "2023-01-01" ; t:validTo "2025-01-01" ; t:recordedAt "2024-07-01" .
+}
+"#;
+
+/// With a valid_at given, the reason names the shape whatever `as_of` is
+/// passed: validity is checked first, and "not yet recorded then" is a fact
+/// about the query where "holds at no instant" is a fact about the data, the
+/// one to fix, so it is not hidden behind the first when both apply. With no
+/// valid_at the recorded side is the only question asked, and its reason the
+/// only one that can apply. The live graph beside it shows the recorded
+/// reason is still given where it is the only thing wrong.
+#[test]
+fn a_period_that_holds_nowhere_says_so_whatever_as_of_is_passed() {
+ let t = temporal(EMPTY_RECORDED_LATER);
+ // At the instant both bounds name and at one outside it, with an as_of
+ // before, at and after the recordedAt of both graphs.
+ for valid_at in [Some("2024-06-01"), Some("2024-01-01")] {
+ for as_of in [Some("2000-01-01"), Some("2024-07-01"), Some("2030-01-01")] {
+ let snap = snapshot(&t, valid_at, as_of);
+ let why = reason(&snap, "g_empty");
+ assert!(
+ why.contains("holds at no instant") && why.contains("empty"),
+ "valid_at {valid_at:?}, as_of {as_of:?}: the data fault wins over the \
+ recorded axis: {why}"
+ );
+ assert!(
+ !why.contains("recorded"),
+ "valid_at {valid_at:?}, as_of {as_of:?}: and the recorded axis is not \
+ mentioned: {why}"
+ );
+ }
+ }
+ // With no valid_at, an as_of before its recordedAt excludes it on the
+ // recorded side alone, as it would a sound graph; at or after it, the
+ // graph is in scope.
+ let early = snapshot(&t, None, Some("2000-01-01"));
+ assert_eq!(
+ reason(&early, "g_empty"),
+ "not yet recorded then",
+ "no instant asked about, so the recorded side is the only question: {early}"
+ );
+ for as_of in [Some("2024-07-01"), Some("2030-01-01")] {
+ let snap = snapshot(&t, None, as_of);
+ assert!(
+ graphs(&snap, "in_scope").contains("g_empty"),
+ "as_of {as_of:?}: {snap}"
+ );
+ }
+ assert_eq!(
+ reason(&early, "g_live"),
+ "not yet recorded then",
+ "a sound period before its recordedAt keeps the recorded reason: {early}"
+ );
+ let later = snapshot(&t, None, Some("2030-01-01"));
+ assert!(graphs(&later, "in_scope").contains("g_live"), "{later}");
+}
+
+/// An empty period beside a graph with no description at all.
+const EMPTY_BESIDE_TIMELESS: &str = r#"
+@prefix ex: <http://example.org/> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+
+ex:g_empty { ex:X a ex:Adherent . }
+ex:g_timeless { ex:X a ex:Suspension . }
+
+{
+ ex:Adherent owl:disjointWith ex:Suspension .
+ ex:g_empty t:validFrom "2024-06-01" ; t:validTo "2024-06-01" .
+}
+"#;
+
+/// A timeless partner is the case the bound test got most wrong: its period
+/// has open ends, so `[t, t)` overlapped it unconditionally. The pair shares
+/// no instant, the row shows the partner as open on both sides, and the
+/// snapshot keeps the timeless graph in scope beside the excluded one.
+#[test]
+fn a_period_that_holds_nowhere_beside_a_timeless_graph_is_not_a_contradiction() {
+ let t = temporal(EMPTY_BESIDE_TIMELESS);
+ let out = conflicts(&t);
+ assert_eq!(out["contradiction_count"], 0, "{out}");
+ assert_eq!(out["non_overlapping_count"], 1, "{out}");
+ assert!(out.get("undecided_count").is_none(), "{out}");
+ assert!(
+ out["non_overlapping"][0]["periods"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|p| p == "always to still true"),
+ "the undescribed partner is shown open on both sides: {out}"
+ );
+ let snap = snapshot(&t, Some("2024-06-01"), None);
+ assert!(graphs(&snap, "in_scope").contains("g_timeless"), "{snap}");
+ assert!(
+ reason(&snap, "g_empty").contains("holds at no instant"),
+ "{snap}"
+ );
+ let open = snapshot(&t, None, None);
+ assert_eq!(
+ graphs(&open, "in_scope"),
+ set(&["g_empty", "g_timeless"]),
+ "no instant asked about, so both are read: {open}"
+ );
+}
+
+/// An empty period beside a graph whose own bound could not be read.
+const EMPTY_BESIDE_UNREADABLE: &str = r#"
+@prefix ex: <http://example.org/> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+
+ex:g_empty { ex:X a ex:Adherent . }
+ex:g_bad { ex:X a ex:Suspension . }
+
+{
+ ex:Adherent owl:disjointWith ex:Suspension .
+ ex:g_empty t:validFrom "2024-06-01" ; t:validTo "2024-06-01" .
+ ex:g_bad t:validFrom "01/06/2024"^^xsd:string .
+}
+"#;
+
+/// Unreadable still wins: a period that holds nowhere shares no instant with
+/// anything, but "shares no instant" is a verdict on two periods, and an
+/// unreadable partner is not a period at all, so the pair stays undecided
+/// rather than being filed as non_overlapping on the strength of one side.
+#[test]
+fn a_period_that_holds_nowhere_beside_an_unreadable_one_is_still_undecided() {
+ let t = temporal(EMPTY_BESIDE_UNREADABLE);
+ let out = conflicts(&t);
+ assert_eq!(out["contradiction_count"], 0, "{out}");
+ assert_eq!(out["non_overlapping_count"], 0, "{out}");
+ assert_eq!(out["undecided_count"], 1, "{out}");
+ assert!(
+ out["undecided"][0]["reason"]
+ .as_str()
+ .unwrap()
+ .contains("could not be read"),
+ "{out}"
+ );
+ let snap = snapshot(&t, Some("2024-06-01"), None);
+ assert!(invalid_reason(&snap, "g_bad").is_some(), "{snap}");
+ assert!(invalid_reason(&snap, "g_empty").is_none(), "{snap}");
+ assert!(
+ reason(&snap, "g_empty").contains("holds at no instant"),
+ "{snap}"
+ );
+ // With no valid_at the unreadable graph stays out and the one that holds
+ // nowhere is in: the two verdicts do not depend on each other.
+ let open = snapshot(&t, None, None);
+ assert!(invalid_reason(&open, "g_bad").is_some(), "{open}");
+ assert!(graphs(&open, "in_scope").contains("g_empty"), "{open}");
+}