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): supersedes and retracts, derived never written (#125)
Nicolas77d81b78e47f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 24203a98..18da4991 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -415,6 +415,78 @@ All notable changes to Open Ontologies are documented here.a third section covers what parsing adds.### Added+- **`temporal:supersedes` and `temporal:retracts`: lineage that is asserted,+ never inferred** (#109). Three situations looked identical in the data: a+ correction (one authority replacing its own assertion), a disagreement (two+ sources) and a retraction (withdrawn, nothing put in its place).+ `onto_temporal_conflicts` filed a correction that shares its predecessor's+ valid period as a contradiction, and with no explicit `recordedUntil` the+ predecessor stayed believed for ever. Both predicates are written on the+ NEWER graph and name the graph it replaces or withdraws. `recordedUntil`+ alone governs scope and an explicit bound is authoritative; where a graph+ carries none, its closing bound is derived from the inbound link as the+ successor's `recordedAt`, the earliest where there are several, since belief+ ended at the first replacement and a later one does not revive it. Where+ both are present and disagree the explicit value governs and the+ disagreement is reported, not reconciled. Nothing is written: the derivation+ is a join made when the validity map is read, inside `validities()`, so the+ snapshot, the query and the conflict check share it by construction.++ `onto_temporal_snapshot` and `onto_temporal_query` gain two keys, present+ only when non-empty like `invalid`. `retracted` holds rows shaped like+ `excluded`, with `reason: "retracted"`, `retracted_by` and `retracted_at`,+ for graphs a `retracts` link recorded by `as_of` has withdrawn; a retracted+ graph leaves `in_scope`, its triples are not read, and retraction is checked+ before the bounds, so for a readable graph it beats every other reason,+ a derived closing bound included; an unreadable graph stays in `invalid`,+ whatever links name it. `lineage` holds one `{graph, reason, ...}` row per+ thing the links could not settle: an explicit bound that disagrees with its+ successor, a transaction interval that closes before it opens (a successor+ recorded before its predecessor, reported as inverted and believed at no+ instant, never clamped), a successor with no `recordedAt`, more than one+ successor (reported whether the close was derived or asserted, in one row+ shape: `closed_by` names the successor where the bound was derived, and+ `recorded_until` the explicit bound where it was asserted, since no+ successor closed a graph that closed itself), a retractor with no+ `recordedAt` (which withdraws at every `as_of` given: a withdrawal at an+ unknown time is still a withdrawal), a cycle, a link naming the graph+ itself, an undescribed or unreadable graph, or a term that is not an IRI,+ and a link asserted by a graph whose own description could not be read,+ which closes and withdraws nothing and says so rather than vanishing with+ its asserter. A link the pass rejects is pruned from the map it hands on,+ so every consumer walks effective links only: a `supersedes` naming an+ undescribed graph puts no pair in `corrections`, and the disjoint pair it+ fails to link is the contradiction it is, the undescribed graph being+ timeless. An excluded row whose closing bound was derived carries+ `superseded_by`. With no `as_of` a derived bound is read as an asserted one+ is: no instant was asked about on the recorded axis, so the graph is in+ scope. With no `as_of` the recorded axis is not consulted for retraction+ either: a retracted graph takes the ordinary path, in scope unless its+ valid-time bounds exclude it, exactly like a graph closed by a+ `recordedUntil`, explicit or derived. One rule for every recorded-time+ fact. The alternative, an absent `as_of` read as "now" for the whole+ recorded axis, is a one-line reversal that would then have to change+ explicit `recordedUntil` too. `onto_temporal_conflicts` gains `corrections`+ / `corrections_count`, present only when non-empty like `undecided`: pairs+ where one graph supersedes the other, directly or through a chain, checked+ before the overlap test, so such a pair is never a contradiction whatever+ its periods, and the `note` says so. Retracted graphs are not treated+ specially there. `temporal:authority` is description, not a key, and is+ left for a follow-up.++ Cap arithmetic: the validity scan counts rows over a six-way UNION now. A+ store that writes neither predicate is unchanged. A graph carrying the four+ bounds and one link costs five rows, both links six, so the 20,000-row cap+ covers roughly 4,000 such graphs, or roughly 3,300 with both, against+ roughly 5,000 fully bounded ones; a test proves the fifth row. The+ `validities` truncation texts, on the snapshot, the query and the conflict+ check, name the failure the shared cap adds: a `supersedes` or `retracts`+ row cut while its asserter's bounds survived was never seen, so the graph+ it named stays open or in scope although it is described, and a pair the+ link would have made a correction is compared on its periods.+ `semantics_version` stays `temporal/2`: the lineage predicates ship in the+ same release as the parsed bounds, and a store without them answers as it+ did.- **CLI: Daemon mode — persistent in-memory store across processes.** New `daemon start / stop / status` subcommand launches `serve-http` as a detached background process and writes its PID + URL to `~/.open-ontologies/daemon.json`. All 24 CLI commands that touch the `Arc<GraphStore>` (load, save, clear, stats, query, lint, reason, shacl, enforce, plan, apply, version, history, rollback, pull, push, ingest, drift, lock, monitor, monitor-clear, marketplace, and `batch`) automatically detect a live daemon and route their request to it via the new `/api/batch` HTTP endpoint — no flags, no code changes per-command. Use `--no-connect` to force local execution. Daemon liveness is checked with a bare `kill(pid, 0)` (Unix) / `tasklist` (Windows), rather than forking `/bin/kill` on the path the daemon exists to make fast; stale `daemon.json` files are removed automatically on the next command. New modules `src/daemon.rs` (PID file management + process control) and `src/connect.rs` (HTTP proxy client), and `libc` as a dependency for the liveness check.Commands are proxied in the structured form of `/api/batch` — `{"command": name, "args": [..]}`, one argument per array element — rather than as a command line the daemon re-tokenizes. The lossy round trip was the source of most of what is fixed below: an argument cannot be torn on a newline, mangled by a quoting rule, or resolved against the wrong directory once it is an array element that reaches the daemon exactly as clap parsed it. Path arguments are made absolute before they are sent, and an invocation carrying a flag the batch handler has no arm for is run locally rather than proxied without it. `daemon start` waits for the port to accept a connection instead of sleeping a fixed 600ms, so it neither burns the wait when the bind is fast nor reports success for a child that never bound.diff --git a/CLAUDE.md b/CLAUDE.mdindex 366ece86..8ff3cea6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -97,7 +97,7 @@ Claude dynamically decides the next tool call based on what the previous tool re| `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. 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. 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 with a reason, never in scope and never timeless || `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 pairs that never met. A disjointness violation only counts when the two assertions claim OVERLAPPING validity; everything else lands in `non_overlapping`, which proves only that the two share no instant, judged on their bounds read as instants on the UTC timeline so a timezone offset is honoured: not that one replaced the other, and it also holds pairs separated by a gap, which is missing coverage rather than history. A pair whose graph has temporal metadata that could not be read goes to `undecided`, in neither bucket, because an unreadable period is not an open one. `superseded` is the same set under its old name, deprecated and dropped at 2.0 |+| `onto_temporal_conflicts` | To separate genuine contradictions from pairs that never met and from asserted corrections. A pair where one graph `temporal:supersedes` the other, directly or through a chain, lands in `corrections` whatever its periods, lineage that is asserted and never inferred; otherwise a disjointness violation only counts when the two assertions claim OVERLAPPING validity, and everything else lands in `non_overlapping`, which proves only that the two share no instant, judged on their bounds read as instants on the UTC timeline so a timezone offset is honoured: not that one replaced the other, and it also holds pairs separated by a gap, which is missing coverage rather than history. A pair whose graph has temporal metadata that could not be read goes to `undecided`, in neither bucket, because an unreadable period is not an open one. `superseded` is the same set under its old name, deprecated and dropped at 2.0 || `onto_lineage` | To view the session's lineage trail (plan → enforce → apply → monitor → drift) || `onto_lint_feedback` | To accept/dismiss a lint issue — teaches lint to suppress repeatedly dismissed warnings || `onto_enforce_feedback` | To accept/dismiss an enforce violation — teaches enforce to suppress repeatedly dismissed violations |diff --git a/src/server.rs b/src/server.rsindex ff3699b9..e6b9be08 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. 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.")]+ #[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. Lineage is asserted, never inferred: temporal:supersedes on the NEWER graph names the graph it replaces, and where the replaced graph carries no recordedUntil its closing bound is derived from the successor's recordedAt (the earliest, where there are several), so an excluded row closed that way carries `superseded_by`; an explicit recordedUntil always governs and a disagreement with the successor is reported, not reconciled. temporal:retracts names a graph withdrawn without replacement: from the retraction's recordedAt the retracted graph leaves in_scope and is listed under `retracted` with the retracting graph and instant; with no as_of the recorded axis is not consulted, for a retraction no more than for a recordedUntil, and the graph takes the ordinary path. `lineage`, present only when non-empty, reports what the links could not settle: a disagreement, a transaction interval that closes before it opens (a successor recorded before its predecessor, reported as inverted and believed at no instant, never clamped), an undated successor or retractor, more than one successor, a cycle, or a link that names nothing readable or is asserted by a graph whose own description could not be read.")]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`. 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`.")]+ #[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`. The scope honours asserted lineage: a graph whose closing bound was derived from the recordedAt of the graph that temporal:supersedes it is out of scope from that instant, and a graph a temporal:retracts link has withdrawn by as_of is not read and is listed under `retracted` (with no as_of the recorded axis is not consulted, for a retraction no more than for a recordedUntil, and the graph is read like any other); `lineage` carries what the links could not settle, both keys present only when non-empty.")]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, 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.")]+ #[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. A pair where one graph asserts that it temporal:supersedes the other, directly or through a chain of supersedes links, lands in `corrections` (with `corrections_count`, present only when non-empty) before the overlap test is reached: lineage that is asserted and never inferred, and such a pair is never a contradiction whatever its periods. A retracted graph is not treated specially here.")]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.rsindex b2ed1022..35877166 100644--- a/src/temporal.rs+++ b/src/temporal.rs@@ -50,6 +50,36 @@//! that replaced it, and the audit question this module exists to answer stops//! being answerable after the first correction.//!+//! ## Lineage is asserted, never inferred+//!+//! Two graphs claiming the same period can be a correction (one authority+//! replaced its own assertion), a disagreement (two sources) or a retraction+//! (withdrawn, nothing put in its place), and nothing in the periods tells+//! the three apart. Two predicates carry the link, both written on the NEWER+//! graph: `temporal:supersedes` names the graph it replaces, and+//! `temporal:retracts` names the graph it withdraws without replacing. They+//! answer different questions from `recordedUntil` and do not compete with+//! it: `recordedUntil` alone governs scope, and an explicit bound is+//! authoritative. Where a graph carries none, the bound is DERIVED from the+//! link: belief in it ended at the `recordedAt` of the graph that supersedes+//! it, the earliest one where there are several. Where both are present and+//! disagree, the explicit value governs and the disagreement is reported+//! under `lineage`, never reconciled. Nothing is written: the derivation is a+//! join made when the validity map is read, so the snapshot, the query and+//! the conflict check share it by construction.+//!+//! A retracted graph stays visible, in its own `retracted` bucket, from the+//! instant the retraction was recorded. With no `as_of` the recorded axis is+//! not consulted, for a retraction no more than for a `recordedUntil`, and+//! the graph takes the ordinary path: one rule for every recorded-time fact,+//! a closing bound asserted or derived and a withdrawal alike. In+//! `conflicts` a disjointness+//! pair where one graph supersedes the other, directly or through a chain, is+//! a correction whatever its periods, and lands in `corrections` rather than+//! `contradictions`. A successor recorded before its predecessor produces a+//! transaction interval that closes before it opens: it is reported as+//! inverted and believed at no instant, never clamped.+//!//! ## Bounds are instants//!//! Every bound is read as an instant on the UTC timeline, from `xsd:date`,@@ -109,6 +139,11 @@ pub const NS: &str = "https://open-ontologies.org/temporal#";/// 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.+///+/// The lineage predicates, `supersedes` and `retracts`, are read under+/// `temporal/2` as well: they ship in the same release as the parsed bounds+/// and a store that does not write them answers exactly as it did without+/// them, so they do not move the version on their own.pub const SEMANTICS_VERSION: &str = "temporal/2";pub struct Temporal {@@ -116,11 +151,14 @@ pub struct Temporal {limits: Limits,}-/// 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.+/// Validity ROWS, not graphs. The query is a six-way UNION, so a graph+/// carrying validFrom, validTo, recordedAt and recordedUntil costs four rows,+/// and one that also asserts a `supersedes` link and a `retracts` link costs+/// six: the cap is reached at roughly 5,000 fully bounded graphs, at roughly+/// 4,000 where each also carries one lineage link, and at roughly 3,300 where+/// each carries both, where a three-predicate store still reaches it at+/// roughly 6,700. A store that never writes recordedUntil or a lineage link+/// pays nothing for them; 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;@@ -188,6 +226,14 @@ struct Scope {/// Graphs whose validity metadata could not be read. In neither of the/// two buckets above: an unreadable claim is not a claim we do not hold.invalid: Vec<serde_json::Value>,+ /// Graphs withdrawn by a `retracts` link recorded by the audit instant.+ /// Not `excluded`: a retracted claim did not fail a bound, it was taken+ /// back, and the row names the graph that took it back.+ retracted: Vec<serde_json::Value>,+ /// What the lineage links could not settle or settled with a remark:+ /// an explicit bound that disagrees with its successor, a transaction+ /// interval that closes before it opens, a link naming nothing readable.+ lineage: Vec<serde_json::Value>,/// The in-scope graph IRIs, in the same order as `in_scope`.graphs: Vec<String>,validity_scan: Capped,@@ -208,7 +254,10 @@ impl Scope {"graphs whose validity rows fell past the limit were read as having no \validity at all, so they are listed in scope as timeless even where their \period excludes them, and one whose metadata is unreadable is published as \- timeless instead of invalid",+ timeless instead of invalid; a supersedes or retracts row that fell past the \+ limit while its asserter's bounds did not was never seen, so the graph it \+ named stays open, never closed, or in scope, never withdrawn, although it is \+ described",),self.graph_scan.report("all_graphs",@@ -228,8 +277,10 @@ impl Scope {if self.validity_scan.hit {parts.push("described graphs were read as timeless and put in scope, which is the \- opposite of the truth for any graph whose period had ended, and unreadable \- ones were published as timeless rather than invalid",+ opposite of the truth for any graph whose period had ended, unreadable \+ ones were published as timeless rather than invalid, and a supersedes or \+ retracts row that fell past the limit was never seen, leaving the graph it \+ named open or in scope although it is described",);}if self.graph_scan.hit {@@ -282,6 +333,78 @@ struct Period {/// compares two periods without seeing the `GraphValidity` each came/// from, so the verdict has to travel on the period itself.degenerate: Option<Degenerate>,+ /// The links this graph asserts, and what the lineage pass derived from+ /// the links that name it. Carried on the period so `scope`, `query_at`+ /// and `conflicts` read one derivation rather than three.+ lineage: Lineage,+}++/// The lineage a graph asserts, and what was derived from the lineage+/// asserted about it. Asserted, never inferred: every field here traces to a+/// `supersedes` or `retracts` triple somebody wrote.+#[derive(Clone, Debug, Default)]+struct Lineage {+ /// The graphs this one asserts it replaces, as plain IRIs. As read, every+ /// asserted target; once `derive_lineage` has run, the EFFECTIVE ones+ /// only, a link it rejected surviving in its report row and nowhere+ /// else, so no consumer can walk a link the report says had no effect.+ supersedes: Vec<String>,+ /// The graphs this one asserts it withdraws, as plain IRIs, pruned to+ /// the effective ones by the same pass.+ retracts: Vec<String>,+ /// Terms on either predicate that are not IRIs, with the predicate each+ /// sat on. Kept so the report can quote them; nothing else reads them.+ not_iris: Vec<(&'static str, String)>,+ /// The successor whose `recordedAt` closed this graph's transaction+ /// interval, when the closing bound was derived rather than asserted.+ /// `None` for an asserted bound and for an open interval alike.+ until_derived_from: Option<String>,+ /// The graphs that retract this one, earliest recorded first and the+ /// undated ones last, so the first that qualifies at an instant is the+ /// one to name.+ retracted_by: Vec<Retractor>,+}++/// One graph that withdraws another, and when the withdrawal was recorded.+#[derive(Clone, Debug)]+struct Retractor {+ graph: String,+ recorded: Option<DateTime<Utc>>,+ /// The asserted lexical form, for the row; `None` when the retracting+ /// graph carries no `recordedAt`.+ recorded_lexical: Option<String>,+}++/// On which side of the recorded interval an instant fell, when it fell+/// outside. Three variants rather than a bool: "recorded later" and "no+/// longer believed" are opposite facts about an assertion, and an interval+/// that closes before it opens is a third, a fact about the data rather+/// than about the instant asked about.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum RecordedMiss {+ NotYet,+ NoLonger,+ /// `recordedUntil` precedes `recordedAt`, asserted or derived, so the+ /// interval holds at no instant.+ Nowhere,+}++impl RecordedMiss {+ fn reason(self) -> &'static str {+ match self {+ RecordedMiss::NotYet => "not yet recorded then",+ RecordedMiss::NoLonger => "no longer recorded then",+ RecordedMiss::Nowhere => {+ "believed at no instant: the transaction interval closes before it opens"+ }+ }+ }++ /// Whether the miss is on the closing side, where a derived bound is the+ /// thing that closed it and the row should name the successor.+ fn closed(self) -> bool {+ !matches!(self, RecordedMiss::NotYet)+ }}/// Why a period with two readable bounds holds at no instant.@@ -330,16 +453,49 @@ impl Period {/// Both bounds are instants like the valid-time pair: a closing bound/// written with an offset or at coarse precision closes the interval where/// that instant falls, not where its text sorts.- fn not_recorded_at(&self, instant: DateTime<Utc>) -> Option<&'static str> {+ ///+ /// An interval that closes before it opens is asked first. The two checks+ /// below already fail every instant for it, so the answer would be right+ /// either way, and wrong to read: "not yet recorded then" for a graph+ /// that was never believed at any instant sends the reader looking for+ /// a later instant that does not exist.+ fn not_recorded_at(&self, instant: DateTime<Utc>) -> Option<RecordedMiss> {+ if self.inverted_recording() {+ return Some(RecordedMiss::Nowhere);+ }if self.recorded.is_some_and(|r| instant < r) {- return Some("not yet recorded then");+ return Some(RecordedMiss::NotYet);}if self.until.is_some_and(|u| u <= instant) {- return Some("no longer recorded then");+ return Some(RecordedMiss::NoLonger);}None}+ /// Whether the transaction interval closes before it opens. Judged on the+ /// composed bound, so a derived `until` counts exactly as an asserted one.+ fn inverted_recording(&self) -> bool {+ match (self.recorded, self.until) {+ (Some(r), Some(u)) => u < r,+ _ => false,+ }+ }++ /// The retraction that stands at `as_of`, if any: the earliest one+ /// recorded by then, or an undated one, which stands at every instant+ /// asked about. With no `as_of` there is none: no instant was asked about+ /// on the recorded axis, so no recorded-time fact is consulted, a+ /// retraction no more than a `recordedUntil`, asserted or derived. One+ /// rule for every fact on that axis; reading an absent `as_of` as "now"+ /// would have to change the explicit bound too.+ fn retracted_as_of(&self, as_of: Option<DateTime<Utc>>) -> Option<&Retractor> {+ let t = as_of?;+ self.lineage+ .retracted_by+ .iter()+ .find(|r| r.recorded.is_none_or(|at| at <= t))+ }+/// Do two validity periods share any instant. Half-open, so touching/// 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)`@@ -379,8 +535,14 @@ enum GraphValidity {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.- Unreadable(Vec<Fault>),+ /// one is timeless. The links the graph asserted travel with the faults,+ /// as `(predicate, target)` pairs, so the lineage pass can report that+ /// each had no effect: a link dropped with its asserter would leave the+ /// graph it names open with nothing saying why.+ Unreadable {+ faults: Vec<Fault>,+ asserted: Vec<(&'static str, String)>,+ },}/// Why one bound could not be read.@@ -408,13 +570,37 @@ struct Bound {instant: DateTime<Utc>,}-/// The raw terms one graph asserts on each axis, before they are read.+/// The raw terms one graph asserts on each axis, before they are read, and+/// the raw lineage terms beside them.#[derive(Default)]struct Bounds {from: Vec<String>,to: Vec<String>,recorded: Vec<String>,until: Vec<String>,+ supersedes: Vec<String>,+ retracts: Vec<String>,+}++/// Split one predicate's raw terms into the graph IRIs it names and the+/// terms that name no graph. A literal on `supersedes` is a data error, and+/// one that was silently dropped would leave a predecessor open for ever,+/// which is the defect the predicate exists to close.+fn links(+ field: &'static str,+ terms: Vec<String>,+ not_iris: &mut Vec<(&'static str, String)>,+) -> Vec<String> {+ let mut iris = Vec::new();+ for term in terms {+ let t = term.trim();+ if t.starts_with('<') && t.ends_with('>') {+ iris.push(plain(t));+ } else {+ not_iris.push((field, term));+ }+ }+ iris}impl Bounds {@@ -430,17 +616,38 @@ impl Bounds {/// 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.+ /// is out-of-order recording (#109), which is a different question, and+ /// the lineage pass reports it once the derived bound is known.+ ///+ /// The lineage terms ride on the period as plain IRIs, for the sound and+ /// the degenerate verdict alike. An unreadable graph keeps its faults and+ /// the links it asserted, as raw pairs: it is invalid already, and a link+ /// asserted by a graph whose own description cannot be read closes+ /// nothing, but the lineage pass reports it rather than losing it.fn resolve(self, graph: String) -> GraphValidity {let mut faults = Vec::new();let from = settle("validFrom", self.from, &mut faults);let to = settle("validTo", self.to, &mut faults);let recorded = settle("recordedAt", self.recorded, &mut faults);let until = settle("recordedUntil", self.until, &mut faults);+ let mut not_iris = Vec::new();+ let supersedes = links("supersedes", self.supersedes, &mut not_iris);+ let retracts = links("retracts", self.retracts, &mut not_iris);if !faults.is_empty() {- return GraphValidity::Unreadable(faults);+ let asserted = supersedes+ .into_iter()+ .map(|t| ("supersedes", t))+ .chain(retracts.into_iter().map(|t| ("retracts", t)))+ .chain(not_iris)+ .collect();+ return GraphValidity::Unreadable { faults, asserted };}+ let lineage = Lineage {+ supersedes,+ retracts,+ not_iris,+ ..Lineage::default()+ };let degenerate = match (&from, &to) {(Some(f), Some(t)) => match f.instant.cmp(&t.instant) {Ordering::Equal => Some(Degenerate::Empty),@@ -462,6 +669,7 @@ impl Bounds {recorded: recorded.map(|b| b.instant),until: until.map(|b| b.instant),degenerate,+ lineage,};match degenerate {Some(kind) => GraphValidity::Degenerate { period, kind },@@ -946,6 +1154,377 @@ mod instant {}}+/// The readable period behind a verdict, if there is one.+fn period_of(v: &GraphValidity) -> Option<&Period> {+ match v {+ GraphValidity::Sound(p) | GraphValidity::Degenerate { period: p, .. } => Some(p),+ GraphValidity::Unreadable { .. } => None,+ }+}++fn period_mut(v: &mut GraphValidity) -> Option<&mut Period> {+ match v {+ GraphValidity::Sound(p) | GraphValidity::Degenerate { period: p, .. } => Some(p),+ GraphValidity::Unreadable { .. } => None,+ }+}++/// The second pass over the validity map: what the lineage links imply.+///+/// A join made when the map is read, and never written back. Every consumer+/// runs on the map this returns, so `scope`, `query_at` and `conflicts`+/// cannot disagree about which bound closed a graph. The rules, in the order+/// they run:+///+/// - A link whose target is the graph itself, a graph with no temporal+/// description, a graph whose description could not be read, or not a+/// graph IRI at all, has no effect and is reported. So does a link+/// asserted BY a graph whose own description could not be read: the+/// graph it names is neither closed nor withdrawn, and the row is the+/// only place that says so, since the asserter's `invalid` row is about+/// its bounds. Lineage is asserted, and a link that asserts nothing+/// readable closes nothing. Such a link is then PRUNED from the map:+/// the report row is the only place it survives, so the cycle walk here+/// and the chain walk in `conflicts` follow effective links only and+/// cannot file a pair as a correction on a link this pass rejected.+/// - A graph with no explicit `recordedUntil` and at least one dated+/// successor is closed at the EARLIEST successor's `recordedAt`. Belief+/// in it ended at the first replacement; a second successor does not+/// revive it. A successor with no `recordedAt` cannot date the+/// replacement and is reported, leaving the bound as it was.+/// - A graph WITH an explicit `recordedUntil` keeps it. A successor whose+/// `recordedAt` names a different instant is reported as a disagreement,+/// never reconciled: the explicit bound is the authority, the report is+/// the place the inconsistency survives.+/// - More than one dated successor is reported on either branch, in one+/// row shape naming them all: `closed_by` names the successor whose+/// `recordedAt` became the bound where it was derived, and+/// `recorded_until` the explicit bound where it was asserted, since no+/// successor closed a graph that closed itself.+/// - A retracted graph carries its retractors, earliest first. One with no+/// `recordedAt` is reported as undated, and stands at every instant+/// asked about; with no `as_of` none is, and no retractor stands.+/// - A cycle of `supersedes` links is reported once, and the derivation+/// above is one hop per graph, so a cycle cannot loop it.+/// - A transaction interval that closes before it opens, from an asserted+/// bound or a derived one, is reported as inverted. Nothing is clamped:+/// the row shows the asserted instants, and `not_recorded_at` answers+/// that the graph was believed at no instant.+///+/// Reports are rows of `{graph, reason, ...}`; a row may carry the IRIs and+/// instants it is about as fields, because each row is about one graph.+fn derive_lineage(map: &mut BTreeMap<String, GraphValidity>) -> Vec<serde_json::Value> {+ let mut reports: Vec<serde_json::Value> = Vec::new();++ // The inbound index: which readable graphs name each graph, per predicate.+ // A link from an unreadable graph joins no index and is reported here,+ // on the asserter's side like every other link that has no effect.+ //+ // A link that joins no index is also PRUNED from the asserter's lineage,+ // below, once this loop has finished reading the map. The report row is+ // the only place a rejected link survives: `conflicts` used to walk the+ // raw `supersedes` list and file a pair as a correction on a link this+ // pass had just said had no effect, a contradiction suppressed by a+ // link that closed nothing. Every consumer now walks effective links by+ // construction, so none can disagree with the report.+ let mut successors: BTreeMap<String, Vec<String>> = BTreeMap::new();+ let mut retractors: BTreeMap<String, Vec<String>> = BTreeMap::new();+ // (asserter, effective supersedes, effective retracts), for asserters+ // that lost at least one link.+ let mut pruned: Vec<(String, Vec<String>, Vec<String>)> = Vec::new();+ for (g, v) in map.iter() {+ let p = match v {+ GraphValidity::Sound(p) | GraphValidity::Degenerate { period: p, .. } => p,+ GraphValidity::Unreadable { asserted, .. } => {+ for (field, target) in asserted {+ reports.push(serde_json::json!({+ "graph": g,+ "reason": format!(+ "{field} is asserted by a graph whose own temporal description \+ could not be read; the link has no effect, and the graph it \+ names is neither closed nor withdrawn by it"+ ),+ "target": target,+ }));+ }+ continue;+ }+ };+ let mut kept_supersedes: Vec<String> = Vec::new();+ let mut kept_retracts: Vec<String> = Vec::new();+ for (field, targets, index, kept) in [+ (+ "supersedes",+ &p.lineage.supersedes,+ &mut successors,+ &mut kept_supersedes,+ ),+ (+ "retracts",+ &p.lineage.retracts,+ &mut retractors,+ &mut kept_retracts,+ ),+ ] {+ for target in targets {+ let fault = if target == g {+ Some("names the graph itself")+ } else {+ match map.get(target) {+ None => Some(+ "names a graph that carries no temporal description, whether or not \+ it exists, so there is nothing to close or withdraw",+ ),+ Some(GraphValidity::Unreadable { .. }) => Some(+ "names a graph whose temporal description could not be read, which \+ is invalid already",+ ),+ Some(_) => None,+ }+ };+ match fault {+ Some(why) => reports.push(serde_json::json!({+ "graph": g,+ "reason": format!("{field} {why}; the link has no effect"),+ "target": target,+ })),+ None => {+ index.entry(target.clone()).or_default().push(g.clone());+ kept.push(target.clone());+ }+ }+ }+ }+ if kept_supersedes.len() != p.lineage.supersedes.len()+ || kept_retracts.len() != p.lineage.retracts.len()+ {+ pruned.push((g.clone(), kept_supersedes, kept_retracts));+ }+ for (field, term) in &p.lineage.not_iris {+ reports.push(serde_json::json!({+ "graph": g,+ "reason": format!("{field} names a term that is not a graph IRI; the link has no effect"),+ "target": term,+ }));+ }+ }+ // From here on the map carries effective links only: a rejected one is+ // in `reports` and nowhere else, so the cycle walk below and the chain+ // walk in `conflicts` cannot follow it.+ for (g, supersedes, retracts) in pruned {+ if let Some(p) = map.get_mut(&g).and_then(period_mut) {+ p.lineage.supersedes = supersedes;+ p.lineage.retracts = retracts;+ }+ }++ // Close each superseded graph from its successors. Collected first and+ // applied after, since a successor is read from the same map.+ let mut closings: Vec<(String, DateTime<Utc>, String)> = Vec::new();+ for (x, succs) in &successors {+ let Some(p) = map.get(x).and_then(period_of) else {+ continue;+ };+ // (instant, lexical form, successor graph): sorted, the first is the+ // earliest, ties broken by the text and then the IRI so the answer+ // does not depend on row order.+ let mut dated: Vec<(DateTime<Utc>, String, String)> = Vec::new();+ for s in succs {+ let Some(sp) = map.get(s).and_then(period_of) else {+ continue;+ };+ match (sp.recorded, sp.shown.recorded_at.as_ref()) {+ (Some(at), Some(lexical)) => dated.push((at, lexical.clone(), s.clone())),+ _ => reports.push(serde_json::json!({+ "graph": x,+ "reason": "the graph that supersedes it carries no recordedAt, so the \+ replacement cannot be dated and this link leaves the \+ transaction interval as it was",+ "successor": s,+ })),+ }+ }+ dated.sort();+ let Some((earliest, _, closer)) = dated.first().cloned() else {+ continue;+ };+ let explicit = match (p.until, p.shown.recorded_until.as_ref()) {+ (Some(explicit), Some(explicit_lexical)) => {+ for (at, lexical, s) in &dated {+ if *at != explicit {+ reports.push(serde_json::json!({+ "graph": x,+ "reason": "explicit recordedUntil disagrees with the recordedAt of \+ the graph that supersedes it; the explicit bound governs",+ "successor": s,+ "recorded_until": explicit_lexical,+ "successor_recorded_at": lexical,+ }));+ }+ }+ Some(explicit_lexical.clone())+ }+ _ => {+ closings.push((x.clone(), earliest, closer.clone()));+ None+ }+ };+ // Multiplicity is a fact about the links, not about which bound+ // closed the graph, so it is reported on both branches in one row+ // shape: `closed_by` names the successor where the bound was derived,+ // and `recorded_until` the explicit bound where it was asserted, so+ // the row never names a successor as having closed what it did not.+ if dated.len() > 1 {+ let mut row = serde_json::json!({+ "graph": x,+ "reason": match explicit {+ Some(_) => "superseded by more than one graph; the explicit recordedUntil \+ governs, so none of them closed it, and a later successor does \+ not revive it",+ None => "superseded by more than one graph; belief in it ended at the \+ earliest recordedAt among them, and a later successor does not \+ revive it",+ },+ "successors": dated.iter().map(|(_, _, s)| s).collect::<Vec<_>>(),+ });+ match explicit {+ Some(lexical) => row["recorded_until"] = serde_json::Value::from(lexical),+ None => row["closed_by"] = serde_json::Value::from(closer.as_str()),+ }+ reports.push(row);+ }+ }++ // Retractors, earliest recorded first and the undated ones last.+ let mut withdrawals: Vec<(String, Vec<Retractor>)> = Vec::new();+ for (x, rets) in &retractors {+ let mut list: Vec<Retractor> = Vec::new();+ for r in rets {+ let Some(rp) = map.get(r).and_then(period_of) else {+ continue;+ };+ if rp.recorded.is_none() {+ reports.push(serde_json::json!({+ "graph": x,+ "reason": "retracted by a graph with no recordedAt, so the withdrawal cannot \+ be dated and stands at every as_of",+ "retracted_by": r,+ }));+ }+ list.push(Retractor {+ graph: r.clone(),+ recorded: rp.recorded,+ recorded_lexical: rp.shown.recorded_at.clone(),+ });+ }+ list.sort_by(|a, b| match (a.recorded, b.recorded) {+ (Some(x), Some(y)) => x.cmp(&y).then_with(|| a.graph.cmp(&b.graph)),+ (Some(_), None) => Ordering::Less,+ (None, Some(_)) => Ordering::Greater,+ (None, None) => a.graph.cmp(&b.graph),+ });+ withdrawals.push((x.clone(), list));+ }++ // Cycles. Iterative rather than recursive: a chain can be as long as the+ // map, and a worker thread's stack is not. The links are effective by+ // construction, pruned above: every child is a readable graph in the+ // map other than its parent, so the walk needs no guard against a+ // self-link or a target that is not there.+ fn children<'a>(map: &'a BTreeMap<String, GraphValidity>, g: &str) -> &'a [String] {+ map.get(g)+ .and_then(period_of)+ .map(|p| p.lineage.supersedes.as_slice())+ .unwrap_or(&[])+ }+ let mut done: BTreeSet<&str> = BTreeSet::new();+ let mut cycles: BTreeSet<Vec<String>> = BTreeSet::new();+ for start in map.keys() {+ if done.contains(start.as_str()) {+ continue;+ }+ let mut path: Vec<(&str, usize)> = vec![(start.as_str(), 0)];+ while let Some(&(g, i)) = path.last() {+ let Some(child) = children(map, g).get(i) else {+ path.pop();+ done.insert(g);+ continue;+ };+ if let Some(frame) = path.last_mut() {+ frame.1 = i + 1;+ }+ let c = child.as_str();+ if done.contains(c) {+ continue;+ }+ if let Some(k) = path.iter().position(|&(on_path, _)| on_path == c) {+ cycles.insert(+ path[k..]+ .iter()+ .map(|(on_path, _)| on_path.to_string())+ .collect(),+ );+ continue;+ }+ path.push((c, 0));+ }+ }+ for cycle in cycles {+ reports.push(serde_json::json!({+ "graph": cycle[0],+ "reason": "supersedes links form a cycle, so no graph in it is the latest version; \+ each bound is still derived from the direct successor and the walk \+ stops here",+ "cycle": cycle,+ }));+ }++ for (x, at, closer) in closings {+ if let Some(p) = map.get_mut(&x).and_then(period_mut) {+ p.until = Some(at);+ p.lineage.until_derived_from = Some(closer);+ }+ }+ for (x, list) in withdrawals {+ if let Some(p) = map.get_mut(&x).and_then(period_mut) {+ p.lineage.retracted_by = list;+ }+ }++ // Inverted transaction intervals, judged on the composed bound.+ let mut inverted: Vec<serde_json::Value> = Vec::new();+ for (g, v) in map.iter() {+ let Some(p) = period_of(v) else { continue };+ if !p.inverted_recording() {+ continue;+ }+ let mut row = serde_json::json!({+ "graph": g,+ "reason": "the transaction interval closes before it opens: recordedUntil precedes \+ recordedAt, an inverted transaction interval; nothing was clamped, and \+ the graph is believed at no instant",+ "recorded_at": p.shown.recorded_at,+ });+ match &p.lineage.until_derived_from {+ Some(s) => {+ row["superseded_by"] = serde_json::Value::from(s.as_str());+ row["recorded_until"] = serde_json::Value::from(+ map.get(s)+ .and_then(period_of)+ .and_then(|sp| sp.shown.recorded_at.clone()),+ );+ }+ None => row["recorded_until"] = serde_json::Value::from(p.shown.recorded_until.clone()),+ }+ inverted.push(row);+ }+ reports.extend(inverted);++ // One graph's rows together, whatever rule produced them.+ reports.sort_by(|a, b| a["graph"].as_str().cmp(&b["graph"].as_str()));+ reports+}+/// Literal or IRI as SPARQL returns it, without its wrapping.fn plain(value: &str) -> String {let v = value.trim();@@ -1032,14 +1611,26 @@ impl Temporal {})}- /// Every graph that carries validity metadata, and whether the scan that- /// found them was complete.- fn validities(&self) -> anyhow::Result<(BTreeMap<String, GraphValidity>, Capped)> {+ /// Every graph that carries validity or lineage metadata, whether the scan+ /// that found them was complete, and what the lineage pass reported.+ ///+ /// The lineage derivation runs here, on the map every consumer reads, so+ /// a graph closed by its successor is closed for the snapshot, the query+ /// and the conflict check alike.+ fn validities(+ &self,+ ) -> anyhow::Result<(+ BTreeMap<String, GraphValidity>,+ Capped,+ Vec<serde_json::Value>,+ )> {let query = format!(- "SELECT ?g ?from ?to ?rec ?until WHERE {{ \+ "SELECT ?g ?from ?to ?rec ?until ?sup ?ret WHERE {{ \{{ ?g <{NS}validFrom> ?from }} UNION {{ ?g <{NS}validTo> ?to }} \UNION {{ ?g <{NS}recordedAt> ?rec }} \- UNION {{ ?g <{NS}recordedUntil> ?until }} }}"+ UNION {{ ?g <{NS}recordedUntil> ?until }} \+ UNION {{ ?g <{NS}supersedes> ?sup }} \+ UNION {{ ?g <{NS}retracts> ?ret }} }}");let scan = self.rows(&query, self.limits.validity_scan)?;// 1.2.0 ASSIGNED each field here, so the last row of the UNION won@@ -1058,6 +1649,8 @@ impl Temporal {("to", &mut entry.to),("rec", &mut entry.recorded),("until", &mut entry.until),+ ("sup", &mut entry.supersedes),+ ("ret", &mut entry.retracts),] {if let Some(v) = row.get(key).and_then(|v| v.as_str()) {let term = v.trim().to_string();@@ -1067,11 +1660,12 @@ impl Temporal {}}}- let out = terms+ let mut out: BTreeMap<String, GraphValidity> = terms.into_iter().map(|(graph, bounds)| (graph.clone(), bounds.resolve(graph))).collect();- Ok((out, scan.capped))+ let lineage = derive_lineage(&mut out);+ Ok((out, scan.capped, lineage))}/// Named graphs holding assertions, whether or not they are described.@@ -1098,12 +1692,13 @@ impl Temporal {valid_at: Option<DateTime<Utc>>,as_of: Option<DateTime<Utc>>,) -> anyhow::Result<Scope> {- let (validities, validity_scan) = self.validities()?;+ let (validities, validity_scan, lineage) = self.validities()?;let (graphs, graph_scan) = self.all_graphs()?;let mut in_scope = Vec::new();let mut excluded = Vec::new();let mut invalid = Vec::new();+ let mut retracted = Vec::new();let mut names = Vec::new();for g in &graphs {// The readable period, and which shape it is when it holds at no@@ -1121,7 +1716,7 @@ impl Temporal {// 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)) => {+ Some(GraphValidity::Unreadable { faults, .. }) => {invalid.push(serde_json::json!({"graph": g,"reason": GraphValidity::fault_reason(faults),@@ -1147,6 +1742,25 @@ impl Temporal {// false for such a period regardless.Some(GraphValidity::Degenerate { period, kind }) => (period, Some(*kind)),};+ // Retraction is asked first, once the graph is readable at all: an+ // unreadable one answered above and stays invalid. It is a fact+ // about the assertion's standing, not about the instant asked+ // about, so it beats "not true at that instant" and both+ // recorded-side reasons; a graph that is both superseded and+ // retracted lands here. Before the retraction was recorded, and+ // with no `as_of` at all, the graph takes the ordinary path: with+ // no `as_of` the recorded axis is consulted for no fact, a+ // retraction no more than a `recordedUntil`, asserted or derived.+ if let Some(r) = p.retracted_as_of(as_of) {+ retracted.push(serde_json::json!({+ "graph": g,+ "valid": p.shown.describe(),+ "reason": "retracted",+ "retracted_by": r.graph,+ "retracted_at": r.recorded_lexical,+ }));+ continue;+ }// 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@@ -1161,15 +1775,27 @@ impl Temporal {in_scope.push(serde_json::json!({"graph": g, "valid": p.shown.describe()}));names.push(g.clone());} else {- excluded.push(serde_json::json!({+ let mut row = serde_json::json!({"graph": g,"valid": p.shown.describe(),"reason": if !valid_ok {kind.map_or("not true at that instant", Degenerate::reason)} else {- recorded_miss.unwrap_or("not yet recorded then")+ recorded_miss.map_or("not yet recorded then", RecordedMiss::reason)},- }));+ });+ // A closing bound that was derived names the graph it was+ // derived from: the row would otherwise say the interval had+ // closed and show no recordedUntil that closed it.+ let closed_by_successor = p+ .lineage+ .until_derived_from+ .as_deref()+ .filter(|_| valid_ok && recorded_miss.is_some_and(RecordedMiss::closed));+ if let Some(s) = closed_by_successor {+ row["superseded_by"] = serde_json::Value::from(s);+ }+ excluded.push(row);}}@@ -1177,6 +1803,8 @@ impl Temporal {in_scope,excluded,invalid,+ retracted,+ lineage,graphs: names,validity_scan,graph_scan,@@ -1202,6 +1830,12 @@ impl Temporal {if !scope.invalid.is_empty() {out["invalid"] = serde_json::Value::Array(scope.invalid.clone());}+ if !scope.retracted.is_empty() {+ out["retracted"] = serde_json::Value::Array(scope.retracted.clone());+ }+ if !scope.lineage.is_empty() {+ out["lineage"] = serde_json::Value::Array(scope.lineage.clone());+ }if let Some(warning) = scope.warning() {out["warning"] = serde_json::Value::String(format!("{warning} See truncated."));out["truncated"] = serde_json::Value::Array(scope.cuts());@@ -1233,6 +1867,8 @@ impl Temporal {let scope_warning = scope.warning();let scope_complete = scope.complete();let invalid = scope.invalid;+ let retracted = scope.retracted;+ let lineage = scope.lineage;let graphs = scope.graphs;if graphs.is_empty() {@@ -1246,6 +1882,12 @@ impl Temporal {if !invalid.is_empty() {out["invalid"] = serde_json::Value::Array(invalid);}+ if !retracted.is_empty() {+ out["retracted"] = serde_json::Value::Array(retracted);+ }+ if !lineage.is_empty() {+ out["lineage"] = serde_json::Value::Array(lineage);+ }if let Some(warning) = scope_warning {out["warning"] = serde_json::Value::String(format!("{warning} An empty scope here may mean \"nothing among the graphs that \@@ -1286,6 +1928,12 @@ impl Temporal {if !invalid.is_empty() {out["invalid"] = serde_json::Value::Array(invalid);}+ if !retracted.is_empty() {+ out["retracted"] = serde_json::Value::Array(retracted);+ }+ if !lineage.is_empty() {+ out["lineage"] = serde_json::Value::Array(lineage);+ }if !cuts.is_empty() {out["truncated"] = serde_json::Value::Array(cuts);}@@ -1318,8 +1966,17 @@ impl Temporal {/// missing coverage, not history, and reading it as a correction invents a/// continuity nobody asserted. Hence `non_overlapping`, and hence/// `superseded` being deprecated rather than redefined — see #110.+ ///+ /// The link the data did not carry, it now can. A pair where one graph+ /// asserts that it supersedes the other, directly or through a chain of+ /// `supersedes` links, is a correction whatever its periods: the issue's+ /// own example is a correction that shares its predecessor's valid period+ /// and was filed as a contradiction. Such a pair lands in `corrections`,+ /// checked before the overlap test, and lineage that is asserted is the+ /// only thing that puts it there. A retracted graph is not treated+ /// specially here.pub fn conflicts(&self) -> anyhow::Result<String> {- let (validities, validity_scan) = self.validities()?;+ let (validities, validity_scan, _lineage) = self.validities()?;let scan = self.rows("PREFIX owl: <http://www.w3.org/2002/07/owl#> \PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \@@ -1343,13 +2000,39 @@ impl Temporal {let timeless = Period::default();let period = |graph: &str| match validities.get(graph) {None => Some(&timeless),- Some(GraphValidity::Sound(p)) | Some(GraphValidity::Degenerate { period: p, .. }) => {- Some(p)+ Some(v) => period_of(v),+ };+ // Does `from` supersede `to`, directly or through a chain. Walks only+ // readable graphs in the map, each once, so a cycle ends the walk+ // rather than the process. The links it follows are EFFECTIVE by+ // construction: `derive_lineage` pruned every link it rejected (a+ // self-link, an undescribed or unreadable target) from the map+ // before handing it on, so a pair can land in `corrections` only on+ // a link the snapshot's `lineage` does not report as having no+ // effect. Reading the raw assertions here would let a link that+ // closed nothing suppress a genuine contradiction.+ let supersedes = |from: &str, to: &str| -> bool {+ let mut seen: BTreeSet<&str> = BTreeSet::new();+ let mut stack: Vec<&str> = vec![from];+ while let Some(g) = stack.pop() {+ if !seen.insert(g) {+ continue;+ }+ let Some(p) = validities.get(g).and_then(period_of) else {+ continue;+ };+ for s in &p.lineage.supersedes {+ if s == to {+ return true;+ }+ stack.push(s.as_str());+ }}- Some(GraphValidity::Unreadable(_)) => None,+ false};let mut conflicts = Vec::new();+ let mut corrections = Vec::new();let mut non_overlapping = Vec::new();let mut undecided = Vec::new();for row in &scan.rows {@@ -1375,13 +2058,26 @@ impl Temporal {continue;};- let entry = serde_json::json!({+ let mut entry = serde_json::json!({"subject": local(&s),"types": [local(&a), local(&b)],"periods": [va.shown.describe(), vb.shown.describe()],- "graphs": [ga, gb],+ "graphs": [&ga, &gb],});- if va.overlaps(vb) {+ // Asserted lineage first: a pair one side of which replaces the+ // other is a correction whatever the periods say, and the+ // overlap test is never reached for it.+ let link = if supersedes(&ga, &gb) {+ Some([&ga, &gb])+ } else if supersedes(&gb, &ga) {+ Some([&gb, &ga])+ } else {+ None+ };+ if let Some([successor, predecessor]) = link {+ entry["supersedes"] = serde_json::json!([successor, predecessor]);+ corrections.push(entry);+ } else if va.overlaps(vb) {conflicts.push(entry);} else {non_overlapping.push(entry);@@ -1392,8 +2088,8 @@ impl Temporal {// unconditionally until 2.0 and behind no flag: an opt-out would be a// third response shape to document and test, and it would let a client// code against a shape no release guarantees. It is deprecated, not- // renamed — when lineage-backed supersession arrives it gets a NEW- // key, so that no key ever names a different set across a major+ // renamed: lineage-backed supersession arrived as `corrections`, a+ // NEW key, so that no key ever names a different set across a major// version. See #110.let mut out = serde_json::json!({"ok": true,@@ -1415,6 +2111,10 @@ impl Temporal {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. \+ corrections are pairs where one graph asserts that it supersedes the \+ other, directly or through a chain of supersedes links, lineage that is \+ asserted and never inferred, and such a pair is never a contradiction \+ whatever its periods. \superseded is the same set as non_overlapping under a name that claimed \more than was proven; it is deprecated and will be dropped at 2.0.",});@@ -1429,7 +2129,9 @@ impl Temporal {"validities","pairs whose validity rows fell past the limit were compared as timeless, and \a timeless period overlaps everything: superseded corrections can appear here \- as contradictions",+ as contradictions; a supersedes row that fell past the limit while its \+ asserter's bounds did not was never seen, so the pair it links was compared \+ on its periods and can appear here as a contradiction too",),scan.capped.report("conflict_pairs",@@ -1441,6 +2143,10 @@ impl Temporal {.flatten().collect();+ if !corrections.is_empty() {+ out["corrections"] = serde_json::Value::Array(corrections.clone());+ out["corrections_count"] = serde_json::Value::from(corrections.len());+ }if !undecided.is_empty() {out["undecided"] = serde_json::Value::Array(undecided.clone());out["undecided_count"] = serde_json::Value::from(undecided.len());@@ -1451,8 +2157,9 @@ impl Temporal {if validity_scan.hit {out["warning"] = serde_json::Value::String("UNSOUND CLASSIFICATION: the validity scan hit its row limit, so some pairs \- were compared without their periods. A correction can be reported here as a \- contradiction, which is the one thing this tool exists to prevent; \+ were compared without their periods, or without the supersedes link that \+ would have pre-empted the comparison. A correction can be reported here as \+ a contradiction, which is the one thing this tool exists to prevent; \contradiction_count is an upper bound over the pairs that were examined, and \says nothing about any pair the candidate scan did not reach. See truncated.".to_string(),@@ -1670,6 +2377,51 @@ ex:g_after { ex:X a ex:Suspension . }assert_eq!(snap["complete"], true, "four rows do: {snap}");}+ /// The same graph, plus one `supersedes` link.+ const FULLY_DESCRIBED_WITH_LINK: &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" ;+ t:supersedes ex:g0 .+}+"#;++ /// The row cost of a lineage link, proved the same way. The link is a+ /// fifth UNION branch, so a graph carrying the four bounds and one+ /// `supersedes` costs five rows and 20,000 rows cover roughly 4,000 such+ /// graphs; with a `retracts` beside it, six rows and roughly 3,300. The+ /// test above is untouched: a graph without a link still costs four.+ #[test]+ fn a_fully_described_graph_with_a_supersedes_link_costs_five_validity_rows() {+ let cut = Temporal::with_limits(+ store(FULLY_DESCRIBED_WITH_LINK),+ Limits {+ validity_scan: 4,+ ..Limits::default()+ },+ );+ let snap = json(cut.snapshot(None, None).unwrap());+ assert_eq!(+ snap["complete"], false,+ "four rows no longer cover a graph that also asserts a link: {snap}"+ );++ let whole = Temporal::with_limits(+ store(FULLY_DESCRIBED_WITH_LINK),+ Limits {+ validity_scan: 5,+ ..Limits::default()+ },+ );+ let snap = json(whole.snapshot(None, None).unwrap());+ assert_eq!(snap["complete"], true, "five 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]@@ -1694,6 +2446,29 @@ ex:g_after { ex:X a ex:Suspension . }assert_eq!(snap["truncated"][0]["scan"], "validities");assert_eq!(snap["truncated"][0]["limit"], 2);+ // The validity UNION carries the lineage rows under the same cap, so+ // both texts must name the failure that costs: a graph whose own+ // bounds survived the cut but whose supersedes or retracts row did+ // not closed or withdrew nothing, and the graph it named stays open+ // or in scope although it is described. Neither text names a graph.+ for text in [+ snap["warning"].as_str().unwrap(),+ snap["truncated"][0]["consequence"].as_str().unwrap(),+ ] {+ assert!(+ text.contains("supersedes or retracts row"),+ "a cut lineage row is a third way the scope is wrong: {text}"+ );+ assert!(+ text.contains("described"),+ "and it happens to a described graph, which is the point: {text}"+ );+ assert!(+ !text.contains("http"),+ "no graph IRI belongs in a cap text: {text}"+ );+ }+// SPARQL does not order an unordered LIMIT, so WHICH graph lost its// description is not fixed — but exactly one did, whichever it was.let misclassified = snap["in_scope"]@@ -1823,6 +2598,21 @@ ex:g_after { ex:X a ex:Suspension . });assert_eq!(cut["truncated"][0]["scan"], "validities");assert_eq!(cut["truncated"][0]["limit"], 1);+ // The supersedes rows share the cap with the bounds, so a link can be+ // cut while both periods survive: the pair is then compared on+ // periods the link was meant to pre-empt. Both texts say so, and+ // neither names a graph.+ let consequence = cut["truncated"][0]["consequence"].as_str().unwrap();+ assert!(+ consequence.contains("supersedes row") && consequence.contains("never seen"),+ "a cut link is a second way a correction reads as a contradiction: {consequence}"+ );+ let warning = cut["warning"].as_str().unwrap();+ assert!(warning.contains("without the supersedes link"), "{warning}");+ assert!(+ !consequence.contains("http") && !warning.contains("http"),+ "{cut}"+ );}/// The pair scan is the mild cap: fewer pairs examined, no claim turneddiff --git a/tests/temporal_conformance_test.rs b/tests/temporal_conformance_test.rsindex d08a1ea6..0423dcc9 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 four sections. The first pins semantics that are **intended**;+//! The file has five 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@@ -22,7 +22,10 @@//! 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.+//! instant. The fifth covers lineage that is asserted, never inferred (#109):+//! `supersedes` and `retracts`, the closing bound derived from a successor and+//! never written, the `retracted` bucket, the `lineage` reports and the+//! `corrections` bucket, led by the issue's own example.//!//! Deliberately not feature-gated: a `#![cfg(feature = ...)]` on a test file//! that CI runs without that feature prints `running 0 tests` and reads as@@ -266,15 +269,25 @@ fn recorded_interval_is_half_open_at_the_upper_bound() {/// 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.+/// fail the same way for the seventh predicate someone adds without wiring.+/// Each predicate gets an object of its own type: the four bounds a date,+/// the two lineage links a graph IRI, since a literal is not a legal object+/// for them and would test the report rather than the map.#[test]fn every_temporal_predicate_takes_its_graph_out_of_the_timeless_bucket() {- for predicate in ["validFrom", "validTo", "recordedAt", "recordedUntil"] {+ for (predicate, object) in [+ ("validFrom", "\"2024-01-01\""),+ ("validTo", "\"2024-01-01\""),+ ("recordedAt", "\"2024-01-01\""),+ ("recordedUntil", "\"2024-01-01\""),+ ("supersedes", "ex:g_other"),+ ("retracts", "ex:g_other"),+ ] {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"+ {{ ex:g_only t:{predicate} {object} . }}\n");let snap = snapshot(&temporal(&trig), None, None);let row = snap["in_scope"]@@ -567,6 +580,11 @@ fn the_note_claims_only_what_the_code_checks() {!note.contains("one period ends where the other begins"),"adjacency is never established by `!overlaps`: {note}");+ assert!(+ note.contains("corrections") && note.contains("asserted and never inferred"),+ "and must say what puts a pair in corrections, which is an asserted link and \+ nothing about its periods: {note}"+ );}/// Two periods that DO share an hour, written with different timezone offsets.@@ -1612,3 +1630,869 @@ fn a_period_that_holds_nowhere_beside_an_unreadable_one_is_still_undecided() {assert!(invalid_reason(&open, "g_bad").is_some(), "{open}");assert!(graphs(&open, "in_scope").contains("g_empty"), "{open}");}++// ---------------------------------------------------------------------------+// Section 5: lineage that is asserted, never inferred (#109)+//+// `as_of` only narrowed forward, and nothing linked one version to the next:+// a correction sharing its predecessor's valid period was filed as a+// contradiction, and with no explicit recordedUntil the predecessor stayed+// believed for ever. Two predicates on the NEWER graph carry the link:+// `supersedes` names the graph it replaces, `retracts` the graph it withdraws+// without replacing. recordedUntil alone governs scope; where a graph carries+// none, its closing bound is DERIVED from the successor's recordedAt at query+// time and never written, and where both are present and disagree the explicit+// bound governs and the disagreement is reported. The issue's own example+// leads.+// ---------------------------------------------------------------------------++/// The row for one graph in one snapshot bucket, named by its local part.+/// Panics rather than returning an Option: every caller is asserting on the+/// row, so a missing one is a failed test.+fn bucket_row(snapshot: &serde_json::Value, bucket: &str, local: &str) -> serde_json::Value {+ snapshot[bucket]+ .as_array()+ .unwrap_or_else(|| panic!("snapshot has no array `{bucket}`: {snapshot}"))+ .iter()+ .find(|row| row["graph"].as_str().is_some_and(|g| g.ends_with(local)))+ .cloned()+ .unwrap_or_else(|| panic!("`{local}` is not in `{bucket}`: {snapshot}"))+}++/// The lineage rows about one graph. Empty, not a panic, when the key is+/// absent: a clean answer carries no `lineage` at all.+fn lineage_about(snapshot: &serde_json::Value, local: &str) -> Vec<serde_json::Value> {+ snapshot+ .get("lineage")+ .and_then(|l| l.as_array())+ .map(|rows| {+ rows.iter()+ .filter(|row| row["graph"].as_str().is_some_and(|g| g.ends_with(local)))+ .cloned()+ .collect()+ })+ .unwrap_or_default()+}++/// Issue #109's own example: the correction shares its predecessor's valid+/// period, the predecessor carries no recordedUntil, and the successor says+/// which graph it replaces.+const ISSUE_109: &str = r#"+@prefix ex: <http://example.org/> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g1 { ex:HEK293 a ex:AdherentCellLine . }+ex:g2 { ex:HEK293 a ex:SuspensionCellLine . }++{+ ex:AdherentCellLine owl:disjointWith ex:SuspensionCellLine .+ ex:g1 t:validFrom "2024-01-01" ; t:recordedAt "2024-01-05" .+ ex:g2 t:validFrom "2024-01-01" ; t:recordedAt "2026-06-01" ; t:supersedes ex:g1 .+}+"#;++#[test]+fn a_successor_closes_its_predecessor_at_its_own_recorded_at() {+ let t = temporal(ISSUE_109);+ // After the correction was recorded: the predecessor is no longer+ // believed, and the row says which graph closed it, since it carries no+ // recordedUntil of its own that could.+ let after = snapshot(&t, None, Some("2026-07-01"));+ assert_eq!(graphs(&after, "in_scope"), set(&["g2"]), "{after}");+ assert_eq!(reason(&after, "g1"), "no longer recorded then", "{after}");+ assert!(+ bucket_row(&after, "excluded", "g1")["superseded_by"]+ .as_str()+ .is_some_and(|g| g.ends_with("g2")),+ "the derived bound names the graph it was derived from: {after}"+ );+ assert!(after.get("lineage").is_none(), "nothing to report: {after}");+ // Before it: the predecessor was what was believed, and the successor+ // had not arrived.+ let before = snapshot(&t, None, Some("2025-01-01"));+ assert_eq!(graphs(&before, "in_scope"), set(&["g1"]), "{before}");+ assert_eq!(reason(&before, "g2"), "not yet recorded then", "{before}");+ // With no as_of no instant was asked about on the recorded axis, and a+ // derived bound is read exactly as an asserted recordedUntil is: both+ // graphs are in scope, as `g_first` is in CORRECTED with no as_of. The+ // derivation composes a bound; it does not change what the axis means.+ let open = snapshot(&t, None, None);+ assert_eq!(graphs(&open, "in_scope"), set(&["g1", "g2"]), "{open}");+ assert!(graphs(&open, "excluded").is_empty(), "{open}");+}++#[test]+fn a_correction_that_shares_its_predecessors_period_is_not_a_contradiction() {+ let t = temporal(ISSUE_109);+ let out = conflicts(&t);+ // Both graphs claim [2024-01-01, open) for disjoint types. On the periods+ // alone that is a contradiction, and it was filed as one; the link says+ // it is a correction, and the link is the only thing that can.+ assert_eq!(out["contradiction_count"], 0, "{out}");+ assert_eq!(out["non_overlapping_count"], 0, "{out}");+ assert_eq!(out["corrections_count"], 1, "{out}");+ assert_eq!(partners(&out, "corrections"), set(&["g1", "g2"]), "{out}");+ let link = out["corrections"][0]["supersedes"].as_array().unwrap();+ assert!(+ link[0].as_str().unwrap().ends_with("g2") && link[1].as_str().unwrap().ends_with("g1"),+ "successor first, predecessor second: {out}"+ );+ let note = out["note"].as_str().unwrap();+ assert!(+ note.contains("corrections") && note.contains("whatever its periods"),+ "the note says the periods are not consulted for such a pair: {note}"+ );+ // And a store with no link still has no corrections key at all.+ let plain = conflicts(&temporal(CONFLICT_OVERLAP));+ assert!(plain.get("corrections").is_none(), "{plain}");+ assert!(plain.get("corrections_count").is_none(), "{plain}");+}++/// The predecessor carries its own recordedUntil, five months before the+/// successor says it was recorded.+const EXPLICIT_DISAGREES: &str = r#"+@prefix ex: <http://example.org/> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g1 { ex:HEK293 a ex:AdherentCellLine . }+ex:g2 { ex:HEK293 a ex:SuspensionCellLine . }++{+ ex:g1 t:validFrom "2024-01-01" ; t:recordedAt "2024-01-05" ; t:recordedUntil "2026-01-01" .+ ex:g2 t:validFrom "2024-01-01" ; t:recordedAt "2026-06-01" ; t:supersedes ex:g1 .+}+"#;++#[test]+fn an_explicit_recorded_until_governs_and_its_disagreement_with_the_successor_is_reported() {+ let t = temporal(EXPLICIT_DISAGREES);+ // Between the two instants: the explicit bound has closed the interval,+ // the successor has not arrived. A derivation that yielded to the+ // successor would put g1 back in scope here.+ let between = snapshot(&t, None, Some("2026-03-01"));+ assert_eq!(+ reason(&between, "g1"),+ "no longer recorded then",+ "{between}"+ );+ assert!(+ bucket_row(&between, "excluded", "g1")+ .get("superseded_by")+ .is_none(),+ "an asserted bound was not derived from anything: {between}"+ );+ assert_eq!(reason(&between, "g2"), "not yet recorded then", "{between}");+ assert!(graphs(&between, "in_scope").is_empty(), "{between}");+ // The inconsistency survives in the report, naming both instants and+ // both graphs, and is reconciled nowhere.+ let rows = lineage_about(&between, "g1");+ assert_eq!(rows.len(), 1, "{between}");+ let row = &rows[0];+ assert!(+ row["reason"]+ .as_str()+ .unwrap()+ .contains("explicit recordedUntil disagrees"),+ "{row}"+ );+ assert!(+ row["reason"]+ .as_str()+ .unwrap()+ .contains("explicit bound governs"),+ "{row}"+ );+ assert!(row["successor"].as_str().unwrap().ends_with("g2"), "{row}");+ assert_eq!(row["recorded_until"], "2026-01-01", "{row}");+ assert_eq!(row["successor_recorded_at"], "2026-06-01", "{row}");+ // Before the explicit bound the predecessor is believed, as asserted.+ let early = snapshot(&t, None, Some("2025-06-01"));+ assert_eq!(graphs(&early, "in_scope"), set(&["g1"]), "{early}");+}++/// Out-of-order recording: the successor says it was recorded five months+/// BEFORE the predecessor it replaces.+const OUT_OF_ORDER: &str = r#"+@prefix ex: <http://example.org/> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g_old { ex:HEK293 a ex:AdherentCellLine . }+ex:g_new { ex:HEK293 a ex:SuspensionCellLine . }++{+ ex:g_old t:validFrom "2024-01-01" ; t:recordedAt "2024-06-01" .+ ex:g_new t:validFrom "2024-01-01" ; t:recordedAt "2024-01-01" ; t:supersedes ex:g_old .+}+"#;++#[test]+fn a_successor_recorded_before_its_predecessor_makes_an_inverted_interval_that_is_reported_not_clamped()+ {+ let t = temporal(OUT_OF_ORDER);+ // Before, between, at and after the two instants: a clamp to an empty+ // interval, or to `[recordedAt, recordedAt)`, would still exclude the+ // graph everywhere, so the assertions below pin the REASON and the+ // reported instants, which a clamp would change.+ for as_of in ["2023-01-01", "2024-03-01", "2024-06-01", "2030-01-01"] {+ let snap = snapshot(&t, None, Some(as_of));+ let why = reason(&snap, "g_old");+ assert!(+ why.contains("believed at no instant") && why.contains("closes before it opens"),+ "as_of {as_of}: the reason names the shape, not a side of the interval: {why}"+ );+ assert_eq!(+ bucket_row(&snap, "excluded", "g_old")["valid"],+ "2024-01-01 to still true",+ "as_of {as_of}: the asserted bounds are shown untouched: {snap}"+ );+ let rows = lineage_about(&snap, "g_old");+ assert_eq!(rows.len(), 1, "as_of {as_of}: {snap}");+ let row = &rows[0];+ assert!(+ row["reason"]+ .as_str()+ .unwrap()+ .contains("inverted transaction interval"),+ "{row}"+ );+ assert_eq!(row["recorded_at"], "2024-06-01", "as asserted: {row}");+ assert_eq!(+ row["recorded_until"], "2024-01-01",+ "as derived from the successor, not moved: {row}"+ );+ assert!(+ row["superseded_by"].as_str().unwrap().ends_with("g_new"),+ "{row}"+ );+ }+ // The successor itself is believed from its own recordedAt.+ let mid = snapshot(&t, None, Some("2024-03-01"));+ assert_eq!(graphs(&mid, "in_scope"), set(&["g_new"]), "{mid}");+ // With no as_of no instant was asked about, and the graph is read like+ // any other, mirroring the rule for a valid period that holds nowhere.+ let open = snapshot(&t, None, None);+ assert_eq!(+ graphs(&open, "in_scope"),+ set(&["g_old", "g_new"]),+ "{open}"+ );+ assert!(+ !lineage_about(&open, "g_old").is_empty(),+ "and the report is still there to read: {open}"+ );+}++/// A correction of a correction: three versions, each superseding the last,+/// of three pairwise disjoint types.+const CHAIN: &str = r#"+@prefix ex: <http://example.org/> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g1 { ex:HEK293 a ex:AdherentCellLine . }+ex:g2 { ex:HEK293 a ex:SuspensionCellLine . }+ex:g3 { ex:HEK293 a ex:HybridCellLine . }++{+ ex:AdherentCellLine owl:disjointWith ex:SuspensionCellLine , ex:HybridCellLine .+ ex:SuspensionCellLine owl:disjointWith ex:HybridCellLine .+ ex:g1 t:validFrom "2024-01-01" ; t:recordedAt "2024-01-05" .+ ex:g2 t:validFrom "2024-01-01" ; t:recordedAt "2025-01-05" ; t:supersedes ex:g1 .+ ex:g3 t:validFrom "2024-01-01" ; t:recordedAt "2026-01-05" ; t:supersedes ex:g2 .+}+"#;++#[test]+fn a_chain_of_supersedes_links_needs_no_special_machinery() {+ let t = temporal(CHAIN);+ // After the third version only it is believed, and each predecessor+ // names its own direct successor: the bound is derived one hop at a time.+ let late = snapshot(&t, None, Some("2026-06-01"));+ assert_eq!(graphs(&late, "in_scope"), set(&["g3"]), "{late}");+ for (graph, successor) in [("g1", "g2"), ("g2", "g3")] {+ assert_eq!(reason(&late, graph), "no longer recorded then", "{late}");+ assert!(+ bucket_row(&late, "excluded", graph)["superseded_by"]+ .as_str()+ .is_some_and(|g| g.ends_with(successor)),+ "{graph} is closed by {successor}: {late}"+ );+ }+ assert!(+ late.get("lineage").is_none(),+ "a clean chain reports nothing: {late}"+ );+ // In the middle the second version is the one believed.+ let mid = snapshot(&t, None, Some("2025-06-01"));+ assert_eq!(graphs(&mid, "in_scope"), set(&["g2"]), "{mid}");+ // Every pair is disjoint and every pair shares the whole period. The+ // direct pairs are corrections by their own link, and the pair at the+ // two ends of the chain is one through it: nothing in the data says g3+ // supersedes g1, and nothing needs to.+ let out = conflicts(&t);+ assert_eq!(out["contradiction_count"], 0, "{out}");+ assert_eq!(out["corrections_count"], 3, "{out}");+ let ends = out["corrections"]+ .as_array()+ .unwrap()+ .iter()+ .find(|row| {+ let graphs: BTreeSet<String> = row["graphs"]+ .as_array()+ .unwrap()+ .iter()+ .map(|g| g.as_str().unwrap().rsplit('/').next().unwrap().to_string())+ .collect();+ graphs == set(&["g1", "g3"])+ })+ .unwrap_or_else(|| panic!("the pair at the ends of the chain is a correction: {out}"));+ let link = ends["supersedes"].as_array().unwrap();+ assert!(+ link[0].as_str().unwrap().ends_with("g3") && link[1].as_str().unwrap().ends_with("g1"),+ "through the chain, g3 supersedes g1: {ends}"+ );+}++/// One graph replaced twice, by two successors a year apart.+const TWO_SUCCESSORS: &str = r#"+@prefix ex: <http://example.org/> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g1 { ex:HEK293 a ex:AdherentCellLine . }+ex:g2 { ex:HEK293 a ex:SuspensionCellLine . }+ex:g3 { ex:HEK293 a ex:HybridCellLine . }++{+ ex:g1 t:validFrom "2024-01-01" ; t:recordedAt "2024-01-05" .+ ex:g2 t:validFrom "2024-01-01" ; t:recordedAt "2025-01-05" ; t:supersedes ex:g1 .+ ex:g3 t:validFrom "2024-01-01" ; t:recordedAt "2026-01-05" ; t:supersedes ex:g1 .+}+"#;++#[test]+fn the_earliest_of_two_successors_closes_the_graph_and_the_multiplicity_is_reported() {+ let t = temporal(TWO_SUCCESSORS);+ // Between the two replacements. Belief in g1 ended at the first, and the+ // second does not revive it; a derivation that took the latest successor+ // would put g1 back in scope here.+ let between = snapshot(&t, None, Some("2025-06-01"));+ assert_eq!(graphs(&between, "in_scope"), set(&["g2"]), "{between}");+ assert_eq!(+ reason(&between, "g1"),+ "no longer recorded then",+ "{between}"+ );+ assert!(+ bucket_row(&between, "excluded", "g1")["superseded_by"]+ .as_str()+ .is_some_and(|g| g.ends_with("g2")),+ "closed by the earliest: {between}"+ );+ let rows = lineage_about(&between, "g1");+ assert_eq!(rows.len(), 1, "{between}");+ let row = &rows[0];+ assert!(+ row["reason"]+ .as_str()+ .unwrap()+ .contains("more than one graph"),+ "{row}"+ );+ assert!(row["closed_by"].as_str().unwrap().ends_with("g2"), "{row}");+ assert_eq!(row["successors"].as_array().unwrap().len(), 2, "{row}");+}++/// One graph replaced twice at the very instant its own recordedUntil names:+/// the explicit bound agrees with both successors, so no disagreement, and+/// neither successor closed anything.+const TWO_SUCCESSORS_EXPLICIT_CLOSE: &str = r#"+@prefix ex: <http://example.org/> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g1 { ex:HEK293 a ex:AdherentCellLine . }+ex:g2 { ex:HEK293 a ex:SuspensionCellLine . }+ex:g3 { ex:HEK293 a ex:HybridCellLine . }++{+ ex:g1 t:validFrom "2024-01-01" ; t:recordedAt "2024-01-05" ; t:recordedUntil "2026-06-01" .+ ex:g2 t:validFrom "2024-01-01" ; t:recordedAt "2026-06-01" ; t:supersedes ex:g1 .+ ex:g3 t:validFrom "2024-01-01" ; t:recordedAt "2026-06-01" ; t:supersedes ex:g1 .+}+"#;++#[test]+fn more_than_one_successor_is_reported_under_an_explicit_close_too() {+ let t = temporal(TWO_SUCCESSORS_EXPLICIT_CLOSE);+ let after = snapshot(&t, None, Some("2026-07-01"));+ // The explicit bound closed the graph, and nothing was derived.+ assert_eq!(reason(&after, "g1"), "no longer recorded then", "{after}");+ assert!(+ bucket_row(&after, "excluded", "g1")+ .get("superseded_by")+ .is_none(),+ "{after}"+ );+ // Exactly one lineage row: the multiplicity. No disagreement, since both+ // successors name the explicit instant, and a report that only spoke on+ // the derived branch would leave nothing here at all.+ let rows = lineage_about(&after, "g1");+ assert_eq!(rows.len(), 1, "{after}");+ let row = &rows[0];+ let reason = row["reason"].as_str().unwrap();+ assert!(reason.contains("more than one graph"), "{row}");+ assert!(+ reason.contains("explicit recordedUntil governs"),+ "the row says which bound closed it: {row}"+ );+ assert!(!reason.contains("disagrees"), "{row}");+ let successors: BTreeSet<String> = row["successors"]+ .as_array()+ .unwrap()+ .iter()+ .map(|s| s.as_str().unwrap().rsplit('/').next().unwrap().to_string())+ .collect();+ assert_eq!(successors, set(&["g2", "g3"]), "{row}");+ // The row names the explicit bound, not a successor, as what closed it:+ // `closed_by` is a graph on the derived branch and would be a lie here.+ assert_eq!(row["recorded_until"], "2026-06-01", "{row}");+ assert!(row.get("closed_by").is_none(), "{row}");+}++/// Two graphs each claiming to supersede the other.+const CYCLE: &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_a { ex:HEK293 a ex:AdherentCellLine . }+ex:g_b { ex:HEK293 a ex:SuspensionCellLine . }++{+ ex:AdherentCellLine owl:disjointWith ex:SuspensionCellLine .+ ex:g_a t:validFrom "2024-01-01" ; t:recordedAt "2024-01-05" ; t:supersedes ex:g_b .+ ex:g_b t:validFrom "2024-01-01" ; t:recordedAt "2025-01-05" ; t:supersedes ex:g_a .+}+"#;++#[test]+fn a_cycle_of_supersedes_links_is_reported_and_does_not_hang() {+ let t = temporal(CYCLE);+ // Returning at all is the first assertion. Each bound is still derived+ // from the direct successor: g_a closes at g_b's recordedAt, and g_b at+ // g_a's, which precedes its own and so is an inverted interval.+ let snap = snapshot(&t, None, Some("2024-06-01"));+ assert_eq!(graphs(&snap, "in_scope"), set(&["g_a"]), "{snap}");+ assert!(+ reason(&snap, "g_b").contains("believed at no instant"),+ "{snap}"+ );+ let cycle = snap["lineage"]+ .as_array()+ .unwrap()+ .iter()+ .find(|row| row["reason"].as_str().is_some_and(|r| r.contains("cycle")))+ .unwrap_or_else(|| panic!("the cycle is reported: {snap}"));+ assert_eq!(cycle["cycle"].as_array().unwrap().len(), 2, "{cycle}");+ // The conflict check walks the same links and stops too. Each graph+ // asserts that it supersedes the other, so the pair is a correction.+ let out = conflicts(&t);+ assert_eq!(out["contradiction_count"], 0, "{out}");+ assert_eq!(out["corrections_count"], 1, "{out}");+}++/// A withdrawal: `r` retracts `g1` a year after it was recorded, and puts+/// nothing in its place. A timeless graph sits beside them for the query.+const RETRACTED: &str = r#"+@prefix ex: <http://example.org/> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g1 { ex:HEK293 a ex:AdherentCellLine . }+ex:r { ex:HEK293 ex:note "withdrawn" . }+ex:g_species { ex:HEK293 ex:species ex:Human . }++{+ ex:g1 t:validFrom "2024-01-01" ; t:recordedAt "2024-01-05" .+ ex:r t:recordedAt "2025-01-01" ; t:retracts ex:g1 .+}+"#;++#[test]+fn a_retracted_graph_leaves_scope_from_the_retraction_and_stays_visible_in_its_own_bucket() {+ let t = temporal(RETRACTED);+ // Before the retraction was recorded, g1 takes the ordinary path.+ let before = snapshot(&t, None, Some("2024-06-01"));+ assert!(graphs(&before, "in_scope").contains("g1"), "{before}");+ assert!(before.get("retracted").is_none(), "{before}");+ // From the retraction on: in neither in_scope nor excluded, and the row+ // names the graph that withdrew it and when.+ let as_of = Some("2025-06-01");+ let snap = snapshot(&t, None, as_of);+ assert!(!graphs(&snap, "in_scope").contains("g1"), "{snap}");+ assert!(+ !graphs(&snap, "excluded").contains("g1"),+ "a withdrawn claim did not fail a bound: {snap}"+ );+ let row = bucket_row(&snap, "retracted", "g1");+ assert_eq!(row["reason"], "retracted", "{row}");+ assert!(+ row["retracted_by"].as_str().unwrap().ends_with("/r"),+ "{row}"+ );+ assert_eq!(row["retracted_at"], "2025-01-01", "{row}");+ assert_eq!(row["valid"], "2024-01-01 to still true", "{row}");+ // And the query does not read its triples.+ let raw = t.query_at("{ ?s a ?type }", None, as_of).unwrap();+ assert!(+ !raw.contains("AdherentCellLine"),+ "a retracted graph is not queried: {raw}"+ );+ let out: serde_json::Value = serde_json::from_str(&raw).unwrap();+ assert_eq!(+ bucket_row(&out, "retracted", "g1")["reason"],+ "retracted",+ "and the query says why it was left out: {out}"+ );+ // With no as_of the recorded axis is not consulted, for a retraction no+ // more than for a recordedUntil, asserted or derived: one rule for every+ // recorded-time fact. The graph takes the ordinary path and is in scope,+ // and the query reads it.+ let none = snapshot(&t, None, None);+ assert!(graphs(&none, "in_scope").contains("g1"), "{none}");+ assert!(none.get("retracted").is_none(), "{none}");+ let raw = t.query_at("{ ?s a ?type }", None, None).unwrap();+ assert!(+ raw.contains("AdherentCellLine"),+ "with no as_of the graph is read like any other: {raw}"+ );+ let out: serde_json::Value = serde_json::from_str(&raw).unwrap();+ assert!(out.get("retracted").is_none(), "{out}");+ // Retraction is a fact about the assertion's standing and is asked+ // first: at an instant the period does not hold at, the row is still in+ // retracted rather than excluded as not true then. With no as_of the+ // ordinary path answers, and that path excludes it as not true then.+ let early = snapshot(&t, Some("2020-01-01"), as_of);+ assert!(!graphs(&early, "excluded").contains("g1"), "{early}");+ assert_eq!(+ bucket_row(&early, "retracted", "g1")["reason"],+ "retracted",+ "{early}"+ );+ let early_none = snapshot(&t, Some("2020-01-01"), None);+ assert_eq!(+ reason(&early_none, "g1"),+ "not true at that instant",+ "{early_none}"+ );+ assert!(early_none.get("retracted").is_none(), "{early_none}");+}++/// Links that assert nothing readable: a successor naming a graph nobody+/// described, a retractor with no recordedAt, and a literal where a graph+/// IRI belongs.+const UNSETTLED_LINKS: &str = r#"+@prefix ex: <http://example.org/> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g1 { ex:HEK293 a ex:AdherentCellLine . }+ex:g_x { ex:HEK293 a ex:SuspensionCellLine . }+ex:r { ex:HEK293 ex:note "withdrawn" . }+ex:g_lit { ex:HEK293 a ex:HybridCellLine . }++{+ ex:g1 t:validFrom "2024-01-01" ; t:recordedAt "2024-01-05" .+ ex:g_x t:recordedAt "2025-01-05" ; t:supersedes ex:nowhere .+ ex:r t:retracts ex:g1 .+ ex:g_lit t:recordedAt "2025-01-05" ; t:supersedes "g1" .+}+"#;++#[test]+fn a_link_that_asserts_nothing_readable_is_reported_and_has_no_effect() {+ let t = temporal(UNSETTLED_LINKS);+ let snap = snapshot(&t, None, Some("2026-01-01"));+ // An unknown target: reported, and nothing closed.+ let rows = lineage_about(&snap, "g_x");+ assert_eq!(rows.len(), 1, "{snap}");+ assert!(+ rows[0]["reason"]+ .as_str()+ .unwrap()+ .contains("no temporal description"),+ "{snap}"+ );+ assert!(+ rows[0]["target"].as_str().unwrap().ends_with("nowhere"),+ "{snap}"+ );+ assert!(graphs(&snap, "in_scope").contains("g_x"), "{snap}");+ // A literal where a graph IRI belongs: reported, and g1 is not closed by+ // it, which the retraction below is what takes g1 out of scope instead.+ let rows = lineage_about(&snap, "g_lit");+ assert_eq!(rows.len(), 1, "{snap}");+ assert!(+ rows[0]["reason"]+ .as_str()+ .unwrap()+ .contains("not a graph IRI"),+ "{snap}"+ );+ assert_eq!(+ rows[0]["target"], "\"g1\"",+ "the term is quoted as written: {snap}"+ );+ // An undated retractor: the withdrawal cannot be dated, is reported as+ // such, and stands at every instant asked about, including one before+ // g1 was recorded at all: a withdrawal at an unknown time is still a+ // withdrawal. With no as_of no instant is asked about on the recorded+ // axis, and the graph is in scope like one closed by a recordedUntil.+ let rows = lineage_about(&snap, "g1");+ assert_eq!(rows.len(), 1, "{snap}");+ assert!(+ rows[0]["reason"]+ .as_str()+ .unwrap()+ .contains("cannot be dated"),+ "{snap}"+ );+ for as_of in [Some("2026-01-01"), Some("2000-01-01")] {+ let snap = snapshot(&t, None, as_of);+ let row = bucket_row(&snap, "retracted", "g1");+ assert!(+ row["retracted_by"].as_str().unwrap().ends_with("/r"),+ "as_of {as_of:?}: {row}"+ );+ assert!(row["retracted_at"].is_null(), "undated: {row}");+ assert!(!graphs(&snap, "excluded").contains("g1"), "{snap}");+ }+ let none = snapshot(&t, None, None);+ assert!(graphs(&none, "in_scope").contains("g1"), "{none}");+ assert!(none.get("retracted").is_none(), "{none}");+}++/// Links asserted by graphs whose own description could not be read: a+/// successor and a retractor, each with a recordedAt that is not a date.+const UNREADABLE_LINKERS: &str = r#"+@prefix ex: <http://example.org/> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g1 { ex:HEK293 a ex:AdherentCellLine . }+ex:g2 { ex:HEK293 a ex:SuspensionCellLine . }+ex:r { ex:HEK293 ex:note "withdrawn" . }++{+ ex:g1 t:validFrom "2024-01-01" ; t:recordedAt "2024-01-05" .+ ex:g2 t:recordedAt "garbage" ; t:supersedes ex:g1 .+ ex:r t:recordedAt "nope" ; t:retracts ex:g1 .+}+"#;++#[test]+fn a_link_asserted_by_an_unreadable_graph_is_reported_and_leaves_its_target_as_it_was() {+ let t = temporal(UNREADABLE_LINKERS);+ for as_of in [Some("2030-01-01"), None] {+ let snap = snapshot(&t, None, as_of);+ // The asserters are invalid for their own bounds, as before.+ assert!(invalid_reason(&snap, "g2").is_some(), "{snap}");+ assert!(invalid_reason(&snap, "/r").is_some(), "{snap}");+ // Neither link takes effect: g1 is neither closed nor withdrawn.+ assert_eq!(graphs(&snap, "in_scope"), set(&["g1"]), "{snap}");+ assert!(snap.get("retracted").is_none(), "{snap}");+ assert!(lineage_about(&snap, "g1").is_empty(), "{snap}");+ // But neither is dropped silently: each asserter's row names the+ // link and the graph it would have closed or withdrawn.+ for (local, field) in [("g2", "supersedes"), ("/r", "retracts")] {+ let rows = lineage_about(&snap, local);+ assert_eq!(rows.len(), 1, "{local}: {snap}");+ let reason = rows[0]["reason"].as_str().unwrap();+ assert!(reason.starts_with(field), "{local}: {snap}");+ assert!(reason.contains("could not be read"), "{local}: {snap}");+ assert!(reason.contains("no effect"), "{local}: {snap}");+ assert!(+ rows[0]["target"].as_str().unwrap().ends_with("g1"),+ "{local}: {snap}"+ );+ }+ }+}++/// One graph both superseded and, later, retracted.+const SUPERSEDED_AND_RETRACTED: &str = r#"+@prefix ex: <http://example.org/> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g1 { ex:HEK293 a ex:AdherentCellLine . }+ex:g2 { ex:HEK293 a ex:SuspensionCellLine . }+ex:r { ex:HEK293 ex:note "withdrawn" . }++{+ ex:g1 t:validFrom "2024-01-01" ; t:recordedAt "2024-01-05" .+ ex:g2 t:validFrom "2024-01-01" ; t:recordedAt "2025-01-01" ; t:supersedes ex:g1 .+ ex:r t:recordedAt "2026-01-01" ; t:retracts ex:g1 .+}+"#;++#[test]+fn a_graph_both_superseded_and_retracted_is_retracted_once_the_retraction_is_recorded() {+ let t = temporal(SUPERSEDED_AND_RETRACTED);+ // Between the two: closed by its successor, and the row says so.+ let between = snapshot(&t, None, Some("2025-06-01"));+ assert_eq!(+ reason(&between, "g1"),+ "no longer recorded then",+ "{between}"+ );+ assert!(+ bucket_row(&between, "excluded", "g1")["superseded_by"]+ .as_str()+ .is_some_and(|g| g.ends_with("g2")),+ "{between}"+ );+ assert!(between.get("retracted").is_none(), "{between}");+ // From the retraction on: retraction is a fact about the assertion's+ // standing and beats the derived closing bound, so the graph is in+ // `retracted`, not `excluded`.+ let snap = snapshot(&t, None, Some("2027-01-01"));+ assert!(!graphs(&snap, "excluded").contains("g1"), "{snap}");+ let row = bucket_row(&snap, "retracted", "g1");+ assert!(+ row["retracted_by"].as_str().unwrap().ends_with("/r"),+ "{row}"+ );+ assert_eq!(row["retracted_at"], "2026-01-01", "{row}");+ // With no as_of neither recorded-time fact is consulted, the derived+ // bound no more than the retraction: the graph is in scope, in neither+ // `excluded` nor `retracted`, as a graph closed by an explicit+ // recordedUntil is.+ let none = snapshot(&t, None, None);+ assert!(graphs(&none, "in_scope").contains("g1"), "{none}");+ assert!(!graphs(&none, "excluded").contains("g1"), "{none}");+ assert!(none.get("retracted").is_none(), "{none}");+}++/// A graph that names itself on both predicates.+const SELF_LINKS: &str = r#"+@prefix ex: <http://example.org/> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g1 { ex:HEK293 a ex:AdherentCellLine . }++{+ ex:g1 t:validFrom "2024-01-01" ; t:recordedAt "2024-01-05" ;+ t:supersedes ex:g1 ; t:retracts ex:g1 .+}+"#;++#[test]+fn a_link_naming_the_graph_itself_is_reported_and_neither_closes_nor_withdraws_it() {+ let t = temporal(SELF_LINKS);+ for as_of in [Some("2026-01-01"), None] {+ let snap = snapshot(&t, None, as_of);+ assert_eq!(graphs(&snap, "in_scope"), set(&["g1"]), "{snap}");+ assert!(snap.get("retracted").is_none(), "{snap}");+ let rows = lineage_about(&snap, "g1");+ assert_eq!(rows.len(), 2, "one row per predicate: {snap}");+ for row in &rows {+ assert!(+ row["reason"]+ .as_str()+ .unwrap()+ .contains("names the graph itself"),+ "{snap}"+ );+ assert!(row["target"].as_str().unwrap().ends_with("g1"), "{snap}");+ }+ }+}++/// A predecessor whose valid period holds at no instant, superseded like any+/// other.+const DEGENERATE_PREDECESSOR: &str = r#"+@prefix ex: <http://example.org/> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g1 { ex:HEK293 a ex:AdherentCellLine . }+ex:g2 { ex:HEK293 a ex:SuspensionCellLine . }++{+ ex:g1 t:validFrom "2024-01-01" ; t:validTo "2024-01-01" ; t:recordedAt "2024-01-05" .+ ex:g2 t:validFrom "2024-01-01" ; t:recordedAt "2025-01-01" ; t:supersedes ex:g1 .+}+"#;++#[test]+fn a_predecessor_that_holds_at_no_instant_is_still_closed_by_its_successor() {+ let t = temporal(DEGENERATE_PREDECESSOR);+ // With no valid_at the empty period is not asked about, and before the+ // successor the graph is in scope like any other.+ let before = snapshot(&t, None, Some("2024-06-01"));+ assert!(graphs(&before, "in_scope").contains("g1"), "{before}");+ // After it, the derived bound closes the graph and the row names the+ // successor, exactly as for a sound predecessor.+ let after = snapshot(&t, None, Some("2026-01-01"));+ assert_eq!(reason(&after, "g1"), "no longer recorded then", "{after}");+ assert!(+ bucket_row(&after, "excluded", "g1")["superseded_by"]+ .as_str()+ .is_some_and(|g| g.ends_with("g2")),+ "{after}"+ );+}++/// A described graph asserts that it supersedes an undescribed one, and the+/// two disagree on a disjoint pair. The undescribed graph carries no temporal+/// description, so the link has no effect and the lineage pass says so; the+/// undescribed graph is timeless, and a timeless period overlaps everything.+const LINK_TO_AN_UNDESCRIBED_PARTNER: &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_b { ex:HEK293 a ex:SuspensionCellLine . }+ex:g_nowhere { ex:HEK293 a ex:AdherentCellLine . }++{+ ex:AdherentCellLine owl:disjointWith ex:SuspensionCellLine .+ ex:g_b t:validFrom "2024-01-01" ; t:recordedAt "2026-06-01" ; t:supersedes ex:g_nowhere .+}+"#;++#[test]+fn a_link_the_lineage_pass_rejected_puts_no_pair_in_corrections() {+ let t = temporal(LINK_TO_AN_UNDESCRIBED_PARTNER);+ // The snapshot reports the link as having no effect, and the undescribed+ // graph stays in scope as timeless beside its would-be successor.+ let snap = snapshot(&t, None, Some("2027-01-01"));+ let rows = lineage_about(&snap, "g_b");+ assert_eq!(rows.len(), 1, "{snap}");+ assert!(+ rows[0]["reason"]+ .as_str()+ .unwrap()+ .contains("no temporal description"),+ "{snap}"+ );+ assert!(+ rows[0]["target"].as_str().unwrap().ends_with("g_nowhere"),+ "{snap}"+ );+ assert_eq!(+ graphs(&snap, "in_scope"),+ set(&["g_b", "g_nowhere"]),+ "{snap}"+ );+ // So the conflict check may not walk that link: the pair overlaps on its+ // periods and is a contradiction, not a correction. A walk over the raw+ // assertions would file it as a correction on a link the same answer+ // says closed nothing, and a genuine contradiction would be suppressed.+ let out = conflicts(&t);+ assert_eq!(out["contradiction_count"], 1, "{out}");+ assert_eq!(+ partners(&out, "contradictions"),+ set(&["g_b", "g_nowhere"]),+ "{out}"+ );+ assert!(out.get("corrections").is_none(), "{out}");+ assert!(out.get("corrections_count").is_none(), "{out}");+ assert_eq!(out["complete"], true, "{out}");+}