Skip to content

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

feat(temporal): read bounds as instants on the UTC timeline (#117)

Nicolasf28c446564a4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 33347229..bb3fbe67 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -93,10 +93,13 @@ All notable changes to Open Ontologies are documented here.
history. The results now come back under `non_overlapping` /
`non_overlapping_count`, and the `note` says what was checked instead of
claiming adjacency the code never tested -- including the comparison that
- backs it. Bounds are compared as text, so two periods written with different
- timezone offsets can share an hour and still land in `non_overlapping`; the
- note says so, and a conformance test pins it so the parsed-time work turns it
- into a contradiction as a diff rather than a new assertion.
+ backs it. When this landed, bounds were still compared as text, so two
+ periods written with different timezone offsets could share an hour and
+ still land in `non_overlapping`; a conformance test pinned that so the
+ parsed-time work would turn it into a contradiction as a diff rather than a
+ new assertion. Bounds are now read as instants (see Changed below), offsets
+ are honoured, that test has flipped on the lines that held the old answer,
+ and the note says the comparison is on instants.
`superseded` / `superseded_count` are still emitted, unconditionally and
behind no flag, carrying exactly the same rows until 2.0. Deprecated, not
@@ -214,6 +217,99 @@ All notable changes to Open Ontologies are documented here.
truncated and one showing a correction turn into a false contradiction when
the validity scan is cut.
+### Changed
+- **Temporal bounds are read as instants on the UTC timeline, not compared as
+ text** (issue #95). `onto_temporal_snapshot`,
+ `onto_temporal_query` and `onto_temporal_conflicts` accept `xsd:date`,
+ `xsd:dateTime`, `xsd:gYearMonth` and `xsd:gYear`; a less precise bound names
+ the FIRST instant of the period it names, so `"2026-05-01"^^xsd:date` as a
+ `validTo` excludes the whole of 1 May and `"2026"^^xsd:gYear` as a
+ `validFrom` starts at midnight on 1 January. A value with no timezone offset
+ is UTC: XSD leaves such a value only partially ordered against one that
+ carries an offset, and "indeterminate" is not an answer a register query can
+ return. All four axes are read this way, `recordedUntil` included: a closing
+ bound written with an offset or at month precision closes the recorded
+ interval where its instant falls, not where its text sorts, and one that
+ matches no grammar makes the graph invalid by the same rule as the other
+ three. Every response now carries `semantics_version` (`temporal/2`), since
+ the same store answers differently under the two readings and an answer that
+ does not say which produced it cannot be replayed or hashed.
+
+ A fractional second is refused only when a digit past the ninth is NONZERO.
+ A zero tail is not extra precision: `.1234567890` is 123,456,789 nanoseconds
+ exactly and names the instant `.123456789` names, so refusing it made two
+ spellings of one instant answer differently, the thing this change resolves
+ everywhere else. Fixed-width formatters pad to a fixed digit count, so the
+ tail arrives from machines rather than from typos, and it reaches both the
+ store bounds and the `valid_at` / `as_of` arguments. Bounds typed
+ `^^xsd:dateTime` were shielded by the store's own canonicalisation; bare and
+ `xsd:string` bounds (the form this module documents as supported, and the
+ form the conformance corpus is written in) were not.
+
+ **Same-precision data with four-digit years, no offsets and no sub-nanosecond
+ fractions answers exactly as it did.** That is the constraint this was built
+ against, and the divergence is narrower than it sounds: for a coarse value
+ and a fine one where the coarse is a lexical prefix of the fine, text said
+ "earlier" and instants say "equal", so mixed precision moves ONLY at the
+ boundary instant. The inputs whose answers move:
+
+ - **Mixed precision at a boundary.** A date-typed `validTo` against a
+ `dateTime` instant at midnight now excludes its own day instead of
+ admitting it. Same on the recorded axis: an `as_of` at date precision
+ against a `recordedAt` of `T00:00:00Z` on the same day now sees the record,
+ which is the inclusive cutoff the tool documents and text comparison
+ quietly did not deliver.
+ - **Bounds carrying an offset.** `"2026-05-01T00:00:00+02:00"` is
+ `2026-04-30T22:00:00Z` and is now compared there, rather than sorting after
+ every `2026-04-…` string.
+ - **Years that are not four digits.** `"20241-01-01"` and `"-0044-03-15"` now
+ order by year rather than by first character, so a graph bounded by one is
+ in scope inside its own interval instead of nowhere.
+ - **Bounds that match none of the four grammars** (a foreign datatype, a
+ language tag, `"01/05/2026"`, `"2024-1-1"`, a calendar-impossible
+ `"2024-02-30"`, a fraction finer than a nanosecond) make the graph
+ INVALID. It is reported in a new `invalid` array with a per-graph reason,
+ excluded from `in_scope`, and above all NOT timeless: "we hold no
+ valid-time claim about this" and "the claim is garbage" are different
+ answers. Previously such a bound was compared as raw text, so
+ `"01/05/2026"` sorted before every ISO value in the store and its graph
+ read as valid since the beginning of time.
+ - **Two different instants on one axis.** Previously the last row of the
+ validity query's UNION won and the other value vanished, on an order the
+ query never contracted. The graph is now invalid and both values are
+ named: choosing one, or the min, or the max, would publish an interval
+ nobody asserted. Two SPELLINGS of one instant (a bare `"2024-01-01"` beside
+ `"2024-01-01"^^xsd:date`, which is what a half-finished migration leaves)
+ still resolve to that one instant: they invent nothing. So do a coarse
+ bound and a fine one naming the same instant, `"2024"^^xsd:gYear` beside
+ `"2024-01-01"^^xsd:date`, because agreement is judged on the instants and
+ not on the strings; the row shows the lexically first form.
+ - **`valid_at` / `as_of` that cannot be read** are now refused rather than
+ ignored. Silently dropping one answered a question nobody asked, with the
+ whole store in scope and nothing saying why.
+ - **`onto_temporal_conflicts`** gains `undecided` and `undecided_count` for
+ pairs where a graph's temporal metadata could not be read on at least one
+ axis, so the graph is invalid and the pair is classified neither way. An
+ unreadable period is not an open one; treating it as timeless would make it
+ overlap everything and publish a correction as a live contradiction, which
+ is the failure that tool exists to prevent. `non_overlapping` and the
+ deprecated `superseded` alias are unchanged, and the `note` now says the
+ disjointness check runs on instants, so an offset is honoured.
+
+ A note on `xsd:string`: RDF 1.1 makes a simple literal and an
+ `xsd:string`-typed literal with the same lexical form the SAME term
+ (`datatype()` answers `xsd:string` for both), so a bound cannot be rejected
+ for carrying that datatype: the store holds no such fact to report. Untyped
+ bounds are read by shape against the four grammars, which rejects
+ `"01/05/2026"` either way while leaving every store written with plain
+ literals answering as before. A value wearing one of the four datatypes but
+ matching another of them (the shape this crate's own module doc shipped for
+ `recordedAt`) is read as what it is. 8 grammar tests in `src/temporal.rs`, and
+ the conformance corpus in `tests/temporal_conformance_test.rs` goes from 24
+ tests to 34: the four cases pinned for this change, and the offset pair the
+ `non_overlapping` fix pinned, flip on the lines that held the old answer, and
+ a third section covers what parsing adds.
+
### Added
- **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.
diff --git a/CLAUDE.md b/CLAUDE.md
index 40777999..366ece86 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -95,9 +95,9 @@ Claude dynamically decides the next tool call based on what the previous tool re
| `onto_support_report` | To summarise provenance quality: unsourced-claim rate over the graph, support rate across the claims judged so far |
| `onto_pack` | To write the loaded graph and its verification evidence to a portable versioned artifact: sorted N-Triples, a manifest (name, version, counts, timestamp, tool version, sha256) and the lint/enforce results recorded at pack time. What you promote between environments is then a graph that has already passed its checks, with the evidence attached |
| `onto_unpack` | To load a pack, refusing it if the checksum does not match. `verify_only` inspects the manifest and evidence without loading |
-| `onto_temporal_snapshot` | To see which named graphs are in scope at a point in time. Two independent clocks: `valid_at` asks what was TRUE then, `as_of` asks what was KNOWN then. Both intervals are half-open — `temporal:recordedUntil` closes the recorded one, so `as_of` answers what was believed then rather than everything recorded by then. Graphs without validity metadata are timeless and always in scope, so the vocabulary is additive to an existing store |
+| `onto_temporal_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 under a LEXICAL comparison of their bounds (offsets are not normalised) — not that one replaced the other, and it also holds pairs separated by a gap, which is missing coverage rather than history. `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. 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_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.rs
index 8d426d04..1239faa4 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -1010,31 +1010,47 @@ 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. 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. The scans are capped: `complete` says whether they finished, and a run that was cut short also carries `truncated` and a `warning`, because a truncated validity scan makes this partition wrong rather than merely short.")]
async fn onto_temporal_snapshot(&self, Parameters(input): Parameters<OntoTemporalSnapshotInput>) -> String {
use crate::temporal::Temporal;
match Temporal::new(self.graph.clone()).snapshot(input.valid_at.as_deref(), input.as_of.as_deref()) {
Ok(json) => json,
+ // Renders the error by quote substitution only, with no JSON
+ // escaping, so a message on this path must never echo caller
+ // text: a backslash or a newline would break the JSON. That is
+ // why `temporal::argument` (the wrapper over `instant::argument`)
+ // does not quote the argument in its message.
Err(e) => format!(r#"{{"error":"{}"}}"#, e.to_string().replace('"', "'")),
}
}
- #[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`. `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`. `complete` is false when the result list was cut at its cap or when the scope it ran over was, and `truncated` says which; only the second case is a wrong answer, and it carries a `warning`.")]
async fn onto_temporal_query(&self, Parameters(input): Parameters<OntoTemporalQueryInput>) -> String {
use crate::temporal::Temporal;
match Temporal::new(self.graph.clone()).query_at(
&input.pattern, input.valid_at.as_deref(), input.as_of.as_deref(),
) {
Ok(json) => json,
+ // Renders the error by quote substitution only, with no JSON
+ // escaping, so a message on this path must never echo caller
+ // text: a backslash or a newline would break the JSON. That is
+ // why `temporal::argument` (the wrapper over `instant::argument`)
+ // does not quote the argument in its message.
Err(e) => format!(r#"{{"error":"{}"}}"#, e.to_string().replace('"', "'")),
}
}
- #[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 under LEXICAL comparison of their bounds. That is all that is checked -- it is not evidence that one assertion replaced another, and the bucket also holds pairs separated by a GAP, which is missing coverage rather than history. The `superseded` key carries the same set under a name that claimed more than was proven; it is deprecated and will be dropped at 2.0. 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. The `superseded` key carries the same set under a name that claimed more than was proven; it is deprecated and will be dropped at 2.0. A pair whose graph has temporal metadata that could not be read is in neither bucket: it goes to `undecided`, because an unreadable period is not an open one and treating it as timeless would make it overlap everything. The scans are capped: `complete` says whether they finished, and if the validity scan was cut a `warning` marks the classification unsound, because a pair compared without its periods can appear here as a contradiction when it is a correction.")]
async fn onto_temporal_conflicts(&self) -> String {
use crate::temporal::Temporal;
match Temporal::new(self.graph.clone()).conflicts() {
Ok(json) => json,
+ // Renders the error by quote substitution only, with no JSON
+ // escaping, so a message on this path must never echo caller
+ // text: a backslash or a newline would break the JSON. This
+ // handler takes no argument, so nothing caller-supplied reaches
+ // it today; the rule is stated so an argument added later
+ // inherits it.
Err(e) => format!(r#"{{"error":"{}"}}"#, e.to_string().replace('"', "'")),
}
}
diff --git a/src/temporal.rs b/src/temporal.rs
index c4f05bf2..5350352a 100644
--- a/src/temporal.rs
+++ b/src/temporal.rs
@@ -25,10 +25,10 @@
//! {
//! :g1 t:validFrom "2024-01-01"^^xsd:date ;
//! t:validTo "2026-05-01"^^xsd:date ;
-//! t:recordedAt "2024-01-05"^^xsd:dateTime ;
-//! t:recordedUntil "2026-05-02"^^xsd:dateTime .
+//! t:recordedAt "2024-01-05T09:00:00Z"^^xsd:dateTime ;
+//! t:recordedUntil "2026-05-02T09:00:00Z"^^xsd:dateTime .
//! :g2 t:validFrom "2026-05-01"^^xsd:date ;
-//! t:recordedAt "2026-05-02"^^xsd:dateTime .
+//! t:recordedAt "2026-05-02T09:00:00Z"^^xsd:dateTime .
//! }
//! ```
//!
@@ -50,6 +50,24 @@
//! that replaced it, and the audit question this module exists to answer stops
//! being answerable after the first correction.
//!
+//! ## Bounds are instants
+//!
+//! Every bound is read as an instant on the UTC timeline, from `xsd:date`,
+//! `xsd:dateTime`, `xsd:gYearMonth` or `xsd:gYear`. A less precise bound names
+//! the FIRST instant of the period it names, so `"2026-05-01"^^xsd:date` as a
+//! `validTo` excludes the whole of 1 May, and `"2026"^^xsd:gYear` as a
+//! `validFrom` starts at midnight on 1 January. A value with no timezone
+//! offset is UTC: XSD leaves such a value only partially ordered against one
+//! carrying an offset, and "indeterminate" is not an answer a register query
+//! can return.
+//!
+//! A bound that matches none of those grammars is not coerced into one, and a
+//! graph asserting two different instants on the same axis is not resolved to
+//! either of them: both make the graph INVALID. An invalid graph is reported
+//! with its reason and is never in scope; above all it is never timeless,
+//! because "we hold no valid-time claim about this" and "the claim is garbage"
+//! are different answers.
+//!
//! ## Bounded scans
//!
//! Every query behind these tools is capped so a pathological store cannot
@@ -64,11 +82,21 @@
//! also carry a `warning`.
use crate::graph::GraphStore;
+use chrono::{DateTime, Utc};
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
pub const NS: &str = "https://open-ontologies.org/temporal#";
+/// Which comparison semantics produced an answer.
+///
+/// `temporal/1` was lexical string comparison of the bounds as written.
+/// `temporal/2` reads every bound as an instant on the UTC timeline. The same
+/// 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.
+pub const SEMANTICS_VERSION: &str = "temporal/2";
+
pub struct Temporal {
graph: Arc<GraphStore>,
limits: Limits,
@@ -143,6 +171,9 @@ struct Scan {
struct Scope {
in_scope: Vec<serde_json::Value>,
excluded: Vec<serde_json::Value>,
+ /// 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>,
/// The in-scope graph IRIs, in the same order as `in_scope`.
graphs: Vec<String>,
validity_scan: Capped,
@@ -162,11 +193,12 @@ impl Scope {
"validities",
"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",
+ period excludes them, and one whose metadata is unreadable is published as \
+ timeless instead of invalid",
),
self.graph_scan.report(
"all_graphs",
- "graphs past the limit are missing from both in_scope and excluded",
+ "graphs past the limit are missing from in_scope, excluded and invalid alike",
),
]
.into_iter()
@@ -182,7 +214,8 @@ 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",
+ opposite of the truth for any graph whose period had ended, and unreadable \
+ ones were published as timeless rather than invalid",
);
}
if self.graph_scan.hit {
@@ -199,7 +232,7 @@ impl Scope {
}
}
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, Default)]
pub struct Validity {
pub graph: String,
pub valid_from: Option<String>,
@@ -209,25 +242,51 @@ pub struct Validity {
}
impl Validity {
+ /// The ASSERTED lexical forms, not the instants they parse to: an answer
+ /// shows what the store says. What `"2024"` means as a bound is a rule,
+ /// and a rule belongs in the tool description, not on every row.
+ fn describe(&self) -> String {
+ let from = self.valid_from.as_deref().unwrap_or("always");
+ let to = self.valid_to.as_deref().unwrap_or("still true");
+ format!("{from} to {to}")
+ }
+}
+
+/// One graph's validity, read as instants on the UTC timeline.
+///
+/// The asserted lexical forms travel alongside so an answer keeps showing
+/// what the store says, while every comparison runs on the parsed instant.
+#[derive(Clone, Debug, Default)]
+struct Period {
+ shown: Validity,
+ from: Option<DateTime<Utc>>,
+ to: Option<DateTime<Utc>>,
+ recorded: Option<DateTime<Utc>>,
+ until: Option<DateTime<Utc>>,
+}
+
+impl Period {
/// Was this true at `instant`, on the half-open interval.
- fn valid_at(&self, instant: &str) -> bool {
- self.valid_from.as_deref().is_none_or(|f| f <= instant)
- && self.valid_to.as_deref().is_none_or(|t| instant < t)
+ fn valid_at(&self, instant: DateTime<Utc>) -> bool {
+ self.from.is_none_or(|f| f <= instant) && self.to.is_none_or(|t| instant < t)
}
/// Was this believed at `instant`, on the half-open recorded interval
- /// `[recordedAt, recordedUntil)` — and if not, on which side it fell.
+ /// `[recordedAt, recordedUntil)`, and if not, on which side it fell.
///
/// This is the two-sided form of what used to be `recorded_by`. Adding the
/// closing bound gives the predicate a second way to fail, and the two are
/// opposite facts about the assertion: one has not been recorded yet, the
/// other is no longer believed. A bool would flatten them back together at
/// the only place that has to tell them apart, so it returns the reason.
- fn not_recorded_at(&self, instant: &str) -> Option<&'static str> {
- if self.recorded_at.as_deref().is_some_and(|r| instant < r) {
+ /// 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> {
+ if self.recorded.is_some_and(|r| instant < r) {
return Some("not yet recorded then");
}
- if self.recorded_until.as_deref().is_some_and(|u| u <= instant) {
+ if self.until.is_some_and(|u| u <= instant) {
return Some("no longer recorded then");
}
None
@@ -235,19 +294,569 @@ impl Validity {
/// Do two validity periods share any instant. Half-open, so touching
/// intervals do not overlap.
- fn overlaps(&self, other: &Validity) -> bool {
- let start_before_end = |a: &Option<String>, b: &Option<String>| match (a, b) {
- (Some(start), Some(end)) => start.as_str() < end.as_str(),
+ fn overlaps(&self, other: &Period) -> bool {
+ let start_before_end = |a: Option<DateTime<Utc>>, b: Option<DateTime<Utc>>| match (a, b) {
+ (Some(start), Some(end)) => start < end,
_ => true, // an open end never closes the interval
};
- start_before_end(&self.valid_from, &other.valid_to)
- && start_before_end(&other.valid_from, &self.valid_to)
+ start_before_end(self.from, other.to) && start_before_end(other.from, self.to)
}
+}
- fn describe(&self) -> String {
- let from = self.valid_from.as_deref().unwrap_or("always");
- let to = self.valid_to.as_deref().unwrap_or("still true");
- format!("{from} to {to}")
+/// A graph's validity metadata as the tools read it.
+///
+/// An enum rather than a struct with a flag, because every consumer has to
+/// answer the question: a graph whose metadata cannot be read must never be
+/// treated as timeless, and a `None` that silently means "open period" is
+/// exactly how that happens.
+#[derive(Clone, Debug)]
+enum GraphValidity {
+ /// Every bound the graph asserts was readable.
+ Sound(Period),
+ /// 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>),
+}
+
+/// Why one bound could not be read.
+#[derive(Clone, Debug)]
+struct Fault {
+ field: &'static str,
+ reason: String,
+}
+
+impl GraphValidity {
+ /// One sentence naming every bound that could not be read.
+ fn fault_reason(faults: &[Fault]) -> String {
+ faults
+ .iter()
+ .map(|f| format!("{}: {}", f.field, f.reason))
+ .collect::<Vec<_>>()
+ .join("; ")
+ }
+}
+
+/// One readable bound: the instant every comparison uses, and the lexical
+/// form the answer shows.
+struct Bound {
+ lexical: String,
+ instant: DateTime<Utc>,
+}
+
+/// The raw terms one graph asserts on each axis, before they are read.
+#[derive(Default)]
+struct Bounds {
+ from: Vec<String>,
+ to: Vec<String>,
+ recorded: Vec<String>,
+ until: Vec<String>,
+}
+
+impl Bounds {
+ /// Read all four axes, and refuse the graph if any one of them cannot be
+ /// read. `recordedUntil` is settled by the same rule as the other three:
+ /// it is a bound, and a bound that stayed a string beside three parsed
+ /// ones would close the interval where its text sorts rather than where
+ /// its instant falls.
+ 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);
+ if !faults.is_empty() {
+ return GraphValidity::Unreadable(faults);
+ }
+ GraphValidity::Sound(Period {
+ shown: Validity {
+ graph,
+ valid_from: from.as_ref().map(|b| b.lexical.clone()),
+ valid_to: to.as_ref().map(|b| b.lexical.clone()),
+ recorded_at: recorded.as_ref().map(|b| b.lexical.clone()),
+ recorded_until: until.as_ref().map(|b| b.lexical.clone()),
+ },
+ from: from.map(|b| b.instant),
+ to: to.map(|b| b.instant),
+ recorded: recorded.map(|b| b.instant),
+ until: until.map(|b| b.instant),
+ })
+ }
+}
+
+/// Read every term asserted on one axis, and insist they agree.
+///
+/// Agreement is judged on the INSTANTS the terms name, not on their lexical
+/// forms. Two terms denoting the SAME instant are two spellings of one
+/// assertion (a bare `"2024-01-01"` beside `"2024-01-01"^^xsd:date` is what a
+/// half-finished migration leaves behind) and they invent no interval, so they
+/// resolve. So do a coarse bound and a fine one naming the same instant:
+/// `"2024"^^xsd:gYear` beside `"2024-01-01"^^xsd:date` is one assertion,
+/// because both name midnight on 1 January. Two terms denoting DIFFERENT
+/// instants resolve to nothing: picking one, or the min, or the max, would
+/// invent an interval nobody asserted. The form shown is the lexically first
+/// term after the sort; a row shows one form per bound.
+fn settle(field: &'static str, mut terms: Vec<String>, faults: &mut Vec<Fault>) -> Option<Bound> {
+ terms.sort(); // the query contracts no row order, so neither does the answer
+ let mut read: Vec<(String, DateTime<Utc>)> = Vec::new();
+ for term in &terms {
+ match instant::bound(term) {
+ Ok(instant) => read.push((plain(term), instant)),
+ Err(reason) => {
+ faults.push(Fault { field, reason });
+ return None;
+ }
+ }
+ }
+ let (lexical, instant) = read.first()?.clone();
+ let mut distinct: Vec<DateTime<Utc>> = read.iter().map(|(_, i)| *i).collect();
+ distinct.sort_unstable();
+ distinct.dedup();
+ if distinct.len() > 1 {
+ faults.push(Fault {
+ field,
+ reason: format!(
+ "{} distinct instants asserted ({}); which interval was meant is not \
+ recoverable, and choosing one would invent an interval nobody asserted",
+ distinct.len(),
+ terms.join(", ")
+ ),
+ });
+ return None;
+ }
+ Some(Bound { lexical, instant })
+}
+
+/// Reading a temporal bound as an instant on the UTC timeline.
+///
+/// XSD leaves a timezone-less value only partially ordered against one that
+/// carries an offset. "Indeterminate" is not an answer a register query can
+/// return, so an absent offset is read as UTC and the order is total; the
+/// tool descriptions say so. A less precise bound names the FIRST instant of
+/// the period it names, which is what lexical comparison already gave for
+/// same-precision data, so a well-formed 1.2.0 dataset answers as it did.
+mod instant {
+ use chrono::{DateTime, NaiveDate, TimeDelta, Utc};
+
+ const XSD: &str = "http://www.w3.org/2001/XMLSchema#";
+
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ enum Form {
+ DateTime,
+ Date,
+ GYearMonth,
+ GYear,
+ }
+
+ /// The four grammars are pairwise disjoint, so at most one can match and
+ /// the order here is only a short-circuit.
+ const FORMS: [Form; 4] = [Form::DateTime, Form::Date, Form::GYearMonth, Form::GYear];
+
+ fn name(form: Form) -> &'static str {
+ match form {
+ Form::DateTime => "xsd:dateTime",
+ Form::Date => "xsd:date",
+ Form::GYearMonth => "xsd:gYearMonth",
+ Form::GYear => "xsd:gYear",
+ }
+ }
+
+ fn form_of(datatype: &str) -> Option<Form> {
+ match datatype.strip_prefix(XSD)? {
+ "date" => Some(Form::Date),
+ "dateTime" => Some(Form::DateTime),
+ "gYearMonth" => Some(Form::GYearMonth),
+ "gYear" => Some(Form::GYear),
+ _ => None,
+ }
+ }
+
+ /// A term as `sparql_select` renders it, split into lexical form and
+ /// datatype IRI. Nothing in the four grammars contains a character
+ /// N-Triples escapes, so an escaped lexical form fails the grammar rather
+ /// than needing to be unescaped.
+ fn split(term: &str) -> Result<(&str, Option<&str>), String> {
+ let trimmed = term.trim();
+ let Some(body) = trimmed.strip_prefix('"') else {
+ return Err(format!("{trimmed} is not a literal"));
+ };
+ if let Some(rest) = body.strip_suffix('>') {
+ let Some((lex, datatype)) = rest.rsplit_once("\"^^<") else {
+ return Err(format!("{trimmed} is not a literal"));
+ };
+ return Ok((lex, Some(datatype)));
+ }
+ if let Some((_, tag)) = body.rsplit_once("\"@") {
+ return Err(format!(
+ "a language-tagged literal (@{tag}) is not a temporal bound"
+ ));
+ }
+ let Some(lex) = body.strip_suffix('"') else {
+ return Err(format!("{trimmed} is not a literal"));
+ };
+ Ok((lex, None))
+ }
+
+ /// A bound as the store holds it.
+ ///
+ /// RDF 1.1 makes a simple literal and an `xsd:string`-typed literal with
+ /// the same lexical form THE SAME TERM (`datatype()` answers `xsd:string`
+ /// for both), so a bound cannot be rejected for "carrying" `xsd:string`:
+ /// the store holds no such fact to report. An untyped bound is therefore
+ /// read by SHAPE against all four grammars. `"01/05/2026"` matches none
+ /// and is rejected, by shape rather than by datatype, but rejected.
+ pub(super) fn bound(term: &str) -> Result<DateTime<Utc>, String> {
+ let (lex, datatype) = split(term)?;
+ let lex = lex.trim(); // XSD whiteSpace on these types is `collapse`
+ match datatype {
+ Some(iri) => match form_of(iri) {
+ // A declared temporal datatype whose value does not match it
+ // is mislabelled rather than unreadable: the crate's own
+ // module doc shipped `"2024-01-05"^^xsd:dateTime`, and reading
+ // it as the date it plainly is keeps every answer such a store
+ // already gave. The re-read stays inside the four grammars, so
+ // `"01/05/2026"` is still rejected whatever it claims to be.
+ Some(form) => at(lex, form).map(Ok).unwrap_or_else(|| {
+ shape(lex).map_err(|_| {
+ format!(
+ "\"{lex}\" is not a valid {} and matches no other temporal type",
+ name(form)
+ )
+ })
+ }),
+ None => Err(format!(
+ "datatype <{iri}> is outside xsd:date, xsd:dateTime, xsd:gYearMonth and xsd:gYear"
+ )),
+ },
+ None => shape(lex),
+ }
+ }
+
+ /// A tool argument. It arrives as text rather than as an RDF term, so
+ /// there is no datatype to consult, and it goes through the same
+ /// grammars a bound does, so an argument and a bound can never disagree
+ /// about what an instant is.
+ pub(super) fn argument(text: &str) -> Result<DateTime<Utc>, String> {
+ shape(text.trim())
+ }
+
+ fn shape(lex: &str) -> Result<DateTime<Utc>, String> {
+ FORMS.iter().find_map(|&form| at(lex, form)).ok_or_else(|| {
+ format!(
+ "\"{lex}\" is not an xsd:date, xsd:dateTime, xsd:gYearMonth or xsd:gYear instant"
+ )
+ })
+ }
+
+ /// The first instant of the period `lex` names, on the UTC timeline.
+ /// `None` when the lexical form does not match the grammar, when the
+ /// fields are not a real date, or when the year is not representable.
+ fn at(lex: &str, form: Form) -> Option<DateTime<Utc>> {
+ let b = lex.as_bytes();
+ let (year, mut i) = year_frag(b)?;
+ let (mut month, mut day) = (1u32, 1u32);
+ let (mut hour, mut minute, mut second, mut nano) = (0u32, 0u32, 0u32, 0u32);
+ let mut next_day = false;
+
+ if !matches!(form, Form::GYear) {
+ i = byte(b, i, b'-')?;
+ let (m, j) = two(b, i, 1, 12)?;
+ month = m;
+ i = j;
+ }
+ if matches!(form, Form::Date | Form::DateTime) {
+ i = byte(b, i, b'-')?;
+ let (d, j) = two(b, i, 1, 31)?; // from_ymd_opt rejects 30 February
+ day = d;
+ i = j;
+ }
+ if matches!(form, Form::DateTime) {
+ i = byte(b, i, b'T')?;
+ // XSD's end-of-day form: 24:00:00 is the first instant of the next
+ // day. The store canonicalises it away, but an argument can carry
+ // it, and an argument must not be refused where a bound would not.
+ if b.get(i..).is_some_and(|rest| rest.starts_with(b"24:00:00")) {
+ next_day = true;
+ i = zero_fraction(b, i + 8)?;
+ } else {
+ let (h, j) = two(b, i, 0, 23)?;
+ hour = h;
+ i = byte(b, j, b':')?;
+ let (m, j) = two(b, i, 0, 59)?;
+ minute = m;
+ i = byte(b, j, b':')?;
+ let (s, j) = two(b, i, 0, 59)?; // :60 is not in the XSD lexical space
+ second = s;
+ let (n, j) = fraction(b, j)?;
+ nano = n;
+ i = j;
+ }
+ }
+ let offset = tz(b, i)?; // 0 when absent: no offset means UTC
+ let date = NaiveDate::from_ymd_opt(year, month, day)?;
+ let date = if next_day { date.succ_opt()? } else { date };
+ date.and_hms_nano_opt(hour, minute, second, nano)?
+ .and_utc()
+ .checked_sub_signed(TimeDelta::try_seconds(i64::from(offset))?)
+ }
+
+ /// XSD yearFrag: `'-'? ( [1-9][0-9]{3,} | '0'[0-9]{3} )`. No leading `+`,
+ /// which is why `"+2024"` is not a gYear, and is not one to the store
+ /// either, which passes it through unchanged.
+ fn year_frag(b: &[u8]) -> Option<(i32, usize)> {
+ let negative = b.first() == Some(&b'-');
+ let start = usize::from(negative);
+ let mut i = start;
+ while b.get(i).is_some_and(u8::is_ascii_digit) {
+ i += 1;
+ }
+ let digits = i - start;
+ if !(4..=9).contains(&digits) {
+ return None; // 9 keeps the parse inside i32 before from_ymd_opt sees it
+ }
+ if b[start] == b'0' && digits != 4 {
+ return None;
+ }
+ let magnitude: i64 = std::str::from_utf8(b.get(start..i)?).ok()?.parse().ok()?;
+ if negative && magnitude == 0 {
+ return None; // XSD 1.1 forbids -0000
+ }
+ let year = if negative { -magnitude } else { magnitude };
+ Some((i32::try_from(year).ok()?, i)) // from_ymd_opt caps the range
+ }
+
+ /// XSD allows unbounded fractional digits; chrono holds nanoseconds. A
+ /// value carrying more PRECISION than that is REFUSED rather than
+ /// truncated. Truncating would silently merge two instants a well-formed
+ /// store distinguishes, and these intervals are half-open, so the instants
+ /// that merge are exactly the ones a boundary test is asking about.
+ ///
+ /// Digits past the ninth are only extra precision when one of them is
+ /// NONZERO. A zero tail adds nothing: `.1234567890` is 123,456,789
+ /// nanoseconds exactly, the same instant `.123456789` names, and refusing
+ /// it would contradict `settle`, which resolves two spellings of one
+ /// instant precisely because they invent no interval. Fixed-width
+ /// formatters pad to a fixed digit count, so the tail is common in stores
+ /// nobody wrote by hand.
+ fn fraction(b: &[u8], i: usize) -> Option<(u32, usize)> {
+ if b.get(i) != Some(&b'.') {
+ return Some((0, i));
+ }
+ let (mut j, mut nano, mut scale) = (i + 1, 0u32, 100_000_000u32);
+ while let Some(d) = b.get(j).and_then(|&c| char::from(c).to_digit(10)) {
+ if scale == 0 {
+ if d != 0 {
+ return None; // more precision asserted than can be compared
+ }
+ } else {
+ nano += d * scale;
+ scale /= 10;
+ }
+ j += 1;
+ }
+ if j == i + 1 {
+ return None; // a lone '.'
+ }
+ Some((nano, j))
+ }
+
+ /// The `('.' '0'+)?` XSD allows after `24:00:00`.
+ fn zero_fraction(b: &[u8], i: usize) -> Option<usize> {
+ let (nano, j) = fraction(b, i)?;
+ (nano == 0).then_some(j)
+ }
+
+ /// A trailing `Z` or `±hh:mm`, in seconds east of UTC. Absent means 0.
+ fn tz(b: &[u8], i: usize) -> Option<i32> {
+ let rest = b.get(i..)?;
+ if rest.is_empty() || rest == b"Z" {
+ return Some(0);
+ }
+ if rest.len() != 6 || rest[3] != b':' {
+ return None;
+ }
+ let sign = match rest[0] {
+ b'+' => 1,
+ b'-' => -1,
+ _ => return None,
+ };
+ let hours = two_digits(&rest[1..3])?;
+ let minutes = two_digits(&rest[4..6])?;
+ if minutes > 59 {
+ return None;
+ }
+ let total = i32::try_from(hours * 60 + minutes).ok()?;
+ if total > 14 * 60 {
+ return None; // XSD caps the offset at ±14:00
+ }
+ Some(sign * total * 60)
+ }
+
+ fn byte(b: &[u8], i: usize, want: u8) -> Option<usize> {
+ (b.get(i) == Some(&want)).then_some(i + 1)
+ }
+
+ fn two(b: &[u8], i: usize, lo: u32, hi: u32) -> Option<(u32, usize)> {
+ let value = two_digits(b.get(i..i + 2)?)?;
+ (lo..=hi).contains(&value).then_some((value, i + 2))
+ }
+
+ fn two_digits(pair: &[u8]) -> Option<u32> {
+ let tens = char::from(*pair.first()?).to_digit(10)?;
+ let units = char::from(*pair.get(1)?).to_digit(10)?;
+ Some(tens * 10 + units)
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ /// The instant a lexical form names, as `YYYY-MM-DDTHH:MM:SSZ`, or the
+ /// word "invalid". One row per rule, so a rule that changes moves one
+ /// line rather than a paragraph of prose.
+ fn read(text: &str) -> String {
+ match argument(text) {
+ Ok(i) => i.format("%Y-%m-%dT%H:%M:%S%.fZ").to_string(),
+ Err(_) => "invalid".to_string(),
+ }
+ }
+
+ #[test]
+ fn a_less_precise_form_names_the_first_instant_of_its_period() {
+ for (lexical, instant) in [
+ ("2024", "2024-01-01T00:00:00Z"),
+ ("2024-03", "2024-03-01T00:00:00Z"),
+ ("2024-03-05", "2024-03-05T00:00:00Z"),
+ ("2024-03-05T06:07:08", "2024-03-05T06:07:08Z"),
+ ("2024-03-05T06:07:08.25", "2024-03-05T06:07:08.250Z"),
+ ] {
+ assert_eq!(read(lexical), instant, "{lexical}");
+ }
+ }
+
+ #[test]
+ fn an_absent_offset_is_utc_and_a_present_one_is_applied() {
+ for (lexical, instant) in [
+ ("2024-03-05T06:00:00", "2024-03-05T06:00:00Z"),
+ ("2024-03-05T06:00:00Z", "2024-03-05T06:00:00Z"),
+ ("2024-03-05T06:00:00+02:00", "2024-03-05T04:00:00Z"),
+ ("2024-03-05T06:00:00-05:00", "2024-03-05T11:00:00Z"),
+ // The offset applies to the coarser forms too, and can move
+ // the instant into the previous day, month or year.
+ ("2024-03-05+02:00", "2024-03-04T22:00:00Z"),
+ ("2024-01+02:00", "2023-12-31T22:00:00Z"),
+ ("2024+02:00", "2023-12-31T22:00:00Z"),
+ // XSD's end-of-day form: the first instant of the next day.
+ ("2024-03-05T24:00:00Z", "2024-03-06T00:00:00Z"),
+ ] {
+ assert_eq!(read(lexical), instant, "{lexical}");
+ }
+ }
+
+ #[test]
+ fn everything_outside_the_four_grammars_is_refused() {
+ for lexical in [
+ "01/05/2026", // the shape a spreadsheet exports
+ "2024-1-1", // XSD requires two digits
+ "20240101", // and the separators
+ "2024-13-01", // month out of range
+ "2024-02-30", // parses field by field, never happened
+ "2024-03-05T25:00:00Z", // hour out of range
+ "2024-03-05T06:07", // xsd:dateTime requires seconds
+ "2024-03-05T06:07:60Z", // leap seconds are not in the lexical space
+ "2024-03-05T06:00:00+00:99", // minutes out of range
+ "2024-03-05T06:00:00+15:00", // XSD caps the offset at 14:00
+ "+2024", // yearFrag has no leading plus
+ "-0000", // XSD 1.1 forbids negative zero
+ "024", // fewer than four digits
+ "02024", // a leading zero is only for four
+ "",
+ " ",
+ "tomorrow",
+ // Finer than a nanosecond: refused rather than truncated, so
+ // two instants a store distinguishes never silently merge.
+ "2024-03-05T06:00:00.0000000001Z",
+ ] {
+ assert_eq!(read(lexical), "invalid", "{lexical}");
+ }
+ }
+
+ #[test]
+ fn a_datatype_outside_the_four_is_refused_whatever_its_value_looks_like() {
+ let date = "\"2024-03-05\"^^<http://www.w3.org/2001/XMLSchema#date>";
+ assert!(bound(date).is_ok());
+ for term in [
+ "\"2024-03-05\"^^<http://www.w3.org/2001/XMLSchema#token>",
+ "\"2024-03-05\"^^<http://example.org/JulianDay>",
+ "\"2024-03-05\"@en",
+ "<http://example.org/not-a-literal>",
+ ] {
+ assert!(bound(term).is_err(), "{term}");
+ }
+ }
+
+ /// The crate's own module doc shipped `"2024-01-05"^^xsd:dateTime`,
+ /// which is a date wearing a dateTime datatype. Reading it as the date
+ /// it plainly is keeps every answer such a store already gave; the
+ /// re-read stays inside the four temporal grammars, so a value fitting
+ /// none of them is still refused whatever it claims to be.
+ #[test]
+ fn a_value_mislabelled_as_another_temporal_type_is_re_read_by_shape() {
+ let mislabelled = "\"2024-01-05\"^^<http://www.w3.org/2001/XMLSchema#dateTime>";
+ assert_eq!(
+ bound(mislabelled)
+ .unwrap()
+ .format("%Y-%m-%dT%H:%M:%SZ")
+ .to_string(),
+ "2024-01-05T00:00:00Z"
+ );
+ let garbage = "\"01/05/2026\"^^<http://www.w3.org/2001/XMLSchema#dateTime>";
+ assert!(bound(garbage).is_err());
+ }
+
+ /// XSD's whiteSpace facet on these types is `collapse`, and a store
+ /// that keeps the padding must not answer differently from one that
+ /// does not, on either path.
+ #[test]
+ fn padding_is_collapsed_on_both_the_typed_and_the_bare_path() {
+ assert_eq!(read(" 2024-03-05 "), "2024-03-05T00:00:00Z");
+ let padded = "\" 2024-03-05 \"^^<http://www.w3.org/2001/XMLSchema#date>";
+ assert!(bound(padded).is_ok());
+ }
+
+ /// A tenth fractional digit is only unrepresentable when it carries a
+ /// value. `.1234567890` is 123,456,789 nanoseconds exactly, the same
+ /// instant `.123456789` names, so refusing it made two spellings of
+ /// one instant answer differently, which is the thing `settle` exists
+ /// to prevent. Fixed-width formatters pad to a fixed digit count, so
+ /// the zero tail arrives from machines, not from typos.
+ #[test]
+ fn a_zero_tail_past_nanoseconds_is_the_same_instant_not_more_precision() {
+ let nine = read("2024-03-05T06:07:08.123456789Z");
+ assert_eq!(read("2024-03-05T06:07:08.1234567890Z"), nine);
+ assert_eq!(read("2024-03-05T06:07:08.12345678900000Z"), nine);
+ // The zero tail must not disturb a value that is entirely zeroes,
+ // nor the `('.' '0'+)?` XSD allows after 24:00:00.
+ assert_eq!(
+ read("2024-03-05T06:07:08.0000000000Z"),
+ read("2024-03-05T06:07:08Z")
+ );
+ assert!(bound("\"2024-03-05T24:00:00.0000000000Z\"").is_ok());
+ }
+
+ /// The negative control for the test above: a NONZERO digit past the
+ /// ninth is real precision this crate cannot compare, and truncating
+ /// it would merge two instants a well-formed store distinguishes.
+ /// Without this case the fix above would read as "accept any tail".
+ #[test]
+ fn a_nonzero_digit_past_nanoseconds_is_still_refused() {
+ assert!(bound("\"2024-03-05T06:07:08.1234567891Z\"").is_err());
+ assert!(bound("\"2024-03-05T06:00:00.0000000001Z\"").is_err());
+ // A nonzero digit further out still counts, however long the tail.
+ assert!(bound("\"2024-03-05T06:07:08.12345678900001Z\"").is_err());
+ // And 24:00:00 still admits only zeroes.
+ assert!(bound("\"2024-03-05T24:00:00.0000000001Z\"").is_err());
+ }
}
}
@@ -271,6 +880,31 @@ fn local(iri: &str) -> &str {
iri.rsplit(['#', '/']).next().unwrap_or(iri)
}
+/// Read a tool argument as an instant.
+///
+/// An argument that cannot be read is refused rather than dropped: treating it
+/// as "no bound" would answer a question nobody asked, with the whole store in
+/// scope and nothing saying why.
+///
+/// The message deliberately does not quote the argument back. The tool
+/// handlers render an `Err` into JSON by hand (`src/server.rs`, quote
+/// substitution only), so caller text reaching that path could emit a
+/// malformed response, and the caller has the value already. Store-side
+/// reasons do quote the offending bound, because those travel in the `invalid`
+/// array, which is built by serde_json and escaped properly.
+fn argument(name: &str, text: Option<&str>) -> anyhow::Result<Option<DateTime<Utc>>> {
+ text.map(|t| {
+ instant::argument(t).map_err(|_| {
+ anyhow::anyhow!(
+ "{name} is not readable as an instant: it must be an xsd:date, xsd:dateTime, \
+ xsd:gYearMonth or xsd:gYear value, and a value carrying no timezone offset \
+ is read as UTC"
+ )
+ })
+ })
+ .transpose()
+}
+
impl Temporal {
pub fn new(graph: Arc<GraphStore>) -> Self {
Self::with_limits(graph, Limits::default())
@@ -314,7 +948,7 @@ impl Temporal {
/// Every graph that carries validity metadata, and whether the scan that
/// found them was complete.
- fn validities(&self) -> anyhow::Result<(BTreeMap<String, Validity>, Capped)> {
+ fn validities(&self) -> anyhow::Result<(BTreeMap<String, GraphValidity>, Capped)> {
let query = format!(
"SELECT ?g ?from ?to ?rec ?until WHERE {{ \
{{ ?g <{NS}validFrom> ?from }} UNION {{ ?g <{NS}validTo> ?to }} \
@@ -322,31 +956,35 @@ impl Temporal {
UNION {{ ?g <{NS}recordedUntil> ?until }} }}"
);
let scan = self.rows(&query, self.limits.validity_scan)?;
- let mut out: BTreeMap<String, Validity> = BTreeMap::new();
+ // 1.2.0 ASSIGNED each field here, so the last row of the UNION won
+ // and any other value vanished. Collect instead: a graph asserting
+ // two different instants on one axis is a data error, and resolving
+ // it by min, max or row order would invent an interval nobody
+ // asserted.
+ let mut terms: BTreeMap<String, Bounds> = BTreeMap::new();
for row in &scan.rows {
let Some(g) = row.get("g").and_then(|v| v.as_str()).map(plain) else {
continue;
};
- let entry = out.entry(g.clone()).or_insert(Validity {
- graph: g,
- valid_from: None,
- valid_to: None,
- recorded_at: None,
- recorded_until: None,
- });
- if let Some(v) = row.get("from").and_then(|v| v.as_str()) {
- entry.valid_from = Some(plain(v));
- }
- if let Some(v) = row.get("to").and_then(|v| v.as_str()) {
- entry.valid_to = Some(plain(v));
- }
- if let Some(v) = row.get("rec").and_then(|v| v.as_str()) {
- entry.recorded_at = Some(plain(v));
- }
- if let Some(v) = row.get("until").and_then(|v| v.as_str()) {
- entry.recorded_until = Some(plain(v));
+ let entry = terms.entry(g).or_default();
+ for (key, slot) in [
+ ("from", &mut entry.from),
+ ("to", &mut entry.to),
+ ("rec", &mut entry.recorded),
+ ("until", &mut entry.until),
+ ] {
+ if let Some(v) = row.get(key).and_then(|v| v.as_str()) {
+ let term = v.trim().to_string();
+ if !slot.contains(&term) {
+ slot.push(term);
+ }
+ }
}
}
+ let out = terms
+ .into_iter()
+ .map(|(graph, bounds)| (graph.clone(), bounds.resolve(graph)))
+ .collect();
Ok((out, scan.capped))
}
@@ -369,12 +1007,17 @@ impl Temporal {
/// `snapshot` renders this and `query_at` runs against it, so the two
/// tools agree by construction and the truncation verdict reaches
/// `query_at` as a value rather than through its own JSON output.
- fn scope(&self, valid_at: Option<&str>, as_of: Option<&str>) -> anyhow::Result<Scope> {
+ fn scope(
+ &self,
+ valid_at: Option<DateTime<Utc>>,
+ as_of: Option<DateTime<Utc>>,
+ ) -> anyhow::Result<Scope> {
let (validities, validity_scan) = 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 names = Vec::new();
for g in &graphs {
match validities.get(g) {
@@ -386,19 +1029,26 @@ impl Temporal {
);
names.push(g.clone());
}
- Some(v) => {
- let valid_ok = valid_at.is_none_or(|t| v.valid_at(t));
+ // Described, but the description could not be read. Never in
+ // scope and never timeless: "we hold no valid-time claim about
+ // this" and "the claim is garbage" are different answers.
+ Some(GraphValidity::Unreadable(faults)) => invalid.push(serde_json::json!({
+ "graph": g,
+ "reason": GraphValidity::fault_reason(faults),
+ })),
+ Some(GraphValidity::Sound(p)) => {
+ let valid_ok = valid_at.is_none_or(|t| p.valid_at(t));
// Which side of the recorded interval `as_of` fell on, not
// merely that it fell outside: "recorded later" and "no
// longer believed" are opposite facts about the assertion.
- let recorded_miss = as_of.and_then(|t| v.not_recorded_at(t));
+ let recorded_miss = as_of.and_then(|t| p.not_recorded_at(t));
if valid_ok && recorded_miss.is_none() {
- in_scope.push(serde_json::json!({"graph": g, "valid": v.describe()}));
+ in_scope.push(serde_json::json!({"graph": g, "valid": p.shown.describe()}));
names.push(g.clone());
} else {
excluded.push(serde_json::json!({
"graph": g,
- "valid": v.describe(),
+ "valid": p.shown.describe(),
"reason": if !valid_ok {
"not true at that instant"
} else {
@@ -413,6 +1063,7 @@ impl Temporal {
Ok(Scope {
in_scope,
excluded,
+ invalid,
graphs: names,
validity_scan,
graph_scan,
@@ -421,7 +1072,9 @@ impl Temporal {
/// Which graphs are in scope for a snapshot, and why.
pub fn snapshot(&self, valid_at: Option<&str>, as_of: Option<&str>) -> anyhow::Result<String> {
- let scope = self.scope(valid_at, as_of)?;
+ let at = argument("valid_at", valid_at)?;
+ let of = argument("as_of", as_of)?;
+ let scope = self.scope(at, of)?;
let mut out = serde_json::json!({
"ok": true,
@@ -430,8 +1083,12 @@ impl Temporal {
"in_scope": scope.in_scope,
"excluded": scope.excluded,
"complete": scope.complete(),
+ "semantics_version": SEMANTICS_VERSION,
"note": "Graphs without validity metadata are timeless and always in scope.",
});
+ if !scope.invalid.is_empty() {
+ out["invalid"] = serde_json::Value::Array(scope.invalid.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());
@@ -450,14 +1107,19 @@ impl Temporal {
valid_at: Option<&str>,
as_of: Option<&str>,
) -> anyhow::Result<String> {
- let scope = self.scope(valid_at, as_of)?;
+ let at = argument("valid_at", valid_at)?;
+ let of = argument("as_of", as_of)?;
+ let scope = self.scope(at, of)?;
// The scope this query runs over is the snapshot's scope, so the
// snapshot's truncation is this query's truncation. Saying nothing
// here would hide a wrong scope behind a tool that never mentions
- // scans at all.
+ // scans at all. Same for the graphs left out as unreadable: a query
+ // that silently narrows what it read is the failure this reporting
+ // exists to remove.
let mut cuts = scope.cuts();
let scope_warning = scope.warning();
let scope_complete = scope.complete();
+ let invalid = scope.invalid;
let graphs = scope.graphs;
if graphs.is_empty() {
@@ -465,8 +1127,12 @@ impl Temporal {
"ok": true,
"results": [],
"complete": scope_complete,
+ "semantics_version": SEMANTICS_VERSION,
"note": "no graphs in scope at that instant",
});
+ if !invalid.is_empty() {
+ out["invalid"] = serde_json::Value::Array(invalid);
+ }
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 \
@@ -502,7 +1168,11 @@ impl Temporal {
"graphs_in_scope": graphs.len(),
"results": scan.rows,
"complete": scope_complete && !scan.capped.hit,
+ "semantics_version": SEMANTICS_VERSION,
});
+ if !invalid.is_empty() {
+ out["invalid"] = serde_json::Value::Array(invalid);
+ }
if !cuts.is_empty() {
out["truncated"] = serde_json::Value::Array(cuts);
}
@@ -549,33 +1219,48 @@ impl Temporal {
self.limits.conflict_pairs,
)?;
+ // An undescribed graph is timeless, which is a real period with two
+ // open ends. An UNREADABLE one is not a period at all, and handing it
+ // this value would make it overlap everything: the false
+ // contradiction the truncation warning below is about, arriving
+ // through the data instead of through a cap.
+ let timeless = Period::default();
+ let period = |graph: &str| match validities.get(graph) {
+ None => Some(&timeless),
+ Some(GraphValidity::Sound(p)) => Some(p),
+ Some(GraphValidity::Unreadable(_)) => None,
+ };
+
let mut conflicts = Vec::new();
let mut non_overlapping = Vec::new();
+ let mut undecided = Vec::new();
for row in &scan.rows {
let get = |k: &str| row.get(k).and_then(|v| v.as_str()).map(plain);
- let (Some(s), Some(a), Some(b), Some(ga), Some(gb)) = (
- get("s"), get("a"), get("b"), get("ga"), get("gb"),
- ) else {
+ let (Some(s), Some(a), Some(b), Some(ga), Some(gb)) =
+ (get("s"), get("a"), get("b"), get("ga"), get("gb"))
+ else {
continue;
};
if ga == gb {
continue;
}
- let timeless = Validity {
- graph: String::new(),
- valid_from: None,
- valid_to: None,
- recorded_at: None,
- recorded_until: None,
+ let (Some(va), Some(vb)) = (period(&ga), period(&gb)) else {
+ undecided.push(serde_json::json!({
+ "subject": local(&s),
+ "types": [local(&a), local(&b)],
+ "graphs": [ga, gb],
+ "reason": "one of these graphs has temporal metadata that could not be read \
+ on at least one axis, so it is invalid and the pair was not \
+ classified; see invalid in onto_temporal_snapshot",
+ }));
+ continue;
};
- let va = validities.get(&ga).unwrap_or(&timeless);
- let vb = validities.get(&gb).unwrap_or(&timeless);
let entry = serde_json::json!({
"subject": local(&s),
"types": [local(&a), local(&b)],
- "periods": [va.describe(), vb.describe()],
+ "periods": [va.shown.describe(), vb.shown.describe()],
"graphs": [ga, gb],
});
if va.overlaps(vb) {
@@ -601,15 +1286,17 @@ impl Temporal {
"superseded": non_overlapping,
"superseded_count": non_overlapping.len(),
"complete": !validity_scan.hit && !scan.capped.hit,
+ "semantics_version": SEMANTICS_VERSION,
"note": "contradictions claim overlapping validity and genuinely disagree. \
- non_overlapping pairs have no instant in common UNDER LEXICAL \
- COMPARISON of their bounds, which is all that has been checked: it is \
- not evidence that one replaced the other, the bucket also holds pairs \
- separated by a GAP (missing coverage rather than history), and bounds \
- written with different timezone offsets are compared as text, so a \
- genuinely overlapping pair can land here until bounds are parsed as \
- instants. superseded is the same set under a name that claimed more \
- than was proven; it is deprecated and will be dropped at 2.0.",
+ non_overlapping pairs have 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 has been checked: it is not evidence that one replaced \
+ the other, and the bucket also holds pairs separated by a GAP (missing \
+ coverage rather than history). undecided holds pairs where a graph's \
+ temporal metadata could not be read: an unreadable period is never \
+ treated as an open one, so such a pair is classified neither way. \
+ superseded is the same set as non_overlapping under a name that claimed \
+ more than was proven; it is deprecated and will be dropped at 2.0.",
});
// A cut validity scan is not a smaller answer here, it is a wrong one:
@@ -634,6 +1321,10 @@ impl Temporal {
.flatten()
.collect();
+ if !undecided.is_empty() {
+ out["undecided"] = serde_json::Value::Array(undecided.clone());
+ out["undecided_count"] = serde_json::Value::from(undecided.len());
+ }
if !cuts.is_empty() {
out["truncated"] = serde_json::Value::Array(cuts);
}
@@ -738,7 +1429,10 @@ ex:g_after { ex:X a ex:Suspension . }
}
/// The contract for every store that never reaches a cap: one honest
- /// `complete`, and not a key more than 1.2.0 emitted.
+ /// `complete`, and no report of a cut that did not happen. "Nothing else"
+ /// is about the cut. `semantics_version` is always present, and `invalid`
+ /// and `undecided` appear whenever they are non-empty; those keys say
+ /// nothing about caps and the conformance corpus pins them separately.
#[test]
fn a_run_that_was_never_cut_says_so_and_adds_nothing_else() {
let t = Temporal::new(store(THREE));
diff --git a/tests/temporal_conformance_test.rs b/tests/temporal_conformance_test.rs
index 8869b7f9..ef3313d0 100644
--- a/tests/temporal_conformance_test.rs
+++ b/tests/temporal_conformance_test.rs
@@ -5,18 +5,21 @@
//! validity with an exclusive upper bound, open bounds, recorded-time
//! visibility, timeless (undescribed) graphs, snapshot-scoped querying, and
//! the overlap-versus-superseded split that is the whole point of carrying
-//! valid time. Every assertion holds on the code as shipped in 1.2.0, so these
-//! are behavioural anchors, not aspirations: a later change to the temporal
-//! semantics has to move a line here on purpose rather than drift silently.
+//! valid time. Every assertion holds on the code as it stands, `temporal/2`,
+//! the parsed-time semantics that #95 asked for, so these are behavioural
+//! 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 two sections. The first pins semantics that are **intended**;
+//! The file has three 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. The second pins what the code does **today** for
-//! mixed-precision and malformed bounds — behaviour that falls out of comparing
-//! datatype-stripped literals lexically rather than being chosen. Each test
-//! there names what the planned parsed-time work (#95, item 4) turns it into,
-//! so that change lands as a diff on assertions that already exist instead of
-//! arriving as new ones the corpus could never have failed on.
+//! 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
+//! when they were compared as datatype-stripped text, behaviour that fell out
+//! of the implementation rather than being chosen, with each test naming what
+//! the parsed-time work (#95, item 4) would turn it into; that work has landed,
+//! so those tests now hold the new answer on the same lines, which is what the
+//! section was for. The third covers what parsing adds and could not be
+//! expressed before: coarse bounds, offsets, and bounds that must be refused.
//!
//! Deliberately not feature-gated: a `#![cfg(feature = ...)]` on a test file
//! that CI runs without that feature prints `running 0 tests` and reads as
@@ -75,6 +78,20 @@ fn set(items: &[&str]) -> BTreeSet<String> {
items.iter().map(|s| s.to_string()).collect()
}
+/// The reason one graph was reported unreadable, or `None` if it was not.
+///
+/// Separate from `graphs()` on purpose: a clean answer carries no `invalid`
+/// key at all, and `graphs()` panics on a bucket that is not there.
+fn invalid_reason(snapshot: &serde_json::Value, graph: &str) -> Option<String> {
+ snapshot
+ .get("invalid")?
+ .as_array()?
+ .iter()
+ .find(|row| row["graph"].as_str().is_some_and(|g| g.ends_with(graph)))
+ .and_then(|row| row["reason"].as_str())
+ .map(str::to_string)
+}
+
/// A correction over time plus one timeless fact. `g_adherent` held for a
/// closed period, `g_suspension` from the boundary onward, and `g_species` has
/// no validity metadata at all.
@@ -314,10 +331,11 @@ fn open_end_still_holds_in_the_far_future() {
}
/// The same shape as `CELL_LINE`, but written with the `xsd:date` and
-/// `xsd:dateTime` typed literals the tool documents on disk. `Temporal::plain`
-/// strips the datatype, so these must behave exactly like their lexical forms;
-/// this is the representation a regression in that stripping would break while
-/// the untyped fixtures stayed green.
+/// `xsd:dateTime` typed literals the tool documents on disk. A typed bound is
+/// read against the grammar its datatype names, an untyped one by shape alone,
+/// and both must land on the same instants; this is the representation a
+/// regression in the typed path would break while the untyped fixtures stayed
+/// green.
const TYPED_LITERALS: &str = r#"
@prefix ex: <http://example.org/> .
@prefix t: <https://open-ontologies.org/temporal#> .
@@ -337,19 +355,23 @@ fn typed_literals_behave_like_their_lexical_form() {
let t = temporal(TYPED_LITERALS);
// Inside the valid interval and after the (dateTime) record: in scope.
assert!(
- graphs(&snapshot(&t, Some("2024-06-01"), Some("2024-01-06")), "in_scope")
- .contains("g_typed"),
+ graphs(
+ &snapshot(&t, Some("2024-06-01"), Some("2024-01-06")),
+ "in_scope"
+ )
+ .contains("g_typed"),
"typed date/dateTime literals compare like their lexical form"
);
// The dateTime record is not yet visible one day before it was entered.
assert!(
- graphs(&snapshot(&t, Some("2024-06-01"), Some("2024-01-04")), "excluded")
- .contains("g_typed")
+ graphs(
+ &snapshot(&t, Some("2024-06-01"), Some("2024-01-04")),
+ "excluded"
+ )
+ .contains("g_typed")
);
// Before the typed validFrom: excluded, exactly as an untyped fixture is.
- assert!(
- graphs(&snapshot(&t, Some("2023-01-01"), None), "excluded").contains("g_typed")
- );
+ assert!(graphs(&snapshot(&t, Some("2023-01-01"), None), "excluded").contains("g_typed"));
}
#[test]
@@ -379,7 +401,9 @@ fn query_at_reports_an_empty_scope_rather_than_the_whole_store() {
// No timeless graph here, and both described graphs begin in 2024, so an
// instant in 2000 leaves nothing in scope.
let t = temporal(CONFLICT_OVERLAP);
- let raw = t.query_at("{ ?s a ?type }", Some("2000-01-01"), None).unwrap();
+ let raw = t
+ .query_at("{ ?s a ?type }", Some("2000-01-01"), None)
+ .unwrap();
let out: serde_json::Value = serde_json::from_str(&raw).unwrap();
assert_eq!(out["results"].as_array().unwrap().len(), 0);
assert_eq!(out["note"], "no graphs in scope at that instant");
@@ -500,10 +524,12 @@ fn the_deprecated_key_carries_the_same_set_until_2_0() {
}
}
-/// The `note` is output, and output can be wrong. It claimed "one period ends
-/// where the other begins" — adjacency — when the only test performed is
+/// The `note` is output, and output can be wrong. It once claimed "one period
+/// ends where the other begins", adjacency, when the only test performed is
/// `!overlaps`, which is disjointness. A gap satisfies it too. Nothing pinned
-/// that sentence, which is how it survived; this pins what the code proves.
+/// that sentence, which is how it survived; this pins what the code proves:
+/// disjointness judged on bounds read as instants, and a third outcome for a
+/// pair whose graph could not be read at all.
#[test]
fn the_note_claims_only_what_the_code_checks() {
let t = temporal(CONFLICT_GAP);
@@ -518,8 +544,16 @@ fn the_note_claims_only_what_the_code_checks() {
"and must name the case that is missing coverage rather than history: {note}"
);
assert!(
- note.contains("LEXICAL COMPARISON") || note.contains("lexical"),
- "and must qualify the guarantee by the comparison that backs it: {note}"
+ note.contains("read as instants"),
+ "and must name the comparison that backs the guarantee, which is on instants: {note}"
+ );
+ assert!(
+ !note.contains("lexical") && !note.contains("LEXICAL"),
+ "bounds are no longer compared as text, so the note may not say they are: {note}"
+ );
+ assert!(
+ note.contains("undecided") && note.contains("could not be read"),
+ "and must say why a pair can be in neither bucket: {note}"
);
assert!(
!note.contains("one period ends where the other begins"),
@@ -547,47 +581,45 @@ ex:g_b { ex:X a ex:Suspension . }
}
"#;
-/// ACCIDENTAL, pinned on purpose so the parsed-time work (#95, item 4) lands as
-/// a diff on an assertion that already exists rather than as a new one.
-///
-/// `overlaps()` compares datatype-stripped literals as TEXT. `"…T01:00:00Z"`
-/// sorts after `"…T00:00:00-02:00"`, so the two periods read as disjoint and
-/// the pair is classified `non_overlapping` — while on the real timeline they
-/// share an hour and are a genuine contradiction.
-///
-/// This is why the `note` qualifies its guarantee with the comparison that
-/// backs it: the key must not promise more than `overlaps()` can establish.
-///
-/// AFTER item 4: `contradiction_count` is 1 and `non_overlapping_count` is 0.
+/// Pinned before the parsed-time work (#95, item 4) as an ACCIDENT of comparing
+/// datatype-stripped literals as text: `"...T01:00:00Z"` sorted after
+/// `"...T00:00:00-02:00"`, so the two periods read as disjoint and a pair that
+/// shares an hour on the real timeline was classified `non_overlapping`. That
+/// pin was written so this change would land as a diff on an assertion that
+/// already existed rather than as a new one, and this is that diff: bounds
+/// are instants, the offset is honoured, and the same fixture is the genuine
+/// contradiction it always was.
#[test]
-fn accidental_offset_bounds_can_hide_a_real_overlap_from_the_disjointness_check() {
+fn offset_bounds_are_compared_as_instants_so_a_real_overlap_is_a_contradiction() {
let t = temporal(CONFLICT_OFFSET_OVERLAP);
let out: serde_json::Value = serde_json::from_str(&t.conflicts().unwrap()).unwrap();
assert_eq!(
- out["contradiction_count"], 0,
- "today the offsets are compared as text, so the real overlap is invisible: {out}"
+ out["contradiction_count"], 1,
+ "2026-05-01T00:00:00-02:00 is 02:00Z, an hour past the 01:00Z start of the other \
+ period, so the two share an instant: {out}"
);
assert_eq!(
- out["non_overlapping_count"], 1,
- "and the pair lands in the bucket whose guarantee it violates: {out}"
+ out["non_overlapping_count"], 0,
+ "and a pair that shares an instant is not in the bucket that promises none: {out}"
);
}
// ---------------------------------------------------------------------------
-// Section 2 — accidental behaviour, pinned so it can be flipped on purpose
+// Section 2: the inputs parsed-time reading changes
//
-// Everything above pins semantics that are intended. What follows pins what the
-// code does TODAY for mixed-precision and malformed bounds, which is a side
-// effect of comparing datatype-stripped literals lexically (`plain()` at
-// temporal.rs:229-242, `validities()` at :309-317) rather than a decision.
+// Everything above pins semantics that are intended, and none of it moved.
+// What follows was pinned in 1.2.0 as ACCIDENTS of comparing datatype-stripped
+// literals lexically rather than as decisions, each test naming what issue #95
+// item 4 would turn it into. Item 4 has landed: same fixtures, same inputs, and
+// the answer each one gives now, a diff on the lines that held the old answer,
+// which is what this section was written for.
//
-// These are the exact inputs the planned parsed-time work (issue #95, item 4)
-// changes: bounds parsed as instants on the UTC timeline accepting xsd:date,
-// xsd:dateTime, xsd:gYearMonth and xsd:gYear; a less precise bound mapping to
-// the first instant of the period it names; timezone-less values read as UTC;
-// any other datatype rejected rather than coerced; and multi-valued bounds
-// marked invalid instead of resolved. Each test below says what it will become,
-// so that work lands as a diff on existing assertions rather than as new ones.
+// Bounds are read as instants on the UTC timeline, accepting xsd:date,
+// xsd:dateTime, xsd:gYearMonth and xsd:gYear. A less precise bound names the
+// FIRST instant of the period it names. A value with no offset is UTC. A bound
+// matching none of the four grammars is invalid, and so is a graph asserting
+// two different instants on one axis; invalid graphs are reported in their own
+// bucket and never fall into the timeless one.
// ---------------------------------------------------------------------------
/// `xsd:date` lower bound, `xsd:dateTime` upper bound, same axis.
@@ -605,21 +637,19 @@ ex:g_mixed { ex:X a ex:A . }
"#;
#[test]
-fn accidental_mixed_precision_upper_bound_admits_its_own_day() {
+fn a_less_precise_instant_names_the_first_moment_of_its_period() {
let t = temporal(MIXED_PRECISION);
- // ACCIDENTAL: "2026-05-01" is a lexical prefix of "2026-05-01T00:00:00Z",
- // so the half-open `instant < to` test passes and the day is in scope.
- // Parsed, the date maps to 2026-05-01T00:00:00Z, which is exactly `to`,
- // so the same instant is excluded.
- // AFTER item 4: this graph is EXCLUDED at 2026-05-01.
- assert!(
- graphs(&snapshot(&t, Some("2026-05-01"), None), "in_scope").contains("g_mixed"),
- "today the dateTime upper bound does not exclude its own date-typed instant"
- );
- // Unchanged by item 4: a day inside the interval stays in scope.
+ // WAS ACCIDENTAL: "2026-05-01" is a lexical prefix of
+ // "2026-05-01T00:00:00Z", so the half-open `instant < to` test passed on
+ // text and the whole day read as in scope.
+ // NOW: the date names the first instant of 1 May, which is exactly `to`,
+ // and a half-open interval excludes its upper bound.
assert!(
- graphs(&snapshot(&t, Some("2026-04-30"), None), "in_scope").contains("g_mixed")
+ graphs(&snapshot(&t, Some("2026-05-01"), None), "excluded").contains("g_mixed"),
+ "the date-typed instant is the upper bound itself, so it is excluded"
);
+ // Unchanged: a day inside the interval stays in scope.
+ assert!(graphs(&snapshot(&t, Some("2026-04-30"), None), "in_scope").contains("g_mixed"));
}
/// A lower bound carrying a `+02:00` offset against an instant expressed in Z.
@@ -637,24 +667,37 @@ ex:g_off { ex:X a ex:A . }
"#;
#[test]
-fn accidental_offset_bound_compares_as_text_not_as_an_instant() {
+fn an_offset_bound_is_read_as_the_instant_it_denotes() {
let t = temporal(OFFSET_BOUND);
// 2026-05-01T00:00:00+02:00 is 2026-04-30T22:00:00Z, so 23:00Z that day is
// one hour INSIDE the interval.
- // ACCIDENTAL: compared as text, "2026-05-…" sorts after "2026-04-…", so the
- // bound reads as later than it is and the instant falls outside.
- // AFTER item 4: this graph is IN SCOPE at 2026-04-30T23:00:00Z.
+ // WAS ACCIDENTAL: compared as text, "2026-05-…" sorts after "2026-04-…",
+ // so the bound read as later than it is and the instant fell outside.
+ // NOW: the offset is applied and the instant is where it always was.
assert!(
- graphs(&snapshot(&t, Some("2026-04-30T23:00:00Z"), None), "excluded").contains("g_off"),
- "today an offset bound is compared lexically, not as an instant"
+ graphs(
+ &snapshot(&t, Some("2026-04-30T23:00:00Z"), None),
+ "in_scope"
+ )
+ .contains("g_off"),
+ "an hour past a +02:00 bound is inside the interval, whatever the text sorts like"
);
- // Unchanged by item 4: an instant past both readings stays in scope.
+ // Unchanged: an instant past both readings stays in scope.
assert!(
- graphs(&snapshot(&t, Some("2026-05-01T00:00:00Z"), None), "in_scope").contains("g_off")
+ graphs(
+ &snapshot(&t, Some("2026-05-01T00:00:00Z"), None),
+ "in_scope"
+ )
+ .contains("g_off")
);
}
-/// A bound whose datatype is `xsd:string`, carrying a non-ISO lexical form.
+/// A bound carrying a non-ISO lexical form.
+///
+/// It is written `^^xsd:string`, but RDF 1.1 makes that the SAME term as the
+/// bare literal `"01/05/2026"` (`datatype()` answers `xsd:string` for both),
+/// so nothing downstream can reject it for its datatype. It is rejected for
+/// its shape, which is what makes the rule implementable at all.
const STRING_TYPED_BOUND: &str = r#"
@prefix ex: <http://example.org/> .
@prefix t: <https://open-ontologies.org/temporal#> .
@@ -668,18 +711,30 @@ ex:g_str { ex:X a ex:A . }
"#;
#[test]
-fn accidental_string_typed_bound_is_coerced_instead_of_rejected() {
+fn a_bound_matching_no_temporal_grammar_is_invalid_rather_than_coerced() {
let t = temporal(STRING_TYPED_BOUND);
- // ACCIDENTAL: `plain()` throws the datatype away, leaving "01/05/2026",
- // which sorts before every ISO value in the store. The graph therefore
- // reads as valid since the beginning of time — including in 1999.
- // AFTER item 4: the datatype is outside the accepted set, so the graph is
- // INVALID: excluded from in_scope and reported with a reason, never
- // silently in scope and never in the timeless bucket.
+ // WAS ACCIDENTAL: `plain()` threw the datatype away, leaving "01/05/2026",
+ // which sorts before every ISO value in the store, so the graph read as
+ // valid since the beginning of time, including in 1999.
+ // NOW: the value matches none of the four grammars, so the graph is
+ // INVALID: out of in_scope, reported with a reason, and above all NOT
+ // timeless. "We hold no valid-time claim about this" and "the claim is
+ // garbage" are different answers.
for instant in ["2020-01-01", "1999-01-01"] {
+ let snap = snapshot(&t, Some(instant), None);
+ assert!(
+ !graphs(&snap, "in_scope").contains("g_str"),
+ "an unreadable bound must not put its graph in scope (at {instant})"
+ );
+ assert!(
+ !graphs(&snap, "excluded").contains("g_str"),
+ "nor in excluded, which claims we read the period and it did not hold"
+ );
+ let reason = invalid_reason(&snap, "g_str")
+ .unwrap_or_else(|| panic!("g_str is reported unreadable: {snap}"));
assert!(
- graphs(&snapshot(&t, Some(instant), None), "in_scope").contains("g_str"),
- "today an xsd:string bound is coerced and sorts before ISO values (at {instant})"
+ reason.contains("validFrom") && reason.contains("01/05/2026"),
+ "the reason names the field and quotes the value: {reason}"
);
}
}
@@ -698,40 +753,372 @@ ex:g_multi { ex:X a ex:A . }
"#;
#[test]
-fn accidental_multi_valued_bound_resolves_to_one_row_instead_of_failing() {
+fn two_different_instants_on_one_axis_are_a_data_error_not_a_choice() {
let t = temporal(MULTI_VALUED_BOUND);
- // ACCIDENTAL: `validities()` overwrites the field on every row of the
- // 4-way UNION, so one of the two values wins and the other vanishes. Which
- // one is whichever the UNION yields last — today that is 2024-01-01, but
- // nothing in the query contracts that order, which is the defect.
- // AFTER item 4: the graph is INVALID, both values are listed in the reason,
- // and it is neither resolved to one of them nor treated as timeless.
+ // WAS ACCIDENTAL: `validities()` overwrote the field on every row of the
+ // validity UNION, so one value won and the other vanished: whichever the
+ // UNION happened to yield last, an order the query never contracted.
+ // NOW: the graph is INVALID and both values are listed. Resolving to one,
+ // or to the min, or to the max, would publish an interval nobody asserted.
let snap = snapshot(&t, Some("2026-06-01"), None);
- // 2026-06-01 is after BOTH candidate lower bounds, so this assertion holds
- // whichever row wins — it pins "resolved to a single interval and admitted"
- // without depending on the iteration order.
+ // 2026-06-01 is after BOTH candidate lower bounds, so under the old
+ // last-row-wins reading the graph was in scope whichever row survived.
+ assert!(
+ !graphs(&snap, "in_scope").contains("g_multi"),
+ "an interval nobody asserted must not be published: {snap}"
+ );
+ let reason = invalid_reason(&snap, "g_multi")
+ .unwrap_or_else(|| panic!("g_multi is reported unreadable: {snap}"));
+ assert!(
+ reason.contains("2024-01-01") && reason.contains("2026-05-01"),
+ "BOTH asserted values are named, not one of them: {reason}"
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Section 3: what reading bounds as instants adds
+//
+// The cases Section 2 does not reach: values that are readable but were never
+// comparable as text, and values that must be refused. Every fixture here is
+// data a real store produces: a half-finished migration, a coarse register
+// bound, a mislabelled datatype, a typo.
+// ---------------------------------------------------------------------------
+
+/// The same instant asserted twice on one axis, in two spellings. A bare
+/// literal beside its typed twin is what a half-finished migration leaves.
+const TWO_SPELLINGS: &str = r#"
+@prefix ex: <http://example.org/> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+
+ex:g_twin { ex:X a ex:A . }
+
+{
+ ex:g_twin t:validFrom "2024-01-01" , "2024-01-01"^^xsd:date .
+}
+"#;
+
+#[test]
+fn two_spellings_of_one_instant_are_one_assertion() {
+ let t = temporal(TWO_SPELLINGS);
+ let snap = snapshot(&t, Some("2024-06-01"), None);
+ // Two terms, one instant: nothing is ambiguous and no interval has to be
+ // invented, so this is not the multi-valued data error. Reading it as one
+ // is what keeps a store mid-migration answering as it did in 1.2.0, where
+ // both rows collapsed to the same string and last-row-wins was a no-op.
+ assert!(
+ graphs(&snap, "in_scope").contains("g_twin"),
+ "two spellings of one instant assert one interval: {snap}"
+ );
+ assert!(
+ invalid_reason(&snap, "g_twin").is_none(),
+ "and nothing about it is unreadable: {snap}"
+ );
+}
+
+/// The same instant asserted at two precisions on one axis: a year beside
+/// the day that year begins on. A register that recorded "2024" and a later
+/// pass that wrote out the day it stands for is the shape this leaves.
+const TWO_PRECISIONS: &str = r#"
+@prefix ex: <http://example.org/> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+
+ex:g_coarse { ex:X a ex:A . }
+
+{
+ ex:g_coarse t:validFrom "2024"^^xsd:gYear , "2024-01-01"^^xsd:date .
+}
+"#;
+
+/// `settle` compares the INSTANTS the terms name, not their lexical forms:
+/// `"2024"` and `"2024-01-01"` are different strings naming one instant, so
+/// they are one assertion, exactly as two spellings at one precision are.
+///
+/// The displayed form is pinned as well. The row shows `2024`, the lexically
+/// first term after the sort, because a row carries one form per bound and
+/// showing both would need a shape change. This pins the current choice so a
+/// change to it is deliberate, not an endorsement of it.
+#[test]
+fn a_coarse_bound_and_a_fine_one_naming_the_same_instant_are_one_assertion() {
+ let t = temporal(TWO_PRECISIONS);
+ let snap = snapshot(&t, Some("2024-06-01"), None);
+ assert!(
+ graphs(&snap, "in_scope").contains("g_coarse"),
+ "a year and the day it begins on are one instant, so one interval: {snap}"
+ );
assert!(
- graphs(&snap, "in_scope").contains("g_multi"),
- "today a multi-valued bound still yields one usable interval"
+ invalid_reason(&snap, "g_coarse").is_none(),
+ "and nothing about it is a data error: {snap}"
);
- // Exactly one of the two values is reported, never both.
- let described = snap["in_scope"]
+ let row = snap["in_scope"]
.as_array()
.unwrap()
.iter()
- .find(|r| r["graph"].as_str().unwrap().ends_with("g_multi"))
- .and_then(|r| r["valid"].as_str())
- .unwrap_or_default()
- .to_string();
- let mentions_early = described.contains("2024-01-01");
- let mentions_late = described.contains("2026-05-01");
+ .find(|row| {
+ row["graph"]
+ .as_str()
+ .is_some_and(|g| g.ends_with("g_coarse"))
+ })
+ .unwrap_or_else(|| panic!("g_coarse is in scope: {snap}"));
+ assert_eq!(
+ row["valid"], "2024 to still true",
+ "the shown form is the lexically first term, `2024`: {row}"
+ );
+}
+
+/// Register data is often coarser than a day.
+const COARSE_BOUNDS: &str = r#"
+@prefix ex: <http://example.org/> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+
+ex:g_year { ex:X a ex:A . }
+ex:g_month { ex:Y a ex:A . }
+
+{
+ ex:g_year t:validFrom "2024"^^xsd:gYear ;
+ t:validTo "2026"^^xsd:gYear .
+ ex:g_month t:validFrom "2024-03"^^xsd:gYearMonth .
+}
+"#;
+
+#[test]
+fn a_year_or_month_bound_names_the_first_instant_of_its_period() {
+ let t = temporal(COARSE_BOUNDS);
+ // "2024" is 2024-01-01T00:00:00Z, so the first instant of 2024 is in.
+ assert!(graphs(&snapshot(&t, Some("2024-01-01"), None), "in_scope").contains("g_year"));
+ // "2026" as an upper bound is the first instant of 2026, and the interval
+ // is half-open, so 2025 is the last year in scope, not 2026.
+ assert!(graphs(&snapshot(&t, Some("2025-12-31"), None), "in_scope").contains("g_year"));
+ assert!(graphs(&snapshot(&t, Some("2026-01-01"), None), "excluded").contains("g_year"));
+ // Same rule one precision down.
+ assert!(graphs(&snapshot(&t, Some("2024-03-01"), None), "in_scope").contains("g_month"));
+ assert!(graphs(&snapshot(&t, Some("2024-02-29"), None), "excluded").contains("g_month"));
+}
+
+/// A value that is a perfectly good instant wearing the wrong datatype. This
+/// is the shape this crate's own module doc shipped, so a store built by
+/// following the documentation must keep answering.
+const MISLABELLED_DATATYPE: &str = r#"
+@prefix ex: <http://example.org/> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+
+ex:g_doc { ex:X a ex:A . }
+
+{
+ ex:g_doc t:validFrom "2024-01-01"^^xsd:date ;
+ t:recordedAt "2024-01-05"^^xsd:dateTime .
+}
+"#;
+
+#[test]
+fn a_value_wearing_the_wrong_temporal_datatype_is_still_read() {
+ let t = temporal(MISLABELLED_DATATYPE);
+ // "2024-01-05" is not in the lexical space of xsd:dateTime. The re-read
+ // stays inside the four temporal grammars, so this resolves to the date it
+ // plainly is, while a value fitting none of them is still refused, which
+ // is what `a_bound_matching_no_temporal_grammar_is_invalid…` pins.
+ let snap = snapshot(&t, Some("2024-06-01"), Some("2024-01-05"));
+ assert!(
+ invalid_reason(&snap, "g_doc").is_none(),
+ "the documented shape must keep answering: {snap}"
+ );
+ assert!(graphs(&snap, "in_scope").contains("g_doc"));
+ // And the recorded-time cutoff still bites on the other side of it.
+ assert!(
+ graphs(
+ &snapshot(&t, Some("2024-06-01"), Some("2024-01-04")),
+ "excluded"
+ )
+ .contains("g_doc")
+ );
+}
+
+/// Bounds nothing can read: a datatype outside the four, a language tag, and
+/// a date that never happened.
+const UNREADABLE_BOUNDS: &str = r#"
+@prefix ex: <http://example.org/> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+
+ex:g_token { ex:X a ex:A . }
+ex:g_lang { ex:Y a ex:A . }
+ex:g_never { ex:Z a ex:A . }
+
+{
+ ex:g_token t:validFrom "2024-01-01"^^xsd:token .
+ ex:g_lang t:validFrom "2024-01-01"@en .
+ ex:g_never t:validFrom "2024-02-30"^^xsd:date .
+}
+"#;
+
+#[test]
+fn a_foreign_datatype_a_language_tag_and_an_impossible_date_are_all_invalid() {
+ let t = temporal(UNREADABLE_BOUNDS);
+ let snap = snapshot(&t, Some("2024-06-01"), None);
+ for graph in ["g_token", "g_lang", "g_never"] {
+ assert!(
+ invalid_reason(&snap, graph).is_some(),
+ "{graph} carries a bound nothing can read: {snap}"
+ );
+ assert!(
+ !graphs(&snap, "in_scope").contains(graph),
+ "and it must never reach the timeless bucket: {snap}"
+ );
+ }
+ // 30 February parses field by field and is still not a day: the calendar
+ // check is what catches it, not the grammar.
+ assert!(
+ invalid_reason(&snap, "g_never")
+ .unwrap()
+ .contains("2024-02-30")
+ );
+}
+
+#[test]
+fn an_unreadable_argument_is_refused_rather_than_ignored() {
+ let t = temporal(CELL_LINE);
+ // Dropping it would answer a question nobody asked: the whole store in
+ // scope, with nothing saying why.
+ assert!(t.snapshot(Some("01/05/2026"), None).is_err());
+ assert!(t.snapshot(None, Some("last tuesday")).is_err());
+ assert!(t.query_at("{ ?s ?p ?o }", Some(""), None).is_err());
+ // And a readable one still works, at every precision.
+ assert!(t.snapshot(Some("2026"), None).is_ok());
+ assert!(t.snapshot(Some("2026-05-01T12:00:00+02:00"), None).is_ok());
+}
+
+/// The closing bound of the recorded interval, written three ways: one that
+/// nothing can read, one carrying an offset, and one at month precision.
+const RECORDED_UNTIL_FORMS: &str = r#"
+@prefix ex: <http://example.org/> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+
+ex:g_garbage { ex:X a ex:A . }
+ex:g_offset { ex:Y a ex:A . }
+ex:g_month { ex:Z a ex:A . }
+
+{
+ ex:g_garbage t:recordedAt "2024-01-05" ; t:recordedUntil "01/05/2026"^^xsd:string .
+ ex:g_offset t:recordedAt "2024-01-05" ; t:recordedUntil "2026-05-02T00:00:00+02:00"^^xsd:dateTime .
+ ex:g_month t:recordedAt "2024-01-05" ; t:recordedUntil "2026-05"^^xsd:gYearMonth .
+}
+"#;
+
+/// `recordedUntil` is the fourth parsed axis and fails the way the other three
+/// do: a value matching no temporal grammar makes the WHOLE graph invalid,
+/// with the reason naming the axis, rather than leaving the recorded interval
+/// open or the graph timeless. Whole-graph invalidation is the rule for every
+/// axis; there is no per-axis fault.
+#[test]
+fn an_unreadable_recorded_until_makes_the_graph_invalid_like_any_other_axis() {
+ let t = temporal(RECORDED_UNTIL_FORMS);
+ for as_of in [None, Some("2025-01-01")] {
+ let snap = snapshot(&t, None, as_of);
+ assert!(
+ !graphs(&snap, "in_scope").contains("g_garbage"),
+ "an unreadable closing bound must not leave the graph in scope (as_of {as_of:?})"
+ );
+ assert!(
+ !graphs(&snap, "excluded").contains("g_garbage"),
+ "nor in excluded, which claims the interval was read and had closed"
+ );
+ let reason = invalid_reason(&snap, "g_garbage")
+ .unwrap_or_else(|| panic!("g_garbage is reported unreadable: {snap}"));
+ assert!(
+ reason.contains("recordedUntil") && reason.contains("01/05/2026"),
+ "the reason names the axis and quotes the value: {reason}"
+ );
+ }
+}
+
+/// The closing bound is compared as the instant it names, not as text.
+/// `2026-05-02T00:00:00+02:00` is `2026-05-01T22:00:00Z`, so an audit at
+/// `23:00Z` on 1 May is already past it although the text says 2 May; and
+/// `"2026-05"` closes the interval at the first instant of May, not somewhere
+/// inside it.
+#[test]
+fn recorded_until_with_an_offset_or_at_coarse_precision_closes_at_its_instant() {
+ let t = temporal(RECORDED_UNTIL_FORMS);
+ let snap = snapshot(&t, None, Some("2026-05-01T23:00:00Z"));
+ assert_eq!(
+ reason(&snap, "g_offset"),
+ "no longer recorded then",
+ "22:00Z on 1 May has passed by 23:00Z, whatever the text sorts like: {snap}"
+ );
+ assert_eq!(
+ reason(&snap, "g_month"),
+ "no longer recorded then",
+ "May has begun, so a month-precision bound has closed: {snap}"
+ );
+ // Two hours earlier the offset bound has not closed yet.
+ let before = snapshot(&t, None, Some("2026-05-01T21:00:00Z"));
+ assert!(
+ graphs(&before, "in_scope").contains("g_offset"),
+ "21:00Z on 1 May is before 22:00Z: {before}"
+ );
+ // And the last second of April is still inside the month-bounded interval.
+ let april = snapshot(&t, None, Some("2026-04-30T23:59:59Z"));
assert!(
- mentions_early ^ mentions_late,
- "exactly one validFrom survives today (last row of the UNION wins): {described}"
+ graphs(&april, "in_scope").contains("g_month"),
+ "April is before the first instant of May: {april}"
);
- // And nothing anywhere says the graph is malformed.
+}
+
+/// A disjointness pair where one side's period cannot be read.
+const UNREADABLE_IN_A_PAIR: &str = r#"
+@prefix ex: <http://example.org/> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+
+ex:g_a { ex:X a ex:Adherent . }
+ex:g_b { ex:X a ex:Suspension . }
+
+{
+ ex:Adherent owl:disjointWith ex:Suspension .
+ ex:g_a t:validFrom "2024-01-01" ; t:validTo "2026-05-01" .
+ ex:g_b t:validFrom "01/05/2026"^^xsd:string .
+}
+"#;
+
+#[test]
+fn a_pair_whose_period_cannot_be_read_is_undecided_not_a_contradiction() {
+ let t = temporal(UNREADABLE_IN_A_PAIR);
+ let out: serde_json::Value = serde_json::from_str(&t.conflicts().unwrap()).unwrap();
+ // An unreadable period is not an open one. Treating it as timeless would
+ // make it overlap everything and publish this pair as a live contradiction:
+ // the false positive the tool exists to prevent, arriving through the
+ // data instead of through a truncated scan. Nor is it a disjoint one, so
+ // the pair is in neither bucket.
+ assert_eq!(out["contradiction_count"], 0, "{out}");
+ assert_eq!(out["non_overlapping_count"], 0, "{out}");
+ assert_eq!(out["superseded_count"], 0, "{out}");
+ assert_eq!(out["undecided_count"], 1, "{out}");
assert!(
- snap.get("invalid").is_none(),
- "today there is no invalid bucket to report this in: {snap}"
+ out["undecided"][0]["reason"]
+ .as_str()
+ .unwrap()
+ .contains("could not be read"),
+ "{out}"
);
}
+
+#[test]
+fn every_answer_names_the_semantics_that_produced_it() {
+ let t = temporal(CELL_LINE);
+ // Two readings of the same store disagree, so an answer that does not say
+ // which one produced it cannot be replayed or hashed, which is what the
+ // snapshot manifest work needs from this PR.
+ for raw in [
+ t.snapshot(None, None).unwrap(),
+ t.query_at("{ ?s ?p ?o }", None, None).unwrap(),
+ t.conflicts().unwrap(),
+ ] {
+ let out: serde_json::Value = serde_json::from_str(&raw).unwrap();
+ assert_eq!(out["semantics_version"], "temporal/2", "{out}");
+ }
+}