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.

temporal: scope is a value, and a run says which graphs it read (#108) (#157)

Fabio Rovai6c59465f2a3a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1eaa8744..9a161c56 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -45,6 +45,66 @@ All notable changes to Open Ontologies are documented here.
skolemised without `_:b0` on both sides becoming one IRI naming two different existentials.
`skolemise` is unchanged for every existing caller.
### Fixed
+- **Reasoning and SHACL read every graph, so a bi-temporal store was judged over a state that
+ never existed (#108).** `Reasoner::run` read the store through `GraphStore::all_triples`, which
+ iterates every quad and drops the graph name, and `ShaclValidator::validate` read it through
+ `sparql_select_union`, which makes the default graph the union of every graph. Neither had an
+ argument that could change it. On the module's own example — `:HEK293` adherent until
+ 2026-05-01 in `:g1`, suspension from 2026-05-01 in `:g2`, two half-open periods that MEET and
+ share no instant — `onto_temporal_conflicts` filed a correction and reported zero
+ contradictions, while `onto_reason` reported a `cax-dw` disjointness clash and `onto_shacl`
+ reported a `sh:maxCount` violation. Both verdicts were about a moment that never occurred.
+
+ This is the failure mode a certificate cannot catch, and that is why it was worth the size of
+ the change. Run with `certificate_dir`, the clash above wrote a `refutation.tsv` that `oo-refute
+ check` ACCEPTS: a machine-checked `unsatisfiable_under_disjointness` over two versions that
+ never coexisted. The certificate is not wrong. `OOCert.certificate_sound` quantifies over the
+ triples in `asserted.tsv`, they were all in the store, every derivation followed, and the Lean
+ checker is telling the truth. `asserted.tsv` was the wrong graph, and no checker in this
+ project can see that far.
+
+ Three things changed. **The scope is a value.** `crate::graph::ReadScope` says which graphs a
+ run may read; `GraphStore::triples_in_scope` and `sparql_select_scoped` read exactly those and
+ no others, by dataset selection rather than by copying, so cross-graph joins keep working and a
+ scoped run costs no extra memory. The named-graph restriction is applied to a query's available
+ named graphs as well as to its default graph, so a `sh:sparql` constraint cannot name its way
+ back out. **The scope is refused rather than guessed.** `onto_reason` and `onto_shacl` take
+ `valid_at`, `as_of` and `all_versions`; over a store that describes its named graphs with the
+ temporal vocabulary, a run with none of them is refused with a message naming the way out. A
+ store that uses no temporal vocabulary is unaffected under every request and answers exactly as
+ it did at 1.3.0. **This is a behaviour change for a bi-temporal store**: a call that used to
+ return a verdict now returns an error until the caller says which question it is asking.
+ **The scope is evidence.** Every report carries `scope`, and every certificate directory now
+ also gets `scope.tsv` (`oo-scope/1`), one line per graph read and one per graph deliberately
+ not read. No Lean checker reads it; it is a record a person or a script can check against the
+ store, and its value is that the selection is no longer invisible.
+
+ Four decisions the issue asked for, taken and visible in the manifest: membership is exactly the
+ snapshot's `in_scope` set; the default graph is in wholesale, because it holds the schema (and
+ therefore, admitted rather than hidden, the validity metadata lands in the reasoner's closure —
+ `docs/trusted-computing-base.md` item 13); a graph holding this engine's own materialised
+ inferences is dropped and the drop is recorded, which closes the across-run inference leak of
+ TCB item 5 for scoped runs; and NO run over a versioned store MATERIALISES, scoped or
+ `all_versions`, and it says so rather than dropping the flag. There is nowhere in such a store
+ that a conclusion can be written without becoming an axiom of every snapshot: the default graph
+ is in scope at every instant because it is timeless, and so is an inference graph carrying no
+ validity description. A snapshot's conclusions held at one instant and would be read at all of
+ them; an `all_versions` closure was drawn from a state that held at no instant, and writing that
+ in is this same leak arriving through the exit rather than the entrance. The CLI and the batch
+ runner make any invocation carrying a scope argument a dry run; over MCP, pass
+ `materialize: false`. A snapshot
+ that selects no graph returns `conforms: null` with its own reason instead of conforming
+ vacuously. A temporal description written into a named graph, where `Temporal::validities` cannot
+ read it, is refused rather than silently treated as an undescribed and therefore timeless store.
+ Scoped runs are not available for `owl-dl`, whose tableaux path still reads
+ `GraphStore::all_triples`, and asking for one is refused rather than ignored.
+ `onto_extend` chains both tools, takes no scope arguments of its own, and inherits the refusal:
+ over a versioned store it returns the error rather than a pipeline report, and the snapshot has
+ to be run through the two tools directly. `onto_reason_incremental` has no snapshot form either
+ — it reads the union through `sparql_select_union` and materialises into the default graph —
+ and is refused over a versioned store unless `all_versions: true` says the union was meant;
+ leaving it ungated would have made the gate on `onto_reason` a suggestion.
+ `tests/temporal_scope_test.rs` holds the reproduction and every gate.
- **A front-page claim was gated by a test that ran nowhere, and now runs in CI.** `README.md`
reported that the cross-kernel differential "reports zero divergent rows", and
`tests/cross_kernel_differential_test.rs` does require exactly that and fails on any row at
diff --git a/docs/lean-certificates.md b/docs/lean-certificates.md
index 3d40dc7e..3f82bd11 100644
--- a/docs/lean-certificates.md
+++ b/docs/lean-certificates.md
@@ -31,7 +31,9 @@ Over MCP, `onto_reason` takes `certificate_dir`. The response gains a `certifica
"asserted": 1128,
"derivations": 268,
"by_rule": {"rdfs2": 41, "rdfs9": 190, "scm-eqc1": 3, "...": "..."},
- "check_with": "cd lean && lake exe oo-cert <dir>/asserted.tsv <dir>/derivations.tsv"
+ "check_with": "cd lean && lake exe oo-cert <dir>/asserted.tsv <dir>/derivations.tsv",
+ "scope": {"selector": "whole-store", "default_graph": true, "complete": true, "...": "..."},
+ "scope_file": "/tmp/cert/scope.tsv"
}
}
```
@@ -39,6 +41,14 @@ Over MCP, `onto_reason` takes `certificate_dir`. The response gains a `certifica
`derivations` always equals `inferred_count`: one line per inferred triple, recorded the first time
it is derived.
+`scope` says which graphs the run READ, and `scope.tsv` carries the same thing as a file beside
+`asserted.tsv`. It exists because the checker cannot ask: `oo-cert` verifies that the derivations
+follow from the triples in front of it, which stays true whatever selected them, so a certificate
+over one snapshot of a bi-temporal register and a certificate over the union of every version are
+indistinguishable as files and only one is about a state that existed (#108). Over a store that
+uses the temporal vocabulary, `onto_reason` takes `valid_at` / `as_of` / `all_versions` and
+REFUSES a run that names none of them.
+
## Check it
The checker needs a Lean 4 toolchain. [elan](https://github.com/leanprover/elan) installs the
@@ -63,7 +73,14 @@ Tab-separated. Terms are in N-Triples spelling, exactly as the engine's interner
them, so a term is spelled identically wherever it appears and tabs and newlines cannot occur
inside one.
-- `asserted.tsv`: one triple per line, `s TAB p TAB o`. Every triple the run started from.
+- `asserted.tsv`: one triple per line, `s TAB p TAB o`. Every triple the run started from — which
+ means every triple in the graphs the run SELECTED, and `scope.tsv` is where that is written down.
+- `scope.tsv`: `oo-scope/1`, then one `key TAB value` line per fact about the selection, with one
+ `graph` line per named graph read (`graph TAB *` for the whole store) and one
+ `excluded TAB graph TAB reason` line per graph deliberately not read. **No checker reads this
+ file.** It is there because none of them can: a certificate over a snapshot and a certificate
+ over the union of every version are indistinguishable as `asserted.tsv` + `derivations.tsv`, and
+ only one of them is about a state that existed (#108).
- `derivations.tsv`: one step per line, `rule TAB s TAB p TAB o` for the conclusion, then the
premises as further triples, in the order documented per rule in `lean/OOCert/Rules.lean`.
- `refutation.tsv`, only when the run found a contradiction it can certify: the line `oo-refute/1`,
@@ -837,15 +854,24 @@ Stated rather than discovered later.
- **`asserted.tsv` is the store, not your file.** Quads are flattened, so a triple present in two
named graphs appears on two lines. Literals are in the store's post-parse canonical spelling, so
`"01"^^xsd:integer` is written `"1"^^xsd:integer`. The guarantee is relative to that file.
-- **Reasoning twice into one store.** The run reaches a fixpoint, so a second run adds nothing. If
- you materialise into the DEFAULT graph of a store that already held inferences, they appear in
- `asserted.tsv` as assumptions with nothing marking them derived: the merge is what the caller
- asked for and it is lossy. `inference_graph: true` (decision 0001) now fixes it rather than
- mitigating it. The certified paths read `GraphStore::triples_outside(&[INFERRED_GRAPH])`, so a
- later run does not read an earlier run's conclusions back as axioms, and the JSON reports
- `graphs_read` and `graphs_excluded` so the certificate says which graphs it is about. Until 15
- September 2026 `all_triples` read every named graph and the separation protected `save` and not
- the certificate; TCB-8 in `docs/trusted-computing-base.md` has the history.
+- **`asserted.tsv` is the store the run SELECTED, and the checker cannot see the selection.** By
+ default that is every graph. Over a store that keeps several versions of an entity in several
+ named graphs, the union of every version is a state that held at no instant, and a certificate
+ over it is a valid proof about a graph that never existed — `oo-cert` accepts it, correctly, and
+ `oo-refute` will accept a `cax-dw` refutation drawn from two versions that never coexisted. That
+ is issue #108. Two things changed: a run over a store that uses the temporal vocabulary is
+ REFUSED unless the caller names an instant (`valid_at` / `as_of`) or asks for every version by
+ name (`all_versions`), and every certificate directory now gets `scope.tsv`, an `oo-scope/1`
+ record of which graphs the run read. **No Lean checker reads `scope.tsv`.** It is evidence for a
+ person, not a proof; see `docs/trusted-computing-base.md` items 11 to 13 for what it does not
+ cover.
+- **Reasoning twice into one store.** The run now reaches a fixpoint, so a second run adds nothing,
+ but if you materialise into a store that already held inferences they appear in `asserted.tsv` as
+ assumptions with nothing marking them derived. Use `inference_graph: true` (decision 0001) when
+ that distinction matters — and note that this separates the SAVE, not the certificate: an
+ unscoped run reads every named graph, the inference graph included. A SCOPED run does not: it
+ drops the inference graph from what it reads, records the drop in `scope.tsv`, and materialises
+ nothing of its own.
- **No clash found is not consistency.** Seven of the seventeen clash rules are not looked for at
all and eight of the ten that are cannot be certified, so a clean `reason` run means "none of the
ten rules tried fired", never "this ontology is consistent". A rejected refutation means the same:
diff --git a/docs/reasoning.md b/docs/reasoning.md
index caeef967..0d28e362 100644
--- a/docs/reasoning.md
+++ b/docs/reasoning.md
@@ -62,6 +62,28 @@ measurements are in
| `onto_dl_explain` | Explain why a class is unsatisfiable (clash trace) |
| `onto_dl_check` | Check if one class is subsumed by another |
+## Which graphs a run reads
+
+By default, all of them: the default graph and every named graph, flattened.
+That is the right dataset for a store that holds one version of everything,
+and the wrong one for a store that keeps several versions of an entity in
+several named graphs, where the union is a state that held at no instant.
+
+`reason` and `shacl` therefore take `--valid-at`, `--as-of` and
+`--all-versions` (`valid_at`, `as_of`, `all_versions` over MCP). Over a store
+that describes its named graphs with the temporal vocabulary
+(`https://open-ontologies.org/temporal#`), a run that names none of them is
+REFUSED rather than answered. A store that uses no temporal vocabulary is
+unaffected.
+
+A scoped run reads the in-scope named graphs plus the default graph and drops
+any graph holding this engine's own materialised inferences. NO run over a
+versioned store materialises, scoped or `--all-versions`: every graph it could
+write to is in scope at every instant, so a conclusion written there becomes an
+axiom of every snapshot. The CLI makes any run carrying a scope argument a dry
+one; over MCP, pass `materialize: false`. Every report carries `scope`, naming
+what was read. See [the temporal module](../src/temporal.rs) and issue #108.
+
## What the rule table cannot see, and the three reasons it cannot
A certificate from `onto_reason` is a sound proof about **the axioms the rules
@@ -126,3 +148,8 @@ Every profile except `owl-dl` can emit a derivation certificate
(`reason --certificate DIR`) that the checker in `lean/` verifies against a
machine-checked soundness theorem. What is proved, what is not, and how to run
it: [lean-certificates.md](lean-certificates.md).
+
+The certificate directory also gets `scope.tsv`, the record of which graphs
+`asserted.tsv` was built from. The Lean checker does not read it and cannot:
+it verifies the derivations against the triples in front of it, and cannot ask
+whether those triples are the graph anyone meant.
diff --git a/docs/trusted-computing-base.md b/docs/trusted-computing-base.md
index fbe9538d..7578aafc 100644
--- a/docs/trusted-computing-base.md
+++ b/docs/trusted-computing-base.md
@@ -33,16 +33,22 @@ see:
- the store after the run, so they cannot tell whether a triple was materialised without a
certificate line covering it;
- the rule file the user passed, so they cannot tell whether `rules.tsv` is the table the engine
- evaluated.
+ evaluated;
+- **which graphs the run selected**, so they cannot tell whether `asserted.tsv` is the graph anyone
+ meant. This one is different in kind from the other four, because there is no way to fail it:
+ every one of the others can make a checker REJECT a legitimate run, and this one cannot. A
+ certificate over the union of every version of a bi-temporal register is a true statement, valid
+ under `OOCert.certificate_sound`, about a state of the world that never existed. That is issue
+ #108, and `scope.tsv` (below) is the mitigation.
-Each of those four blind spots is a property below.
+Each of those five blind spots is a property below.
## The emission paths
| path | entry point | files written | checker |
|---|---|---|---|
-| built-in forward chaining | `Reasoner::run_full` (`src/reason.rs`) | `asserted.tsv`, `derivations.tsv` | `oo-cert` |
-| supplied Horn rules | `Reasoner::run_horn` (`src/reason.rs`) | `rules.tsv`, `asserted.tsv`, `horn.tsv` | `oo-horn` |
+| built-in forward chaining | `Reasoner::run_full` (`src/reason.rs`) | `asserted.tsv`, `derivations.tsv`, `scope.tsv` | `oo-cert` |
+| supplied Horn rules | `Reasoner::run_horn` (`src/reason.rs`) | `rules.tsv`, `asserted.tsv`, `horn.tsv`, `scope.tsv` | `oo-horn` |
| DL model certificate | `DlReasoner::write_model_certificate` (`src/tableaux.rs`) | `axioms.tsv`, `model.tsv` | `oo-dlmodel` |
| SHACL | no Rust emission | N-Triples handed to the Lean evaluator | `oo-shacl` |
@@ -110,13 +116,45 @@ tab inside a literal, this engine would stop writing certificates instead of wri
### The asserted graph
-- **TCB-6 (asserted is the graph, no drops).** Every triple in the store at the start of a certified
+- **TCB-6 (asserted is the graph, no drops).** Every triple in the SCOPE at the start of a certified
run appears as a line in `asserted.tsv`. A dropped assertion makes the checker reject a legitimate
step, so this direction is fail-safe, but it is still part of the claim the file makes.
- **TCB-7 (asserted is the graph, no additions).** Every line of `asserted.tsv` corresponds to a
- triple that was in the store at the start of the run. This is the unsafe direction. An extra line
+ triple that was in the SCOPE at the start of the run. This is the unsafe direction. An extra line
is an axiom nobody asserted, and every conclusion resting on it is certified against a graph that
does not exist.
+- **TCB-6a (the scope is recorded).** "The scope" in TCB-6 and TCB-7 means the graphs named by
+ `scope.tsv`, written into the certificate directory by the same block that writes
+ `asserted.tsv`. Until #108 the scope was always the whole store and was written down nowhere, so
+ TCB-6 and TCB-7 quantified over a set the reader had to assume. They now quantify over a set the
+ reader can see. `scope.tsv` is `oo-scope/1`, one `key TAB value` line per fact, with one `graph`
+ line per named graph read (or `graph\t*` for the whole store) and one `excluded` line per graph
+ deliberately not read. **No Lean checker reads it**, and calling it a certificate would be the
+ overclaim this page exists to prevent: it is a record, checkable by a person or a script against
+ the store, and its value is that the selection stops being invisible.
+- **TCB-8 (no inference leaks into the assertions, within a run).** No conclusion of
+ `derivations.tsv` appears in `asserted.tsv`. The engine reaches a fixpoint in one pass and
+ captures `facts` before materialising, so this holds within a run.
+ **Across runs it does not hold for an unscoped run and cannot be made to hold by this layer.**
+ Materialising into the default graph turns run N's conclusions into run N+1's assertions, and
+ `asserted.tsv` has no column that says "derived". `docs/lean-certificates.md` states this under
+ "Known limitations" and decision 0001 is the mitigation (`inference_graph: true` keeps them in a
+ named graph). Note that `GraphStore::all_triples` iterates `store.iter()` over every graph, so
+ inferences parked in `https://open-ontologies.org/graph/inferred` by an earlier run are read back
+ as assertions by a later UNSCOPED certified run. The separation protects `save`, not the
+ certificate.
+ A run over a VERSIONED store is the exception, on both halves. A scoped one reads through
+ `GraphStore::triples_in_scope`, which reads the graphs the scope names and no others, drops the
+ inference graph from that set and records the drop in `scope.tsv`. And no run over such a store
+ materialises at all, scoped or `all_versions`, so none of them creates a next-run assertion:
+ every graph a run could write to is in scope at every instant, which makes the write a poisoning
+ of every future snapshot rather than only of the next run.
+- **TCB-8a (the scope is the one that was asked for).** The graphs listed in `scope.tsv` are the
+ graphs `triples_in_scope` read, and for a snapshot they are exactly the `in_scope` set
+ `Temporal::snapshot` reports at the same instant, less the inference graph. This is a reading of
+ `Temporal::read_scope`, which calls the same `scope()` the snapshot tool calls, plus
+ `tests/temporal_scope_test.rs`, which pins the graph lists at two instants. Nothing derives one
+ from the other.
- **TCB-8 (no inference leaks into the assertions).** No conclusion of `derivations.tsv` appears in
`asserted.tsv`. Within a run this holds because the engine reaches a fixpoint in one pass and
captures `facts` before materialising.
@@ -135,7 +173,8 @@ tab inside a literal, this engine would stop writing certificates instead of wri
asserts the fix for the named graph and the leak for the merged one, in one test, so neither half
can change without the documentation being forced to change with it.
- **TCB-9 (the store is a set, the file is a list).** A triple present in two named graphs is
- written twice, because `all_triples` flattens quads. Duplicate lines are harmless to soundness
+ written twice, because `all_triples` flattens quads — and so does `triples_in_scope`, where both
+ of those graphs are in the scope. Duplicate lines are harmless to soundness
(the Lean side builds a `HashSet`) but `asserted` in the JSON report counts lines, not distinct
triples. The Horn path reports both numbers; the built-in path reports only the line count.
@@ -462,6 +501,97 @@ purpose is to enumerate what is trusted. A page that lists `oxrdf`'s escaping as
and omits the proof checker that every theorem on this page depends on was understating its own
trusted base by a wide margin, and the omission is recorded here rather than quietly repaired.
+1. **`oxrdf`'s escaping is the entire escaping layer.** `asserted.tsv` is safe because
+ `print_quoted_str` turns a tab inside a literal into `\t`. This repository has no escaper of its
+ own and never inspects a term. TCB-4 pins the behaviour a test can observe, which means an
+ upgrade that changed it would fail loudly; it does not mean it cannot change, and it does not
+ cover a term that reaches the store by a route the tests do not exercise.
+ *To close it:* escape at the certificate writer rather than relying on the term's `Display`, or
+ change the format to one that cannot be forged by its payload (length-prefixed, or JSON Lines).
+ Both are changes to `lean/`'s parsers as well, which is why neither was done here.
+2. **`oxiri`'s IRI validation is why a separator cannot reach an IRI.** `NamedNodeRef`'s `Display`
+ is `write!(f, "<{}>", self.as_str())` with no escaping at all, so the only thing standing between
+ a tab and `asserted.tsv` is that the parser refused to build the IRI. Tens of thousands of lines
+ of parsing sit behind that sentence and none of it is verified here.
+ *To close it:* check the term at the writer, as in (1). The check is four lines; the reason it is
+ not there is that it would be a second place the question is decided.
+3. **TCB-14, the premise ORDER per rule.** `OOCert.checkStep` matches premises positionally, arm by
+ arm, and the emitter passes them in a hand-written order at thirty-one call sites. The two agree
+ because `tests/lean_certificate_test.rs` walks every rule and the checker accepts. Nothing
+ derives one from the other, so a rule added with the wrong order fails at the checker rather than
+ at compile time. *To close it:* generate both sides from one table, which is what the Horn path
+ already does and the built-in path does not.
+4. **TCB-26, the DL name guard's coverage.** `name_is_safe` is applied to a `names` vector built by
+ one loop; the files are written by another. Individuals in `model.ind` are covered only because
+ `DlAxiom::Indiv(i)` happens to be emitted for every individual that reaches the model.
+ *To close it:* check at the point of writing, not in a separate pass.
+5. **TCB-8 across runs, on the UNSCOPED path.** Materialising into the default graph turns an
+ inference into the next run's assertion, and `asserted.tsv` has no column that says "derived".
+ `inference_graph: true` does not fix it either: `GraphStore::all_triples` reads every named
+ graph, so a later certified run sees them as assertions. The separation protects `save`; it does
+ not protect the certificate. *Closed for a scoped run* (#108): `triples_in_scope` reads the
+ graphs the scope names, the inference graph is not one of them, the drop is recorded in
+ `scope.tsv`, and a scoped run materialises nothing. *Still open for an unscoped run,* which is
+ every run over a store that does not use the temporal vocabulary — that is, most of them. *To
+ close it there:* a scope argument that names the asserted graphs on a store with no temporal
+ metadata, which is `ReadScope::Graphs` with no selector in front of it and is not wired to any
+ tool today.
+6. **Materialisation is not atomic, and that is now latent rather than fixed.** `GraphStore::
+ load_lines` runs `for quad in parser { store.insert(&quad?)?; }`, so a parse error partway
+ through a batch leaves everything before it inserted and propagates the error. That is what
+ turned the `rdfs7` defect from a crash into uncertified triples in the store. `writable_triple`
+ removes the only way the reasoner could hand it an unparseable line, so the path is unreachable
+ TODAY; the hazard is still there for any future caller.
+ *To close it:* insert into a transaction, or build the batch through a serialiser that cannot
+ produce an unparseable line rather than through string concatenation.
+7. **The reasoner's completeness.** The checker proves each recorded step is a sound instance of a
+ rule it knows. It says nothing about whether the engine found every inference, so a certificate
+ is evidence about what was derived and not about what follows.
+8. **The SHIQ tableaux reasoner.** Model certificates cover positive satisfiability answers only.
+ Unsatisfiability and inconsistency carry no certificate at all, and those are the answers a
+ consistency check is usually asked for.
+9. **The Rust SHACL validator (TCB-28, TCB-29).** Not certified. `oo-shacl` is a second, verified
+ evaluator that the Rust one is measured against; a measurement is not a proof, and the two read
+ RDF with two different parsers whose agreement is by construction on both sides rather than by a
+ check.
+10. **Everything between the store and the certificate that is not a term:** the SPARQL layer, the
+ MCP server, the CLI, the daemon, the file I/O, the roughly fifty thousand lines of `src/`. The
+ Kani harnesses cover four pure functions totalling about twenty lines. That is the correct
+ proportion to report: this work verified the joint, not the machine.
+11. **The scope of a run is recorded, not checked.** `scope.tsv` says which graphs `asserted.tsv`
+ was built from. No Lean checker reads it; nothing compares it against the store; a caller who
+ ignores it is exactly as exposed as before #108. What changed is that the selection is now a
+ value the engine computed and wrote down, rather than a consequence of which method the code
+ happened to call, so a disagreement between the scope and the certificate is a thing a reviewer
+ CAN find. *To close it:* a checker that takes the store and `scope.tsv` and re-derives
+ `asserted.tsv`, which is a verified RDF store away and not a Lean file away.
+12. **A blank-node graph name makes a scoped run error rather than answer.** `Temporal`'s graph
+ scan binds `?g` inside `GRAPH ?g { … }`, which in oxigraph can bind a blank node, and both
+ consumers then build an IRI from it: the scoped reader returns `_:g1 is not an IRI: Invalid IRI
+ code point ':'` and `query_at` would splice `FROM NAMED <_:g1>` into a query that does not
+ parse. Measured on 15 September 2026 with `reason --valid-at` over a TriG file using `_:g1 { … }`.
+ This fails in the safe direction and is pre-existing rather than introduced by #108 — the
+ temporal query layer had it already — but a store loaded from TriG or N-Quads with unnamed
+ graphs cannot be scoped at all. *To close it:* carry graph names as terms rather than as
+ strings through `Temporal::all_graphs`, `ReadScope` and `query_at`.
+13. **The default graph enters a snapshot wholesale.** A scoped run reads the in-scope named graphs
+ plus the whole default graph, because that is where the schema lives and a snapshot of the ABox
+ with no TBox answers a question nobody asked. The default graph also holds the validity metadata
+ itself, so `temporal:validFrom` and its siblings are in the reasoner's closure and are counted as
+ triples of their graph IRIs by SHACL. On the shapes people write this is inert — the subjects are
+ graph IRIs, and the predicates carry no declared domain or range — and it is not inert in
+ principle: a shape targeting a class that a graph IRI belongs to, or an `rdfs:domain` asserted on
+ a temporal predicate, would see them. It is visible in `asserted.tsv` and pinned by
+ `tests/temporal_scope_test.rs`. *To close it:* an explicitly named schema graph, which decides
+ for the user where their schema lives, or a predicate-namespace filter, which decides that the
+ engine's vocabulary can never be domain data. Neither was worth taking on the user's behalf.
+
+The honest summary is that the trusted base is five things: the serialisation of a term, the
+identity of the asserted graph, the SELECTION of the asserted graph, the completeness of the
+derivation record, and the identity of the rule table. Those are now property-tested and, for the pure parts, bounded-model-checked. Every one
+of them still rests on a dependency's behaviour that this repository observes rather than enforces.
+The engine is not verified. It was never going to be, and a report that read as though it were
+would be the same defect this project exists to attack.
1. **TCB-6 and TCB-7, that `asserted.tsv` IS the store's contents.** The engine reads the store,
interns what it reads, and writes the interned strings back out. Nothing between the store and
the file checks that the file is the store. `tests/certificate_boundary_proptest.rs` re-reads
diff --git a/python/src/open_ontologies_lite/horn/reason.py b/python/src/open_ontologies_lite/horn/reason.py
index e7275a87..fec3d593 100644
--- a/python/src/open_ontologies_lite/horn/reason.py
+++ b/python/src/open_ontologies_lite/horn/reason.py
@@ -246,7 +246,7 @@ def _facts(store, graphs) -> tuple[list[Fact], list[str]]:
The default is the DEFAULT GRAPH ALONE, which is where `OntologyEngine.load()`
puts everything, so this package's own users lose nothing by it. The Rust
engine flattens every named graph here EXCEPT the inferred one
- (`src/reason.rs:2935`, `graph.triples_outside(&[INFERRED_GRAPH])`). Before
+ (`src/reason.rs:3110`, `graph.triples_in_scope(&scope)`). Before
15 September 2026 it excepted nothing, which was the defect above: a store
holding a prior materialisation turned derived triples into assertions.
"""
diff --git a/python/tests/test_horn_differential.py b/python/tests/test_horn_differential.py
index 00afa4f8..d6b2db7d 100644
--- a/python/tests/test_horn_differential.py
+++ b/python/tests/test_horn_differential.py
@@ -26,7 +26,7 @@ WHAT IS COMPARED, AND WHAT IS NOT.
The assertion is SET EQUALITY OF DERIVED TRIPLES against the Rust `run_horn`, over
the same `builtin_rules.tsv`. Byte identity of the two `horn.tsv` files is NOT a
goal and must not be asserted: the Rust emitter sorts interned `u32` triples
-(`src/reason.rs:3005`, `all.sort_unstable()` over `Vec<(u32,u32,u32)>`), so its
+(`src/reason.rs:3180`, `all.sort_unstable()` over `Vec<(u32,u32,u32)>`), so its
line order is first-appearance order in the store, not lexicographic order.
Reproducing it from Python would mean reimplementing the interner and betting on
identical store-iteration order across two bindings, to buy nothing the set
diff --git a/python/tests/test_horn_fixpoint_and_scope.py b/python/tests/test_horn_fixpoint_and_scope.py
index 55850735..90ee15b6 100644
--- a/python/tests/test_horn_fixpoint_and_scope.py
+++ b/python/tests/test_horn_fixpoint_and_scope.py
@@ -24,7 +24,7 @@ previous materialisation in the inferred graph turned derived triples into
ASSERTIONS. The checker could not detect it: the soundness theorem is conditional
on the assertions, and it is TOLD what they are, so the result was a green
absolute verdict about a graph nobody asserted. It now reads
-`src/reason.rs:2935`, `graph.triples_outside(&[INFERRED_GRAPH])`, and the
+`src/reason.rs:3110`, `graph.triples_in_scope(&scope)`, and the
inferred graph is out of scope.
The two engines still differ in HOW, and the difference is deliberate. Rust
diff --git a/src/batch.rs b/src/batch.rs
index 06eb45d4..5b41ab77 100644
--- a/src/batch.rs
+++ b/src/batch.rs
@@ -278,6 +278,24 @@ impl BatchRunner {
.unwrap_or("rdfs".to_string());
let certificate = Self::flag_value(args, "--certificate");
let rules = Self::flag_value(args, "--rules");
+ // #108. Batch is the only entry point that can load and certify in one
+ // process, so it is the one a certified run over a versioned store
+ // actually uses. A batch runner that did not understand these flags
+ // would leave the gate with no way through on the path that needs it
+ // most.
+ let request = match crate::temporal::ScopeRequest::from_args(
+ Self::flag_value(args, "--valid-at").as_deref(),
+ Self::flag_value(args, "--as-of").as_deref(),
+ args.iter().any(|a| a == "--all-versions"),
+ ) {
+ Ok(r) => r,
+ Err(e) => return json!({"error": e.to_string()}),
+ };
+ // Nothing may be written into a versioned store, so passing any
+ // temporal scope argument makes the run a DRY one rather than a
+ // refusal on every scoped invocation. A run with no such argument
+ // keeps the historical `true` and is refused before it can write.
+ let materialize = matches!(request, crate::temporal::ScopeRequest::Unscoped);
// `--rules FILE` evaluates a SUPPLIED Horn table instead of a built-in
// profile and writes a certificate `oo-horn check` can verify. It needs
// somewhere to put that certificate: a run over rules nobody has
@@ -285,10 +303,11 @@ impl BatchRunner {
// certificate there would be nothing to check and the counts would
// stand on the engine's word alone.
let result = match (rules.as_deref(), certificate.as_deref()) {
- (Some(rules_path), Some(dir)) => Reasoner::run_horn(
+ (Some(rules_path), Some(dir)) => Reasoner::run_horn_scoped(
&self.graph,
std::path::Path::new(rules_path),
std::path::Path::new(dir),
+ &request,
)
.unwrap_or_else(|e| json!({"error": e.to_string()}).to_string()),
(Some(_), None) => json!({
@@ -297,14 +316,15 @@ impl BatchRunner {
`lake exe oo-horn check` is what pronounces on it"
})
.to_string(),
- (None, cert) => Reasoner::run_full(
+ (None, cert) => Reasoner::run_scoped(
&self.graph,
&profile,
- true,
+ materialize,
InferenceTarget::DefaultGraph,
cert.map(std::path::Path::new),
+ &request,
)
- .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e)),
+ .unwrap_or_else(|e| json!({"error": e.to_string()}).to_string()),
};
serde_json::from_str(&result).unwrap_or(json!({"raw": result}))
}
@@ -560,10 +580,19 @@ impl BatchRunner {
Some(p) => p,
None => return json!({"error": "shacl requires a shapes file path"}),
};
+ let request = match crate::temporal::ScopeRequest::from_args(
+ Self::flag_value(args, "--valid-at").as_deref(),
+ Self::flag_value(args, "--as-of").as_deref(),
+ args.iter().any(|a| a == "--all-versions"),
+ ) {
+ Ok(r) => r,
+ Err(e) => return json!({"error": e.to_string()}),
+ };
match std::fs::read_to_string(shapes_path) {
Ok(shapes_content) => {
- let result = ShaclValidator::validate(&self.graph, &shapes_content)
- .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
+ let result =
+ ShaclValidator::validate_scoped(&self.graph, &shapes_content, &request)
+ .unwrap_or_else(|e| json!({"error": e.to_string()}).to_string());
serde_json::from_str(&result).unwrap_or(json!({"raw": result}))
}
Err(e) => json!({"error": e.to_string()}),
diff --git a/src/graph.rs b/src/graph.rs
index 7503927c..2a3754a9 100644
--- a/src/graph.rs
+++ b/src/graph.rs
@@ -16,6 +16,101 @@ pub struct ValidationCounts {
pub triples: usize,
}
+/// The graphs one run may read.
+///
+/// Until #108 every verdict-producing path in this engine read the WHOLE
+/// store and had no vocabulary for saying so. The reasoner read it through
+/// [`GraphStore::all_triples`], which iterates every quad and drops the graph
+/// name; the SHACL validator read it through
+/// [`GraphStore::sparql_select_union`], which makes the default graph the
+/// union of every graph. On a single-version store those are the same set and
+/// the right one. On a store that keeps one entity's versions in one named
+/// graph each, they are a union of states that held at no instant, and a
+/// verdict over that union is neither what was true then nor what is true now.
+///
+/// The failure is invisible to every gate this project has, which is why it
+/// needed a type rather than a flag. A derivation certificate is a claim about
+/// the graph in `asserted.tsv`, and the Lean checker verifies exactly that
+/// claim; if the triples in `asserted.tsv` were selected by a scope nobody
+/// chose, the certificate is valid and the answer is wrong. Making the scope a
+/// value means a run can RECORD what it read, and a reader can audit the scope
+/// instead of assuming it.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum ReadScope {
+ /// The default graph and every named graph. The historical behaviour, and
+ /// what a store with no versioning means.
+ AllGraphs,
+ /// Exactly these graphs. `default_graph` says whether the store's default
+ /// graph is one of them; `named` lists the named graphs, in the order they
+ /// are to be read.
+ Graphs {
+ default_graph: bool,
+ named: Vec<String>,
+ },
+}
+
+impl ReadScope {
+ /// The graph names this scope admits, for a certificate to record.
+ ///
+ /// A certificate that does not say which graphs it read cannot be checked
+ /// against the store it claims to be about, so both reading paths report
+ /// this: the one that excludes named graphs by name, and this one, which
+ /// names the set it selected.
+ pub fn graphs_read(&self) -> Vec<String> {
+ match self {
+ ReadScope::AllGraphs => vec!["(every graph in the store)".to_string()],
+ ReadScope::Graphs { default_graph, named } => {
+ let mut v = Vec::with_capacity(named.len() + 1);
+ if *default_graph {
+ v.push("(default graph)".to_string());
+ }
+ v.extend(named.iter().cloned());
+ v
+ }
+ }
+ }
+
+ /// True when this scope is the whole store.
+ pub fn is_all_graphs(&self) -> bool {
+ matches!(self, ReadScope::AllGraphs)
+ }
+
+ /// Point a prepared query's dataset at exactly this scope.
+ ///
+ /// Both halves matter. `set_default_graph` is what an UNGUARDED pattern
+ /// reads, which is every pattern the SHACL validator emits. Restricting
+ /// the available NAMED graphs to the same set is what stops a `GRAPH`
+ /// block a caller wrote — in a `sh:sparql` constraint, say — from reaching
+ /// a graph the scope excluded.
+ fn apply(
+ &self,
+ dataset: &mut oxigraph::sparql::QueryDatasetSpecification,
+ ) -> anyhow::Result<()> {
+ match self {
+ ReadScope::AllGraphs => dataset.set_default_graph_as_union(),
+ ReadScope::Graphs {
+ default_graph,
+ named,
+ } => {
+ let mut names: Vec<GraphName> = Vec::with_capacity(named.len() + 1);
+ if *default_graph {
+ names.push(GraphName::DefaultGraph);
+ }
+ let mut available: Vec<NamedOrBlankNode> = Vec::with_capacity(named.len());
+ for g in named {
+ let node =
+ NamedNode::new(g).map_err(|e| anyhow::anyhow!("{g} is not an IRI: {e}"))?;
+ names.push(GraphName::NamedNode(node.clone()));
+ available.push(NamedOrBlankNode::NamedNode(node));
+ }
+ dataset.set_default_graph(names);
+ dataset.set_available_named_graphs(available);
+ }
+ }
+ Ok(())
+ }
+}
+
/// Optional HTTP authentication for remote SPARQL endpoints.
///
/// Enterprise triple stores gate their SPARQL Protocol endpoints behind auth:
@@ -384,7 +479,13 @@ impl GraphStore {
if union_default_graph {
prepared.dataset_mut().set_default_graph_as_union();
}
- match prepared.on_store(store).execute()? {
+ Self::render(prepared.on_store(store).execute()?)
+ }
+
+ /// The JSON every SELECT path in this module returns, so a scoped run and
+ /// an unscoped one differ in the dataset they read and in nothing else.
+ fn render(results: QueryResults) -> anyhow::Result<String> {
+ match results {
QueryResults::Solutions(solutions) => {
let vars: Vec<String> = solutions
.variables()
@@ -720,12 +821,21 @@ impl GraphStore {
/// Extract all triples as (subject, predicate, object) string tuples.
///
- /// EVERY graph, the default one and every named one, flattened. A caller
- /// that is going to treat what it gets back as ASSERTED wants
- /// [`triples_outside`](Self::triples_outside) instead: this method cannot
- /// tell an assertion from a triple some earlier run of the reasoner parked
- /// in a named graph, and the certificate layer's soundness theorem is
- /// conditional on the assertions.
+ /// Reads EVERY graph and drops the graph name. That is the right answer for
+ /// a single-version store and the wrong one for a store that keeps several
+ /// versions of the same entity in several named graphs, where the union is
+ /// a state that held at no instant.
+ ///
+ /// A caller that is going to treat what it gets back as ASSERTED wants one
+ /// of the two narrower forms instead, because this method cannot tell an
+ /// assertion from a triple some earlier run of the reasoner parked in a
+ /// named graph, and the certificate layer's soundness theorem is
+ /// conditional on the assertions:
+ /// [`triples_outside`](Self::triples_outside) excludes named graphs by
+ /// name, and [`triples_in_scope`](Self::triples_in_scope) reads a stated
+ /// set. This one is what [`ReadScope::AllGraphs`] means and is kept
+ /// unchanged so a run that asks for every graph gets byte-identical input
+ /// to the one it always got.
pub fn all_triples(&self) -> anyhow::Result<Vec<(String, String, String)>> {
let store = &self.store;
let mut triples = Vec::new();
@@ -739,6 +849,134 @@ impl GraphStore {
Ok(triples)
}
+ /// The triples of exactly the graphs a scope names, in the spelling
+ /// [`all_triples`](Self::all_triples) yields.
+ ///
+ /// The default graph comes first when it is in scope, then each named
+ /// graph in the order the scope lists them, so the line order of a
+ /// certificate written from this is a function of the scope and the store
+ /// rather than of iteration order.
+ ///
+ /// A named graph the scope lists and the store does not hold contributes
+ /// nothing and is NOT an error: a snapshot names the graphs that were in
+ /// scope, and a graph can be in scope and empty.
+ pub fn triples_in_scope(&self, scope: &ReadScope) -> anyhow::Result<AssertedTriples> {
+ let ReadScope::Graphs {
+ default_graph,
+ named,
+ } = scope
+ else {
+ // `AllGraphs` is every graph the caller may read, and that is still
+ // not every graph in the store: the inference graph is where this
+ // engine parks its OWN conclusions, and reading them back makes run
+ // N's conclusions run N+1's axioms with nothing in `asserted.tsv`
+ // saying they were derived. TCB-8.
+ //
+ // This used to be `all_triples()`, which is byte-identical to the
+ // historical behaviour and reintroduced that defect the moment a
+ // store held a previous materialisation.
+ // `tcb_8_across_runs_only_the_default_graph_leaks` caught it.
+ return self.triples_outside(&[crate::reason::INFERRED_GRAPH]);
+ };
+ let mut triples = Vec::new();
+ // The names actually read, in the order read, so a certificate records
+ // what it was built from rather than what was asked for. The two differ
+ // whenever a named graph in scope holds nothing.
+ let mut read: Vec<String> = Vec::new();
+ // Returns how many it took, so the caller can record the graph only
+ // when it actually contributed. Counting inside avoids reading
+ // `triples.len()` while the closure still holds it mutably.
+ let mut take = |g: GraphNameRef<'_>| -> anyhow::Result<usize> {
+ let mut n = 0usize;
+ for quad in self.store.quads_for_pattern(None, None, None, Some(g)) {
+ let q = quad?;
+ triples.push((
+ q.subject.to_string(),
+ q.predicate.to_string(),
+ q.object.to_string(),
+ ));
+ n += 1;
+ }
+ Ok(n)
+ };
+ if *default_graph && take(GraphNameRef::DefaultGraph)? > 0 {
+ read.push("<default>".to_string());
+ }
+ for g in named {
+ let node = NamedNode::new(g).map_err(|e| anyhow::anyhow!("{g} is not an IRI: {e}"))?;
+ if take(GraphNameRef::NamedNode(node.as_ref()))? > 0 {
+ read.push(g.clone());
+ }
+ }
+ Ok((triples, read))
+ }
+
+ /// Run a SELECT over exactly the graphs a scope names.
+ ///
+ /// [`ReadScope::AllGraphs`] is [`sparql_select_union`](Self::sparql_select_union)
+ /// unchanged. A stated set of graphs becomes the query's default graph, so
+ /// an UNGUARDED pattern sees the union of those graphs and nothing else,
+ /// and the same set is the only one a `GRAPH` block can reach: without
+ /// [`set_available_named_graphs`] a `sh:sparql` constraint could name an
+ /// out-of-scope graph and read it, which is the escape `Temporal::query_at`
+ /// closes with `FROM NAMED` for the same reason.
+ ///
+ /// [`set_available_named_graphs`]: https://docs.rs/spareval
+ pub fn sparql_select_scoped(&self, query: &str, scope: &ReadScope) -> anyhow::Result<String> {
+ match scope {
+ ReadScope::AllGraphs => self.sparql_select_union(query),
+ ReadScope::Graphs { .. } => {
+ let mut prepared = SparqlEvaluator::new().parse_query(query)?;
+ scope.apply(prepared.dataset_mut())?;
+ Self::render(prepared.on_store(&self.store).execute()?)
+ }
+ }
+ }
+
+ /// [`sparql_select_union_prebound`](Self::sparql_select_union_prebound),
+ /// restricted to the graphs a scope names.
+ pub fn sparql_select_scoped_prebound(
+ &self,
+ query: &str,
+ var: &str,
+ terms: &[Term],
+ scope: &ReadScope,
+ ) -> anyhow::Result<Vec<Vec<std::collections::HashMap<String, String>>>> {
+ let store = &self.store;
+ let mut prepared = SparqlEvaluator::new().parse_query(query)?;
+ scope.apply(prepared.dataset_mut())?;
+ let variable = Variable::new(var)?;
+ let mut out = Vec::with_capacity(terms.len());
+ for term in terms {
+ let bound = prepared
+ .clone()
+ .substitute_variable(variable.clone(), term.clone());
+ let QueryResults::Solutions(solutions) = bound.on_store(store).execute()? else {
+ anyhow::bail!("pre-bound evaluation needs a SELECT query");
+ };
+ let vars: Vec<String> = solutions
+ .variables()
+ .iter()
+ .map(|v| v.as_str().to_string())
+ .collect();
+ let mut rows = Vec::new();
+ for solution in solutions {
+ let solution = solution?;
+ let mut row = std::collections::HashMap::new();
+ for v in &vars {
+ if let Some(t) = solution.get(v.as_str()) {
+ row.insert(v.clone(), t.to_string());
+ }
+ }
+ row.entry(var.to_string())
+ .or_insert_with(|| term.to_string());
+ rows.push(row);
+ }
+ out.push(rows);
+ }
+ Ok(out)
+ }
+
/// Every triple in the store EXCEPT those in the named graphs listed, in
/// the same spelling [`all_triples`](Self::all_triples) yields, together
/// with the names of the graphs that were read.
diff --git a/src/inputs.rs b/src/inputs.rs
index 394d48b4..8b2d2923 100644
--- a/src/inputs.rs
+++ b/src/inputs.rs
@@ -222,6 +222,19 @@ pub struct OntoShaclInput {
pub shapes: String,
/// If true, treat shapes as inline Turtle content
pub inline: Option<bool>,
+ /// Validate the snapshot that was TRUE at this instant. Read like
+ /// `onto_temporal_snapshot`'s `valid_at`: `xsd:date`, `xsd:dateTime`,
+ /// `xsd:gYearMonth` or `xsd:gYear`, no offset meaning UTC.
+ pub valid_at: Option<String>,
+ /// Validate the snapshot that was KNOWN at this instant, the recorded-time
+ /// axis. Combines with `valid_at`; either may be given alone.
+ pub as_of: Option<String>,
+ /// Validate every version at once, over a store that has versions. A real
+ /// question ("does ANY version violate this shape") and a different one
+ /// from any snapshot's, so it is said out loud. Refused together with
+ /// `valid_at` or `as_of`. On a store that uses no temporal vocabulary this
+ /// changes nothing: every graph is read either way.
+ pub all_versions: Option<bool>,
}
#[derive(Deserialize, JsonSchema)]
@@ -304,6 +317,22 @@ pub struct OntoReasonInput {
/// pronounces on that, and it distinguishes the built-in table from any
/// other. See docs/decisions/0003.
pub rules_file: Option<String>,
+ /// Reason over the snapshot that was TRUE at this instant. Read like
+ /// `onto_temporal_snapshot`'s `valid_at`: `xsd:date`, `xsd:dateTime`,
+ /// `xsd:gYearMonth` or `xsd:gYear`, no offset meaning UTC.
+ ///
+ /// No run over a versioned store materialises, and it refuses rather than
+ /// dropping the flag, because there is no graph in such a store that a
+ /// conclusion can be written to without becoming an axiom of every
+ /// snapshot. Pass `materialize: false`.
+ pub valid_at: Option<String>,
+ /// Reason over the snapshot that was KNOWN at this instant, the
+ /// recorded-time axis. Combines with `valid_at`; either may be given alone.
+ pub as_of: Option<String>,
+ /// Reason over every version at once, over a store that has versions.
+ /// Refused together with `valid_at` or `as_of`. On a store that uses no
+ /// temporal vocabulary this changes nothing.
+ pub all_versions: Option<bool>,
}
#[derive(Deserialize, JsonSchema)]
@@ -1507,6 +1536,12 @@ pub struct OntoReasonIncrementalInput {
pub delta: String,
/// Write the inferences into the store (default true)
pub materialize: Option<bool>,
+ /// Reason over every version at once, over a store that has versions.
+ /// This path has NO snapshot form: it reads the union of every graph and
+ /// materialises into the default graph, so over a versioned store it is
+ /// refused unless this says the union is what you meant. Use `onto_reason`
+ /// with `valid_at` / `as_of` for a snapshot.
+ pub all_versions: Option<bool>,
}
#[derive(Deserialize, JsonSchema)]
diff --git a/src/main.rs b/src/main.rs
index e7855bd1..3eddb6e7 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -431,7 +431,21 @@ enum Commands {
base_iri: Option<String>,
},
/// Validate against SHACL shapes
- Shacl { shapes: String },
+ Shacl {
+ shapes: String,
+ /// Validate the snapshot that was TRUE at this instant (#108). Read as
+ /// an instant on the UTC timeline, like `temporal-snapshot --valid-at`.
+ #[arg(long)]
+ valid_at: Option<String>,
+ /// Validate the snapshot that was KNOWN at this instant.
+ #[arg(long)]
+ as_of: Option<String>,
+ /// Validate every version at once over a store that has versions. A
+ /// different question from any snapshot's, so it is said out loud;
+ /// refused together with --valid-at or --as-of.
+ #[arg(long)]
+ all_versions: bool,
+ },
/// Closed-world vocab check: flag data terms not declared in the loaded ontology
VocabCheck { data: String },
/// Run inference (rdfs, owl-rl, owl-rl-ext, owl-dl)
@@ -457,6 +471,18 @@ enum Commands {
/// table is the whole rule set for the run. Nothing is materialised.
#[arg(long)]
rules: Option<String>,
+ /// Reason over the snapshot that was TRUE at this instant (#108).
+ /// Passing any temporal scope argument makes the run a DRY one:
+ /// nothing may be written into a versioned store.
+ #[arg(long)]
+ valid_at: Option<String>,
+ /// Reason over the snapshot that was KNOWN at this instant.
+ #[arg(long)]
+ as_of: Option<String>,
+ /// Reason over every version at once over a store that has versions;
+ /// refused together with --valid-at or --as-of.
+ #[arg(long)]
+ all_versions: bool,
},
/// Export the loaded ontology as first-order logic, for a prover or a model finder
///
@@ -889,7 +915,14 @@ impl Commands {
Commands::Query { query } => cmd("query", vec![query.clone()]),
Commands::Lint { input } => cmd("lint", vec![absolutize(input)]),
Commands::Defects { input } => cmd("defects", vec![absolutize(input)]),
- Commands::Reason { profile, certificate, rules } => {
+ Commands::Reason {
+ profile,
+ certificate,
+ rules,
+ valid_at,
+ as_of,
+ all_versions,
+ } => {
let mut a = vec!["--profile".into(), profile.clone()];
if let Some(c) = certificate {
a.push("--certificate".into());
@@ -899,6 +932,17 @@ impl Commands {
a.push("--rules".into());
a.push(absolutize(r));
}
+ if let Some(v) = valid_at {
+ a.push("--valid-at".into());
+ a.push(v.clone());
+ }
+ if let Some(v) = as_of {
+ a.push("--as-of".into());
+ a.push(v.clone());
+ }
+ if *all_versions {
+ a.push("--all-versions".into());
+ }
cmd("reason", a)
}
Commands::Fol { out, format, smt_domain, clif_dialect, clif_comments, goals, goals_skip_columns } => {
@@ -1082,7 +1126,26 @@ impl Commands {
}
cmd("closure-diff", a)
}
- Commands::Shacl { shapes } => cmd("shacl", vec![absolutize(shapes)]),
+ Commands::Shacl {
+ shapes,
+ valid_at,
+ as_of,
+ all_versions,
+ } => {
+ let mut a = vec![absolutize(shapes)];
+ if let Some(v) = valid_at {
+ a.push("--valid-at".into());
+ a.push(v.clone());
+ }
+ if let Some(v) = as_of {
+ a.push("--as-of".into());
+ a.push(v.clone());
+ }
+ if *all_versions {
+ a.push("--all-versions".into());
+ }
+ cmd("shacl", a)
+ }
Commands::Status => cmd("status", vec![]),
Commands::Pull { url, sparql, query } => {
let mut a = vec![url.clone()];
@@ -2768,12 +2831,24 @@ async fn async_main() -> anyhow::Result<()> {
}
}
}
- Commands::Shacl { shapes } => {
+ Commands::Shacl {
+ shapes,
+ valid_at,
+ as_of,
+ all_versions,
+ } => {
use open_ontologies::shacl::ShaclValidator;
let (_db, graph) = setup(&cli.data_dir)?;
let shapes_content = std::fs::read_to_string(&shapes)?;
- let result = ShaclValidator::validate(&graph, &shapes_content)
- .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
+ let result = match open_ontologies::temporal::ScopeRequest::from_args(
+ valid_at.as_deref(),
+ as_of.as_deref(),
+ all_versions,
+ ) {
+ Ok(request) => ShaclValidator::validate_scoped(&graph, &shapes_content, &request)
+ .unwrap_or_else(|e| serde_json::json!({"error": e.to_string()}).to_string()),
+ Err(e) => serde_json::json!({"error": e.to_string()}).to_string(),
+ };
output_result(&result, cli.pretty);
}
Commands::VocabCheck { data } => {
@@ -2783,15 +2858,43 @@ async fn async_main() -> anyhow::Result<()> {
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result_checked(&result, cli.pretty);
}
- Commands::Reason { profile, certificate, rules } => {
+ Commands::Reason {
+ profile,
+ certificate,
+ rules,
+ valid_at,
+ as_of,
+ all_versions,
+ } => {
use open_ontologies::reason::{InferenceTarget, Reasoner};
let (_db, graph) = setup(&cli.data_dir)?;
+ let request = match open_ontologies::temporal::ScopeRequest::from_args(
+ valid_at.as_deref(),
+ as_of.as_deref(),
+ all_versions,
+ ) {
+ Ok(r) => r,
+ Err(e) => {
+ output_result_checked(
+ &serde_json::json!({"error": e.to_string()}).to_string(),
+ cli.pretty,
+ );
+ return Ok(());
+ }
+ };
+ // Nothing may be written into a versioned store, so passing any
+ // temporal scope argument here makes the run a DRY one rather than
+ // a refusal on every scoped invocation. The report says `dry_run`.
+ // A run with no such argument keeps the CLI's historical `true`,
+ // and on a versioned store it is refused before it can write.
+ let materialize = matches!(request, open_ontologies::temporal::ScopeRequest::Unscoped);
let result = match (rules.as_deref(), certificate.as_deref()) {
// A supplied table and somewhere to put the certificate.
- (Some(rules_path), Some(dir)) => Reasoner::run_horn(
+ (Some(rules_path), Some(dir)) => Reasoner::run_horn_scoped(
&graph,
std::path::Path::new(rules_path),
std::path::Path::new(dir),
+ &request,
)
.unwrap_or_else(|e| serde_json::json!({"error": e.to_string()}).to_string()),
// A supplied table and nowhere to put the certificate. The run
@@ -2804,14 +2907,15 @@ async fn async_main() -> anyhow::Result<()> {
and `lake exe oo-horn check` is what pronounces on it"
})
.to_string(),
- (None, cert) => Reasoner::run_full(
+ (None, cert) => Reasoner::run_scoped(
&graph,
&profile,
- true,
+ materialize,
InferenceTarget::DefaultGraph,
cert.map(std::path::Path::new),
+ &request,
)
- .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e)),
+ .unwrap_or_else(|e| serde_json::json!({"error": e.to_string()}).to_string()),
};
output_result_checked(&result, cli.pretty);
}
@@ -3507,11 +3611,16 @@ mod proxy_serialization_tests {
Commands::Stats,
Commands::Query { query: "SELECT ?s WHERE { ?s ?p ?o }".into() },
Commands::Lint { input: "x.ttl".into() },
- Commands::Reason { profile: "rdfs".into(), certificate: None, rules: None },
+ Commands::Reason { profile: "rdfs".into(), certificate: None, rules: None, valid_at: None, as_of: None, all_versions: false },
+ // The scoped form proxies too: a daemon-backed `reason --valid-at`
+ // that silently dropped the flag would run over every version and
+ // report a snapshot it did not have.
+ Commands::Reason { profile: "rdfs".into(), certificate: None, rules: None, valid_at: Some("2026-01-01".into()), as_of: None, all_versions: false },
Commands::Fol { out: "/tmp/fol".into(), format: "tptp".into(), smt_domain: None, clif_dialect: "iso".into(), clif_comments: "standalone".into(), goals: None, goals_skip_columns: 0 },
Commands::FolModel { out: "/tmp/folmodel".into(), solver: "z3".into(), max_domain: 16, timeout_secs: 30, unbounded_probe: true, goals: None, goals_skip_columns: 0, checker: None },
Commands::FolProve { out: Some("/tmp/folprove".into()), prover: "vampire".into(), timeout_secs: 30, goals: None, goals_skip_columns: 0, problem: None, proof: None },
- Commands::Shacl { shapes: "s.ttl".into() },
+ Commands::Shacl { shapes: "s.ttl".into(), valid_at: None, as_of: None, all_versions: false },
+ Commands::Shacl { shapes: "s.ttl".into(), valid_at: None, as_of: None, all_versions: true },
Commands::Status,
Commands::Pull { url: "http://example.org".into(), sparql: false, query: None },
Commands::Push { endpoint: "http://example.org".into(), graph: None },
diff --git a/src/reason.rs b/src/reason.rs
index a0d6e5a1..3eb34e79 100644
--- a/src/reason.rs
+++ b/src/reason.rs
@@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use crate::graph::GraphStore;
+use crate::temporal::ScopeRequest;
// Well-known IRIs
const RDF_TYPE: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";
@@ -1170,10 +1171,12 @@ impl Reasoner {
/// Run the forward-chaining reasoner and, when `certificate_dir` is given,
/// write a derivation certificate beside the result.
///
- /// The certificate is two tab-separated files: `asserted.tsv`, every
- /// triple the run started from, and `derivations.tsv`, one line per
- /// inferred triple naming the rule that produced it and the premises the
- /// rule read. `lean/` holds a checker for that format whose soundness is a
+ /// The certificate is three tab-separated files: `asserted.tsv`, every
+ /// triple the run started from, `derivations.tsv`, one line per inferred
+ /// triple naming the rule that produced it and the premises the rule read,
+ /// and `scope.tsv`, which graphs those triples were read from. The Lean
+ /// checker reads the first two and cannot read the third: see
+ /// [`run_scoped`](Self::run_scoped). `lean/` holds a checker for that format whose soundness is a
/// machine-checked theorem (`OOCert.certificate_sound`): a certificate it
/// accepts contains only triples entailed by the asserted graph under the
/// RDF-based semantics of the vocabulary the rules use. The engine's own
@@ -1186,6 +1189,10 @@ impl Reasoner {
/// (tests/reason_rl_ext_soundness_test.rs).
///
/// Not available for `owl-dl`: the tableaux path has no rule trace.
+ ///
+ /// Reads the whole store. Over a store that uses the temporal vocabulary
+ /// that is now REFUSED rather than done silently — see
+ /// [`run_scoped`](Self::run_scoped), which this delegates to.
pub fn run_full(
graph: &Arc<GraphStore>,
profile: &str,
@@ -1193,7 +1200,14 @@ impl Reasoner {
target: InferenceTarget,
certificate_dir: Option<&std::path::Path>,
) -> anyhow::Result<String> {
- Self::run_capturing(graph, profile, materialize, target, certificate_dir, None)
+ Self::run_scoped(
+ graph,
+ profile,
+ materialize,
+ target,
+ certificate_dir,
+ &ScopeRequest::Unscoped,
+ )
}
/// The whole derivation DAG of a run: every asserted triple, every triple
@@ -1207,6 +1221,12 @@ impl Reasoner {
/// Refuses `owl-dl` for the same reason `--certificate` does: the tableaux
/// path has no rule trace, so there is no DAG to hand back and an empty one
/// would read as "nothing was derived".
+ ///
+ /// It asks for no scope, which is not the same as escaping the scope
+ /// gate: `ScopeRequest::Unscoped` still goes through
+ /// [`crate::temporal::resolve`], so over a versioned store naming no
+ /// instant this is REFUSED like any other run. A DAG over the union of
+ /// every version would explain a state that held at no instant.
pub fn derivation_graph(
graph: &Arc<GraphStore>,
profile: &str,
@@ -1218,12 +1238,13 @@ impl Reasoner {
);
}
let mut cap = Capture::default();
- Self::run_capturing(
+ Self::run_scoped_capturing(
graph,
profile,
false,
InferenceTarget::DefaultGraph,
None,
+ &ScopeRequest::Unscoped,
Some(&mut cap),
)?;
cap.out.ok_or_else(|| {
@@ -1231,12 +1252,110 @@ impl Reasoner {
})
}
- fn run_capturing(
+ /// [`run_full`](Self::run_full) over a stated set of graphs (#108).
+ ///
+ /// Every entry point above funnels here, so the scope gate cannot be
+ /// evaded by picking an older signature. What the gate does is in
+ /// [`crate::temporal::resolve`]; what it means for THIS path is:
+ ///
+ /// * A store with no temporal vocabulary is unaffected under every
+ /// request, and produces the same bytes it produced at 1.3.0.
+ /// * A bi-temporal store with no instant named is refused. Nothing else
+ /// in this engine would have caught that run: the reasoner would have
+ /// computed a correct closure over the union of every version, the
+ /// certificate would have been a true statement about the graph in
+ /// `asserted.tsv`, and the Lean checker would have accepted it. The
+ /// graph in `asserted.tsv` is the thing that would have been wrong, and
+ /// the checker cannot see that far.
+ /// * NO run over a versioned store MATERIALISES, and it says so rather
+ /// than dropping the flag. There is nowhere in such a store that a
+ /// conclusion can be written without becoming an axiom of every
+ /// snapshot: the default graph is in scope at every instant by being
+ /// timeless, and so is a named inference graph that carries no validity
+ /// description. That bites both ways round. A snapshot's conclusions
+ /// held at ONE instant and would be read at all of them; an
+ /// `all_versions` run's held at NONE, and writing those in is the leak
+ /// this issue is about arriving through the exit rather than the
+ /// entrance. The precedent is `rules_file`, refused for the same shape
+ /// of reason.
+ /// * The scope is recorded, in the report and, when a certificate is
+ /// written, in `scope.tsv` beside `asserted.tsv`.
+ pub fn run_scoped(
+ graph: &Arc<GraphStore>,
+ profile: &str,
+ materialize: bool,
+ target: InferenceTarget,
+ certificate_dir: Option<&std::path::Path>,
+ request: &ScopeRequest,
+ ) -> anyhow::Result<String> {
+ Self::run_scoped_capturing(
+ graph,
+ profile,
+ materialize,
+ target,
+ certificate_dir,
+ request,
+ None,
+ )
+ }
+
+ /// [`run_scoped`](Self::run_scoped) with somewhere to put the derivation
+ /// DAG. Private because `Capture` is, which is why the public form above
+ /// exists rather than this taking an `Option` nobody outside can build.
+ #[allow(clippy::too_many_arguments)]
+ fn run_scoped_capturing(
+ graph: &Arc<GraphStore>,
+ profile: &str,
+ materialize: bool,
+ target: InferenceTarget,
+ certificate_dir: Option<&std::path::Path>,
+ request: &ScopeRequest,
+ capture: Option<&mut Capture>,
+ ) -> anyhow::Result<String> {
+ let (scope, manifest) = crate::temporal::resolve(graph, request)?;
+ if !scope.is_all_graphs() && profile == "owl-dl" {
+ anyhow::bail!(
+ "the owl-dl tableaux path reads the whole store and has no scoped form yet \
+ (src/tableaux.rs reads GraphStore::all_triples), so a snapshot argument here \
+ would be accepted and ignored. Run rdfs, owl-rl or owl-rl-ext for a scoped run"
+ );
+ }
+ if manifest.store_has_versions() && materialize {
+ anyhow::bail!(
+ "a run over a versioned store does not materialise. There is nowhere in such a \
+ store that a conclusion can be written without becoming an axiom of every \
+ snapshot: the default graph is in scope at every instant because it is \
+ timeless, and so is an inference graph carrying no validity description. That \
+ bites both ways round. A SNAPSHOT's conclusions held at one instant and would \
+ be read at all of them; a run over EVERY VERSION at once (all_versions) draws \
+ its conclusions from a state that held at no instant, and writing those into \
+ the timeless graph is the leak of #108 arriving through the exit rather than \
+ the entrance. Run with materialize=false and read the inferences from the \
+ report, or describe a destination graph with temporal:validFrom / validTo \
+ yourself and load them into it"
+ );
+ }
+ Self::run_in_scope(
+ graph,
+ profile,
+ materialize,
+ target,
+ certificate_dir,
+ &scope,
+ &manifest,
+ capture,
+ )
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn run_in_scope(
graph: &Arc<GraphStore>,
profile: &str,
materialize: bool,
target: InferenceTarget,
certificate_dir: Option<&std::path::Path>,
+ scope: &crate::graph::ReadScope,
+ manifest: &crate::temporal::ScopeManifest,
capture: Option<&mut Capture>,
) -> anyhow::Result<String> {
// Delegate OWL-DL to tableaux reasoner
@@ -1255,7 +1374,18 @@ impl Reasoner {
run it with the default target, or use owl-rl / owl-rl-ext"
);
}
- return crate::tableaux::DlReasoner::run(graph, materialize);
+ // Only ever reached with the whole store, since `run_scoped`
+ // refuses a snapshot here. It still says so: "the scope key is on
+ // every report" is a sentence a reader has to be able to rely on,
+ // and a tool that omits it on one profile makes its absence
+ // ambiguous between "read everything" and "older build".
+ let raw = crate::tableaux::DlReasoner::run(graph, materialize)?;
+ let mut parsed: serde_json::Value = serde_json::from_str(&raw)?;
+ if parsed.is_object() {
+ parsed["scope"] = manifest.to_json();
+ return Ok(parsed.to_string());
+ }
+ return Ok(raw);
}
let profile_used = match profile {
@@ -1266,17 +1396,13 @@ impl Reasoner {
let include_owl = profile_used == "owl-rl" || profile_used == "owl-rl-ext";
let include_ext = profile_used == "owl-rl-ext";
- // Extract and intern the ASSERTED triples.
- //
- // Every graph except [`INFERRED_GRAPH`], which is where this same
- // function parks its own conclusions when the caller asks for them to
- // be kept apart. Reading them back would make run N's conclusions run
- // N+1's axioms, and `asserted.tsv` has no column that says "derived",
- // so the certificate would be conditional on a graph that was never
- // asserted. Until 15 September 2026 it did exactly that and the defect
- // was pinned by a test rather than fixed; TCB-8 in
- // `docs/trusted-computing-base.md` has the history.
- let (raw_triples, graphs_read) = graph.triples_outside(&[INFERRED_GRAPH])?;
+ // Extract and intern the triples of the graphs THIS RUN MAY READ. For
+ // `ReadScope::AllGraphs` that is `all_triples()` and the same bytes as
+ // before; for a snapshot it is the default graph plus the in-scope
+ // named graphs, and `asserted.tsv` below is written from exactly this
+ // list, so the certificate is about the graph the scope selected and
+ // `scope.tsv` says which one that was.
+ let (raw_triples, graphs_read) = graph.triples_in_scope(scope)?;
let mut interner = Interner::new();
let mut facts: Vec<(u32, u32, u32)> = Vec::with_capacity(raw_triples.len());
for (s, p, o) in &raw_triples {
@@ -2175,8 +2301,26 @@ impl Reasoner {
"fixpoint_reached": fixpoint_reached,
"initial_triples": initial_size,
"final_triples": triple_set.len(),
- "sample_inferences": sample
+ "sample_inferences": sample,
+ // Which graphs this closure was computed over. Present on every
+ // run, scoped or not: a number with no units is what an unlabelled
+ // verdict is, and the run where the scope first matters must not
+ // be the run where the key first appears.
+ "scope": manifest.to_json(),
});
+ if let Some(w) = &manifest.warning {
+ result["warning"] = serde_json::json!(w);
+ }
+ if manifest.graphs.as_ref().is_some_and(Vec::is_empty) {
+ // The default graph alone: the schema, and whatever else sits
+ // outside a named graph. A closure over that is a real answer to a
+ // question about the TBox and is NOT an answer about the data,
+ // and an `inferred_count` with nothing saying so reads as one.
+ result["warning"] = serde_json::json!(
+ "no graphs in scope at that instant: this closure was computed over the default \
+ graph alone, so it says nothing about the assertions. See scope."
+ );
+ }
if !materialize {
result["dry_run"] = serde_json::json!(true);
}
@@ -2250,6 +2394,16 @@ impl Reasoner {
// is no such file.
let _ = std::fs::remove_file(dir.join("refutation.tsv"));
+ // The scope, beside the files it selected. `asserted.tsv` is a
+ // list of triples with nothing in it that says where they came
+ // from, and the Lean checker has no way to ask: it verifies that
+ // the derivations follow from the triples in front of it, which
+ // stays true whatever scope chose them. A certificate over a
+ // snapshot and a certificate over the union of every version are
+ // indistinguishable as files, and only one of them is about a
+ // state that existed. This file is what tells them apart.
+ std::fs::write(dir.join("scope.tsv"), manifest.to_tsv())?;
+
result["certificate"] = serde_json::json!({
"dir": dir.display().to_string(),
"format": "oo-cert/1",
@@ -2262,6 +2416,13 @@ impl Reasoner {
"graphs_read": graphs_read,
"graphs_excluded": [INFERRED_GRAPH],
"check_with": "cd lean && lake exe oo-cert <dir>/asserted.tsv <dir>/derivations.tsv",
+ "scope": manifest.to_json(),
+ "scope_file": dir.join("scope.tsv").display().to_string(),
+ "scope_means": "oo-cert verifies that every derivation follows from the triples \
+ in asserted.tsv. It does not and cannot check that asserted.tsv \
+ is the graph you meant to reason over. scope.tsv records which \
+ graphs were read; a reader who cares whether this answer is \
+ about a state that existed has to read it.",
});
}
@@ -2912,11 +3073,28 @@ impl Reasoner {
/// table holds only in models that satisfy that table, and writing it in
/// beside the assertions would lose exactly the distinction decision 0003
/// is about.
+ ///
+ /// Reads the whole store; refused over a bi-temporal store with no instant
+ /// named, exactly as [`run_full`](Self::run_full) is. A certificate over a
+ /// user's own rule table has the same blind spot as one over the built-in
+ /// table and for the same reason: `oo-horn` verifies the steps against the
+ /// triples in `asserted.tsv` and cannot ask where they came from.
pub fn run_horn(
graph: &Arc<GraphStore>,
rules_path: &std::path::Path,
certificate_dir: &std::path::Path,
) -> anyhow::Result<String> {
+ Self::run_horn_scoped(graph, rules_path, certificate_dir, &ScopeRequest::Unscoped)
+ }
+
+ /// [`run_horn`](Self::run_horn) over a stated set of graphs (#108).
+ pub fn run_horn_scoped(
+ graph: &Arc<GraphStore>,
+ rules_path: &std::path::Path,
+ certificate_dir: &std::path::Path,
+ request: &ScopeRequest,
+ ) -> anyhow::Result<String> {
+ let (scope, manifest) = crate::temporal::resolve(graph, request)?;
let rules_text = std::fs::read_to_string(rules_path)
.map_err(|e| anyhow::anyhow!("cannot read rule table {}: {e}", rules_path.display()))?;
let rules = parse_rules(&rules_text)
@@ -2929,10 +3107,7 @@ impl Reasoner {
);
}
- // The asserted triples, every graph except the one the built-in path
- // parks its own conclusions in. See TCB-8; this path materialises
- // nothing itself (decision 0003) but it reads the same store.
- let (raw_triples, graphs_read) = graph.triples_outside(&[INFERRED_GRAPH])?;
+ let (raw_triples, graphs_read) = graph.triples_in_scope(&scope)?;
let mut interner = Interner::new();
let mut facts: Vec<Fact> = Vec::with_capacity(raw_triples.len());
for (s, p, o) in &raw_triples {
@@ -3207,8 +3382,18 @@ impl Reasoner {
"lean/, through `oo-horn check`, which decides what this run earned by \
comparing the table against the built-in one. This engine emits the \
certificate and states no verdict of its own",
- }
+ "scope": manifest.to_json(),
+ "scope_file": certificate_dir.join("scope.tsv").display().to_string(),
+ "scope_means": "oo-horn verifies the steps against the triples in asserted.tsv. \
+ It does not and cannot check that asserted.tsv is the graph you \
+ meant. scope.tsv records which graphs were read.",
+ },
+ "scope": manifest.to_json(),
});
+ std::fs::write(certificate_dir.join("scope.tsv"), manifest.to_tsv())?;
+ if let Some(w) = &manifest.warning {
+ result["warning"] = serde_json::json!(w);
+ }
if !fixpoint {
// An iteration cap reached with work still to do is not a fixpoint,
// and a count from such a run is a lower bound. Say it in the
diff --git a/src/reason_incremental.rs b/src/reason_incremental.rs
index 9e626116..47a2f5ed 100644
--- a/src/reason_incremental.rs
+++ b/src/reason_incremental.rs
@@ -237,6 +237,56 @@ impl IncrementalReasoner {
/// Derive and materialise the consequences of `delta` against the closure
/// already in the store, without reading the store into memory.
pub fn run(graph: &Arc<GraphStore>, delta: &[Triple], materialize: bool) -> anyhow::Result<String> {
+ Self::run_scoped(graph, delta, materialize, false)
+ }
+
+ /// As [`run`](Self::run), with the #108 scope gate.
+ ///
+ /// This path reads the store through `sparql_select_union`, so it has the
+ /// SHACL-side selection rather than the reasoner's, and it materialises
+ /// into the default graph. Over a bi-temporal store that is the same
+ /// defect `onto_reason` was gated for, arriving through a second door, and
+ /// leaving it open would have made the gate on `onto_reason` a suggestion.
+ ///
+ /// There is no snapshot form here. Aligning the incremental reader with
+ /// the full one is #108's own "not this issue", and a tool that accepted
+ /// `valid_at` and ignored it would be worse than one that has no such
+ /// argument. So the gate is binary: over a store that uses the temporal
+ /// vocabulary, this refuses unless `all_versions` says the union of every
+ /// version is what the caller meant, and the message points at
+ /// `onto_reason` for the snapshot.
+ pub fn run_scoped(
+ graph: &Arc<GraphStore>,
+ delta: &[Triple],
+ materialize: bool,
+ all_versions: bool,
+ ) -> anyhow::Result<String> {
+ let request = if all_versions {
+ crate::temporal::ScopeRequest::AllVersions
+ } else {
+ crate::temporal::ScopeRequest::Unscoped
+ };
+ let resolved = crate::temporal::resolve(graph, &request);
+ if let Ok((_, manifest)) = &resolved
+ && manifest.store_has_versions()
+ && materialize
+ {
+ anyhow::bail!(
+ "a run over a versioned store does not materialise. This path writes its \
+ conclusions into the DEFAULT graph, which is timeless and therefore in scope at \
+ every instant, so a closure drawn from every version at once would become an \
+ axiom of every snapshot. Run with materialize=false"
+ );
+ }
+ if let Err(e) = resolved {
+ anyhow::bail!(
+ "{e}\n\nNote for this tool: incremental reasoning has no snapshot form. It reads \
+ the union of every graph and materialises into the default graph, so over a \
+ versioned store it computes the closure of a state that held at no instant and \
+ writes it in beside the assertions. Run onto_reason with valid_at / as_of for a \
+ snapshot, or pass all_versions=true here to say the union is what you meant"
+ );
+ }
if let Err(reason) = Self::applies_to(delta) {
return Ok(serde_json::json!({
"ok": false,
diff --git a/src/server.rs b/src/server.rs
index 6df9b60d..718deee2 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -1087,14 +1087,19 @@ impl OpenOntologiesServer {
}
}
- #[tool(name = "onto_reason_incremental", description = "Derive the consequences of newly added triples WITHOUT recomputing the whole closure. Pass the added triples as N-Triples in `delta`; the engine joins them against the existing closure (semi-naive evaluation), so the work is proportional to what changed rather than to the size of the store. Use after adding facts to an already-materialised graph. Adding SCHEMA axioms (subClassOf, domain, range, inverseOf, equivalentClass) changes what the whole store entails and is refused with an explanation: run onto_reason for those.")]
+ #[tool(name = "onto_reason_incremental", description = "Derive the consequences of newly added triples WITHOUT recomputing the whole closure. Pass the added triples as N-Triples in `delta`; the engine joins them against the existing closure (semi-naive evaluation), so the work is proportional to what changed rather than to the size of the store. Use after adding facts to an already-materialised graph. Adding SCHEMA axioms (subClassOf, domain, range, inverseOf, equivalentClass) changes what the whole store entails and is refused with an explanation: run onto_reason for those. This path has NO snapshot form: it reads the union of every graph and materialises into the default graph, so over a store that describes its named graphs with the temporal vocabulary (https://open-ontologies.org/temporal#) it is REFUSED unless `all_versions: true` says the union of every version is what you meant. Use onto_reason with valid_at / as_of for a snapshot.")]
async fn onto_reason_incremental(&self, Parameters(input): Parameters<OntoReasonIncrementalInput>) -> String {
use crate::reason_incremental::{parse_ntriples, IncrementalReasoner};
let delta = parse_ntriples(&input.delta);
if delta.is_empty() {
return r#"{"error":"delta parsed to no triples: expected N-Triples"}"#.to_string();
}
- match IncrementalReasoner::run(&self.graph, &delta, input.materialize.unwrap_or(true)) {
+ match IncrementalReasoner::run_scoped(
+ &self.graph,
+ &delta,
+ input.materialize.unwrap_or(true),
+ input.all_versions.unwrap_or(false),
+ ) {
Ok(json) => json,
Err(e) => Self::err_json(e),
}
@@ -1242,7 +1247,7 @@ impl OpenOntologiesServer {
result.to_string()
}
- #[tool(name = "onto_shacl", description = "Validate the loaded ontology data against SHACL shapes. Checks the core constraint components written under `sh:property`, including `sh:minCount`, `sh:maxCount`, `sh:datatype`, `sh:class`, `sh:nodeKind`, `sh:pattern`, `sh:in`, `sh:hasValue`, `sh:or` and `sh:not`, plus `sh:sparql`. A constraint it cannot execute is listed in `skipped_constraints` and the verdict is null rather than true. Returns a conformance report with violations, `focus_nodes` and `unmatched_shapes`.")]
+ #[tool(name = "onto_shacl", description = "Validate the loaded ontology data against SHACL shapes. Checks the core constraint components written under `sh:property`, including `sh:minCount`, `sh:maxCount`, `sh:datatype`, `sh:class`, `sh:nodeKind`, `sh:pattern`, `sh:in`, `sh:hasValue`, `sh:or` and `sh:not`, plus `sh:sparql`. A constraint it cannot execute is listed in `skipped_constraints` and the verdict is null rather than true. Returns a conformance report with violations, `focus_nodes` and `unmatched_shapes`, plus `scope`, which names the graphs the run READ. By default every graph in the store is read. Over a store that describes its named graphs with the temporal vocabulary (https://open-ontologies.org/temporal#) that union is a state that held at no instant, so a run with no instant named is REFUSED rather than answered: pass `valid_at` (what was TRUE then), `as_of` (what was KNOWN then) or `all_versions: true` to say the union is what you meant. A scoped run evaluates every data-side query, `sh:sparql` included, against the in-scope named graphs plus the default graph and nothing else. A snapshot that selects no graph returns `conforms: null` with its own reason rather than conforming vacuously. Class and property DECLARATION lookups are never scoped: a declaration is context-free and has the same answer at every instant.")]
async fn onto_shacl(&self, Parameters(input): Parameters<OntoShaclInput>) -> String {
use crate::shacl::ShaclValidator;
let shapes = if input.inline.unwrap_or(false) {
@@ -1253,7 +1258,15 @@ impl OpenOntologiesServer {
Err(e) => return Self::err_json(format!("Cannot read shapes file: {}", e)),
}
};
- ShaclValidator::validate(&self.graph, &shapes)
+ let request = match crate::temporal::ScopeRequest::from_args(
+ input.valid_at.as_deref(),
+ input.as_of.as_deref(),
+ input.all_versions.unwrap_or(false),
+ ) {
+ Ok(r) => r,
+ Err(e) => return Self::err_json(e),
+ };
+ ShaclValidator::validate_scoped(&self.graph, &shapes, &request)
.unwrap_or_else(Self::err_json)
}
@@ -2039,9 +2052,21 @@ impl OpenOntologiesServer {
body.to_string()
}
- #[tool(name = "onto_reason", description = "Run inference over the loaded ontology. Profiles: 'rdfs' (subclass, domain/range), 'owl-rl' (+ transitive/symmetric/inverse, sameAs, equivalentClass), 'owl-rl-ext' (+ someValuesFrom, allValuesFrom, hasValue, intersectionOf, unionOf), 'owl-dl' (SHIQ tableaux: satisfiability, classification, qualified number restrictions with node merging, inverse/symmetric roles, functional properties, parallel agent-based classification, explanation traces, ABox reasoning. Nominals are not implemented: owl:oneOf is not read and owl:hasValue is approximated as an atomic concept, so an ontology that uses either returns undetermined classes rather than a classification. Datatype ranges are skipped). Materializes inferred triples. Set `inference_graph` to keep them in a separate graph, where nothing downstream can read an inference as an assertion and a Turtle/RDF-XML save cannot publish one. Pass `rules_file` to evaluate a SUPPLIED Horn rule table instead of a built-in profile: it needs `certificate_dir`, materialises nothing, and writes a certificate the proved-sound Lean checker verifies with `lake exe oo-horn check`. The verdict comes from that checker and not from here, because rules you supply are assumed and never checked: a conclusion then holds in every model of the asserted graph that ALSO satisfies your rules. With `certificate_dir` the run ALSO looks for a contradiction in the closure it reached, and writes refutation.tsv when it finds one the Lean refutation checker can judge: `lake exe oo-refute check`, or `oo-refute guard` which refuses the derivation certificate over a graph it can refute. Seventeen OWL 2 RL rules conclude false, ten are detected here and exactly ONE, cax-dw, is certifiable, because OOCert.RefuteConditions carries a semantic condition for that rule alone. The other nine are reported as `clash_found_by_this_engine` with no file written, and that word is not the checker's `unsatisfiable_under_disjointness`: an engine opinion and a machine-checked result never share a string here. cax-dw needs an INDIVIDUAL in two disjoint classes, so a TBox unsatisfiable with no individual asserted is invisible to this route; profile 'owl-dl' sees that case and its answer carries no certificate. No clash found is never a consistency result.")]
+ #[tool(name = "onto_reason", description = "Run inference over the loaded ontology. Profiles: 'rdfs' (subclass, domain/range), 'owl-rl' (+ transitive/symmetric/inverse, sameAs, equivalentClass), 'owl-rl-ext' (+ someValuesFrom, allValuesFrom, hasValue, intersectionOf, unionOf), 'owl-dl' (SHIQ tableaux: satisfiability, classification, qualified number restrictions with node merging, inverse/symmetric roles, functional properties, parallel agent-based classification, explanation traces, ABox reasoning. Nominals are not implemented: owl:oneOf is not read and owl:hasValue is approximated as an atomic concept, so an ontology that uses either returns undetermined classes rather than a classification. Datatype ranges are skipped). Materializes inferred triples. Set `inference_graph` to keep them in a separate graph, where nothing downstream can read an inference as an assertion and a Turtle/RDF-XML save cannot publish one. Pass `rules_file` to evaluate a SUPPLIED Horn rule table instead of a built-in profile: it needs `certificate_dir`, materialises nothing, and writes a certificate the proved-sound Lean checker verifies with `lake exe oo-horn check`. The verdict comes from that checker and not from here, because rules you supply are assumed and never checked: a conclusion then holds in every model of the asserted graph that ALSO satisfies your rules. With `certificate_dir` the run ALSO looks for a contradiction in the closure it reached, and writes refutation.tsv when it finds one the Lean refutation checker can judge: `lake exe oo-refute check`, or `oo-refute guard` which refuses the derivation certificate over a graph it can refute. Seventeen OWL 2 RL rules conclude false, ten are detected here and exactly ONE, cax-dw, is certifiable, because OOCert.RefuteConditions carries a semantic condition for that rule alone. The other nine are reported as `clash_found_by_this_engine` with no file written, and that word is not the checker's `unsatisfiable_under_disjointness`: an engine opinion and a machine-checked result never share a string here. cax-dw needs an INDIVIDUAL in two disjoint classes, so a TBox unsatisfiable with no individual asserted is invisible to this route; profile 'owl-dl' sees that case and its answer carries no certificate. No clash found is never a consistency result. Every report carries `scope`, the graphs the run READ, and a certificate directory also gets `scope.tsv`: the Lean checkers verify the steps against the triples in asserted.tsv and cannot ask where those triples came from, so a certificate over one snapshot and a certificate over the union of every version are indistinguishable as files and only one is about a state that existed. Over a store that describes its named graphs with the temporal vocabulary (https://open-ontologies.org/temporal#), a run with no instant named is REFUSED: pass `valid_at`, `as_of` or `all_versions: true`. NO run over a versioned store materialises and it says so, whether scoped or `all_versions`: the default graph and an undescribed inference graph are both in scope at every instant, so a conclusion written to either becomes an axiom of every snapshot, and an `all_versions` closure was drawn from a state that held at no instant. Pass `materialize: false`. A scoped run also drops any graph holding this engine's own materialised inferences from what it reads, and records the drop. Scoped runs are not available for 'owl-dl'.")]
async fn onto_reason(&self, Parameters(input): Parameters<OntoReasonInput>) -> String {
use crate::reason::Reasoner;
+ // Resolved before anything else: which graphs a run reads decides what
+ // its answer is about, so a request that cannot be honoured is refused
+ // rather than carried into a run that then reports a scope it did not
+ // have.
+ let request = match crate::temporal::ScopeRequest::from_args(
+ input.valid_at.as_deref(),
+ input.as_of.as_deref(),
+ input.all_versions.unwrap_or(false),
+ ) {
+ Ok(r) => r,
+ Err(e) => return Self::err_json(e),
+ };
// A supplied Horn rule table takes a different path: it is evaluated
// instead of a built-in profile, it materialises nothing, and the
// response carries no verdict, because a rule the caller wrote is an
@@ -2066,10 +2091,11 @@ impl OpenOntologiesServer {
})
.to_string();
}
- return Reasoner::run_horn(
+ return Reasoner::run_horn_scoped(
&self.graph,
std::path::Path::new(rules_file),
std::path::Path::new(dir),
+ &request,
)
.unwrap_or_else(Self::err_json);
}
@@ -2081,7 +2107,7 @@ impl OpenOntologiesServer {
crate::reason::InferenceTarget::DefaultGraph
};
let dir = input.certificate_dir.as_deref().map(std::path::Path::new);
- Reasoner::run_full(&self.graph, profile, materialize, target, dir)
+ Reasoner::run_scoped(&self.graph, profile, materialize, target, dir, &request)
.unwrap_or_else(Self::err_json)
}
@@ -2458,7 +2484,7 @@ impl OpenOntologiesServer {
}).to_string()
}
- #[tool(name = "onto_extend", description = "Convenience pipeline: ingest data → validate with SHACL → run OWL reasoning, all in one call. Combines onto_ingest + onto_shacl + onto_reason.")]
+ #[tool(name = "onto_extend", description = "Convenience pipeline: ingest data → validate with SHACL → run OWL reasoning, all in one call. Combines onto_ingest + onto_shacl + onto_reason. It takes no temporal scope arguments and inherits the refusal from the two tools it chains: over a store that describes its named graphs with the temporal vocabulary (https://open-ontologies.org/temporal#), this returns the error rather than a pipeline report, and the snapshot has to be run through onto_shacl and onto_reason directly with valid_at / as_of.")]
async fn onto_extend(&self, Parameters(input): Parameters<OntoExtendInput>) -> String {
use crate::ingest::DataIngester;
use crate::mapping::MappingConfig;
diff --git a/src/shacl.rs b/src/shacl.rs
index e67b91b5..8951e75c 100644
--- a/src/shacl.rs
+++ b/src/shacl.rs
@@ -1,4 +1,5 @@
-use crate::graph::GraphStore;
+use crate::graph::{GraphStore, ReadScope};
+use crate::temporal::{ScopeManifest, ScopeRequest};
use oxigraph::io::{RdfFormat, RdfParser};
use oxigraph::model::{Term, Variable};
use oxigraph::sparql::{QueryResults, SparqlEvaluator};
@@ -48,7 +49,50 @@ impl ShaclValidator {
/// can be read back as the findings table it is (#131). The keys that
/// predate those (`constraint`, `focus_node`, `message`, `severity`,
/// `path`) are unchanged.
+ ///
+ /// Reads the whole store. Over a store that uses the temporal vocabulary
+ /// that is now REFUSED rather than done silently — see
+ /// [`validate_scoped`](Self::validate_scoped), which this delegates to.
pub fn validate(graph: &Arc<GraphStore>, shapes_ttl: &str) -> anyhow::Result<String> {
+ Self::validate_scoped(graph, shapes_ttl, &ScopeRequest::Unscoped)
+ }
+
+ /// [`validate`](Self::validate) over a stated set of graphs (#108).
+ ///
+ /// Every data-side query of the run is evaluated against exactly the
+ /// graphs the scope names. Before this, the union of every graph was the
+ /// only dataset available and no argument could change it, so a store
+ /// holding one entity's versions in one named graph each was validated
+ /// against the union of its versions: a `sh:maxCount 1` saw one value per
+ /// version at once and reported a violation that was wrong at every
+ /// instant.
+ ///
+ /// The scope reaches `sh:sparql` too. A constraint someone wrote can
+ /// contain a `GRAPH` block, so restricting the default graph alone would
+ /// leave an escape open; the dataset's available named graphs are
+ /// restricted to the same set, which is the same reason
+ /// `Temporal::query_at` wraps a caller's pattern in `FROM NAMED`.
+ ///
+ /// What is NOT scoped: `class_exists` and `property_exists`, which
+ /// `check_shapes` uses to decide whether a shape references something that
+ /// exists. A declaration is context-free and has the same answer at every
+ /// instant, so narrowing it would report a live shape as referencing a
+ /// missing class whenever the version that declared it fell out of scope.
+ pub fn validate_scoped(
+ graph: &Arc<GraphStore>,
+ shapes_ttl: &str,
+ request: &ScopeRequest,
+ ) -> anyhow::Result<String> {
+ let (scope, manifest) = crate::temporal::resolve(graph, request)?;
+ Self::validate_in_scope(graph, shapes_ttl, &scope, &manifest)
+ }
+
+ fn validate_in_scope(
+ graph: &Arc<GraphStore>,
+ shapes_ttl: &str,
+ scope: &ReadScope,
+ manifest: &ScopeManifest,
+ ) -> anyhow::Result<String> {
// 1. Parse shapes Turtle into a temporary store
let shapes_store = Store::new()?;
let reader = Cursor::new(shapes_ttl.as_bytes());
@@ -290,7 +334,7 @@ impl ShaclValidator {
// constraints against the empty set and contributes no violations,
// which is indistinguishable in the report from a shape that checked
// its nodes and found them sound.
- let focus_count = count_focus_nodes(graph, &focus_pattern)?;
+ let focus_count = count_focus_nodes(graph, scope, &focus_pattern)?;
focus_nodes_total += focus_count;
if focus_count == 0 {
let mut entry = serde_json::json!({
@@ -745,7 +789,7 @@ impl ShaclValidator {
FILTER(!({disjunction}))
}}"#
);
- for row in &graph_sparql_select(graph, &query)? {
+ for row in &graph_sparql_select(graph, scope, &query)? {
if let Some(focus) = row.get("focus") {
let msg = if node_message.is_empty() {
"Node conforms to none of the sh:or member shapes".to_string()
@@ -857,7 +901,7 @@ impl ShaclValidator {
OPTIONAL {{ ?focus <{q_path}> ?val . FILTER({clause}) }}
}} GROUP BY ?focus"#
);
- for result in &graph_sparql_select(graph, &query)? {
+ for result in &graph_sparql_select(graph, scope, &query)? {
let (Some(focus), Some(n_raw)) = (result.get("focus"), result.get("n")) else {
continue;
};
@@ -982,7 +1026,7 @@ impl ShaclValidator {
OPTIONAL {{ ?focus {path_expr} ?val }}
}} GROUP BY ?focus HAVING (COUNT(DISTINCT ?val) < {min_count})"#
);
- let results = graph_sparql_select(graph, &query)?;
+ let results = graph_sparql_select(graph, scope, &query)?;
for row in &results {
if let Some(focus) = row.get("focus") {
let msg = if message.is_empty() {
@@ -1016,7 +1060,7 @@ impl ShaclValidator {
?focus {path_expr} ?val .
}} GROUP BY ?focus HAVING (COUNT(DISTINCT ?val) > {max_count})"#
);
- let results = graph_sparql_select(graph, &query)?;
+ let results = graph_sparql_select(graph, scope, &query)?;
for row in &results {
if let Some(focus) = row.get("focus") {
let msg = if message.is_empty() {
@@ -1054,7 +1098,7 @@ impl ShaclValidator {
}}
}}"#
);
- let results = graph_sparql_select(graph, &query)?;
+ let results = graph_sparql_select(graph, scope, &query)?;
for row in &results {
if let Some(focus) = row.get("focus") {
let msg = if message.is_empty() {
@@ -1100,7 +1144,7 @@ impl ShaclValidator {
FILTER(DATATYPE(?val) != <{dt}>)
}}"#
);
- let results = graph_sparql_select(graph, &query)?;
+ let results = graph_sparql_select(graph, scope, &query)?;
for row in &results {
if let Some(focus) = row.get("focus") {
let msg = if message.is_empty() {
@@ -1135,7 +1179,7 @@ impl ShaclValidator {
FILTER(!REGEX(STR(?val), "{escaped}"))
}}"#
);
- let results = graph_sparql_select(graph, &query)?;
+ let results = graph_sparql_select(graph, scope, &query)?;
for row in &results {
if let Some(focus) = row.get("focus") {
let msg = if message.is_empty() {
@@ -1177,7 +1221,7 @@ impl ShaclValidator {
FILTER(!({disjunction}))
}}"#
);
- let results = graph_sparql_select(graph, &query)?;
+ let results = graph_sparql_select(graph, scope, &query)?;
for row in &results {
if let Some(focus) = row.get("focus") {
let msg = if message.is_empty() {
@@ -1224,7 +1268,7 @@ impl ShaclValidator {
FILTER(isBlank(?val) || STRLEN(STR(?val)) {cmp} {bound})
}}"#
);
- for row in &graph_sparql_select(graph, &query)? {
+ for row in &graph_sparql_select(graph, scope, &query)? {
if let Some(focus) = row.get("focus") {
let msg = if message.is_empty() {
format!("Value is {wording} {bound} characters")
@@ -1267,7 +1311,7 @@ impl ShaclValidator {
FILTER(!(?val {ok_cmp} ?otherVal))
}}"#
);
- for row in &graph_sparql_select(graph, &query)? {
+ for row in &graph_sparql_select(graph, scope, &query)? {
if let Some(focus) = row.get("focus") {
let msg = if message.is_empty() {
format!("Value is not {ok_cmp} the value of <{other}>")
@@ -1300,7 +1344,7 @@ impl ShaclValidator {
FILTER(!({expr}))
}}"#
);
- for row in &graph_sparql_select(graph, &query)? {
+ for row in &graph_sparql_select(graph, scope, &query)? {
if let Some(focus) = row.get("focus") {
let msg = if message.is_empty() {
format!(
@@ -1344,7 +1388,7 @@ impl ShaclValidator {
FILTER({conjunction})
}}"#
);
- let results = graph_sparql_select(graph, &query)?;
+ let results = graph_sparql_select(graph, scope, &query)?;
for row in &results {
if let Some(focus) = row.get("focus") {
let msg = if message.is_empty() {
@@ -1375,7 +1419,7 @@ impl ShaclValidator {
FILTER(?val NOT IN ({list}))
}}"#
);
- let results = graph_sparql_select(graph, &query)?;
+ let results = graph_sparql_select(graph, scope, &query)?;
for row in &results {
if let Some(focus) = row.get("focus") {
let msg = if message.is_empty() {
@@ -1420,7 +1464,7 @@ impl ShaclValidator {
FILTER(!{t})
}}"#
);
- let results = graph_sparql_select(graph, &query)?;
+ let results = graph_sparql_select(graph, scope, &query)?;
for row in &results {
if let Some(focus) = row.get("focus") {
let msg = if message.is_empty() {
@@ -1459,7 +1503,7 @@ impl ShaclValidator {
FILTER NOT EXISTS {{ ?focus {path_expr} {term} }}
}}"#
);
- let results = graph_sparql_select(graph, &query)?;
+ let results = graph_sparql_select(graph, scope, &query)?;
for row in &results {
if let Some(focus) = row.get("focus") {
let msg = if message.is_empty() {
@@ -1503,7 +1547,7 @@ impl ShaclValidator {
FILTER(!COALESCE(?val {satisfy_op} {bound}, false))
}}"#
);
- let results = graph_sparql_select(graph, &query)?;
+ let results = graph_sparql_select(graph, scope, &query)?;
for row in &results {
if let Some(focus) = row.get("focus") {
let msg = if message.is_empty() {
@@ -1608,6 +1652,7 @@ impl ShaclValidator {
// be named in a VALUES clause; there is no VALUES clause any more.
let focus_rows = graph_sparql_select(
graph,
+ scope,
&format!("SELECT ?this WHERE {{ {this_pattern} }}"),
)?;
let mut focus_terms: Vec<Term> = Vec::new();
@@ -1707,7 +1752,7 @@ impl ShaclValidator {
}));
continue;
}
- match graph.sparql_select_union_prebound(&query, "this", &focus_terms) {
+ match graph.sparql_select_scoped_prebound(&query, "this", &focus_terms, scope) {
Ok(per_focus) => {
for (focus, rows) in focus_terms.iter().zip(per_focus) {
let focus_str = focus.to_string();
@@ -1811,14 +1856,31 @@ impl ShaclValidator {
"focus_nodes": focus_nodes_total,
"unmatched_shapes": unmatched,
// A verdict that does not say what it selected over cannot be
- // replayed or compared against the next one, and this value is
- // about to stop being the only one: temporal scoping arrives as
- // an argument, and the moment two runs of the same shapes over
- // the same store can differ, an unlabelled report is a number
- // without units. Naming it now means the key does not appear for
- // the first time on the run where it matters.
- "scope": "all_graphs",
+ // replayed or compared against the next one. This used to be the
+ // bare string `all_graphs`, placed before temporal scoping arrived
+ // so the key would not appear for the first time on the run where
+ // it mattered. It now carries the manifest, and the run it
+ // mattered on is here: two runs of the same shapes over the same
+ // store CAN differ, and the report says which graphs each read.
+ "scope": manifest.to_json(),
});
+ if manifest.graphs.as_ref().is_some_and(Vec::is_empty) {
+ // A snapshot that selected no graph at all. Reporting `conforms:
+ // true` here would be the same class of non-answer as a shapes
+ // graph that targeted absent classes, and it reuses the same
+ // three-valued verdict with its own reason: the data was not
+ // examined and found clean, there was no data in scope to examine.
+ report["conforms"] = serde_json::Value::Null;
+ report["warning"] = serde_json::Value::String(
+ "no graphs in scope at that instant, so nothing was validated and conformance is \
+ undetermined. See scope."
+ .to_string(),
+ );
+ if !skipped.is_empty() {
+ report["skipped_constraints"] = serde_json::Value::Array(skipped);
+ }
+ return Ok(report.to_string());
+ }
if nothing_matched && skipped.is_empty() {
// Every shape targeted a class with no instances in the data, so
// nothing was checked. Reporting `conforms: true` here would be the
@@ -1840,6 +1902,15 @@ impl ShaclValidator {
));
report["skipped_constraints"] = serde_json::Value::Array(skipped);
}
+ // A scope that was cut short is a WRONG set of graphs, not a short
+ // one, so it overrides whatever verdict the branches above reached
+ // rather than sitting quietly inside `scope`.
+ if let Some(w) = &manifest.warning {
+ report["warning"] = serde_json::Value::String(match report["warning"].as_str() {
+ Some(existing) => format!("{w} {existing}"),
+ None => w.clone(),
+ });
+ }
Ok(report.to_string())
}
@@ -2123,28 +2194,35 @@ fn query_solutions(
/// Run a SPARQL SELECT ?shape against the main `GraphStore` and return results
/// as a vec of maps, using the existing `sparql_select` JSON output.
///
-/// Every data-side query in this module runs over the union of every graph in
-/// the store. It used to run over the store's default graph alone, which made
-/// the verdict depend on the serialisation the data arrived in: an ontology
-/// and its instances loaded from Turtle validated, and the identical triples
-/// loaded from TriG selected no focus nodes at all and came back as
+/// Every data-side query in this module runs over the scope the run was given.
+/// It used to run over the store's default graph alone, which made the verdict
+/// depend on the serialisation the data arrived in: an ontology and its
+/// instances loaded from Turtle validated, and the identical triples loaded
+/// from TriG selected no focus nodes at all and came back as
/// `nothing_matched` with a null verdict. That is the right answer to a
/// question nobody asked, and it is why the defect never arrived as a bug
/// report.
///
-/// Reading every graph is the only default that cannot silently drop data.
-/// The alternative, selecting instances from the graphs in temporal scope, is
-/// the opposite direction: it can only remove focus nodes, so it can turn a
-/// `conforms: false` into a `true` by dropping the data that failed. That
-/// belongs behind an argument someone passes on purpose, never behind the
-/// no-argument path. See the graph-scope rule on issue #108: a declaration is
-/// read from every graph because a declaration is context-free, and instance
-/// data is scoped because it is not.
+/// Reading every graph is the only DEFAULT that cannot silently drop data, and
+/// it is still the default. Narrowing to a temporal snapshot runs the opposite
+/// risk — it can only remove focus nodes, so it can turn a `conforms: false`
+/// into a `true` by dropping the data that failed — which is why it sits
+/// behind an argument someone passes on purpose and never behind the
+/// no-argument path. That argument has now landed (#108), and with it the
+/// third case the other two left out: over a store that HAS versions, the
+/// no-argument path is refused rather than answered, because reading every
+/// version at once is not a safe default either, it is a verdict about a state
+/// that held at no instant.
+///
+/// The graph-scope rule from #108 holds throughout: a declaration is read from
+/// every graph because a declaration is context-free (`class_exists`,
+/// `property_exists`), and instance data is scoped because it is not.
fn graph_sparql_select(
graph: &Arc<GraphStore>,
+ scope: &ReadScope,
query: &str,
) -> anyhow::Result<Vec<HashMap<String, String>>> {
- let json_str = graph.sparql_select_union(query)?;
+ let json_str = graph.sparql_select_scoped(query, scope)?;
let parsed: serde_json::Value = serde_json::from_str(&json_str)?;
let mut rows = Vec::new();
if let Some(results) = parsed["results"].as_array() {
@@ -2174,6 +2252,11 @@ fn graph_sparql_select(
/// default graph and every named graph, unconditionally: there is no scope
/// argument and no flag that narrows it back to the default graph.
fn class_exists(graph: &Arc<GraphStore>, iri: &str) -> anyhow::Result<bool> {
+ // No scope argument, deliberately, and #108 did not add one: a class
+ // declaration is context-free, so "is this IRI declared" has the same
+ // answer at every instant, and narrowing it to a snapshot would report a
+ // shape as referencing a missing class because the version that declared
+ // it is out of scope.
let query = format!(
r#"SELECT ?x WHERE {{
{{ <{iri}> a ?type }}
@@ -2183,7 +2266,7 @@ fn class_exists(graph: &Arc<GraphStore>, iri: &str) -> anyhow::Result<bool> {
|| ?type = <http://www.w3.org/2000/01/rdf-schema#Class>)
}} LIMIT 1"#
);
- let results = graph_sparql_select(graph, &query)?;
+ let results = graph_sparql_select(graph, &ReadScope::AllGraphs, &query)?;
Ok(!results.is_empty())
}
@@ -2194,6 +2277,7 @@ fn class_exists(graph: &Arc<GraphStore>, iri: &str) -> anyhow::Result<bool> {
/// named graph, unconditionally, so a property declared inside a `GRAPH`
/// block is not reported as `missing_path`.
fn property_exists(graph: &Arc<GraphStore>, iri: &str) -> anyhow::Result<bool> {
+ // Whole store, for the reason given on `class_exists`.
let query = format!(
r#"SELECT ?x WHERE {{
{{ <{iri}> a ?type }}
@@ -2204,7 +2288,7 @@ fn property_exists(graph: &Arc<GraphStore>, iri: &str) -> anyhow::Result<bool> {
|| ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property>)
}} LIMIT 1"#
);
- let results = graph_sparql_select(graph, &query)?;
+ let results = graph_sparql_select(graph, &ReadScope::AllGraphs, &query)?;
Ok(!results.is_empty())
}
@@ -2505,11 +2589,15 @@ fn target_pattern(kind: &str, value: &str, var: &str) -> String {
/// `?focus`. Taking the pattern rather than a class is what lets all four target
/// forms share one counter, and keeps `focus_nodes` in the report meaning the
/// same thing whichever form selected them.
-fn count_focus_nodes(graph: &Arc<GraphStore>, focus_pattern: &str) -> anyhow::Result<u64> {
+fn count_focus_nodes(
+ graph: &Arc<GraphStore>,
+ scope: &ReadScope,
+ focus_pattern: &str,
+) -> anyhow::Result<u64> {
let query = format!(
r#"SELECT (COUNT(DISTINCT ?focus) AS ?cnt) WHERE {{ {focus_pattern} }}"#
);
- let rows = graph_sparql_select(graph, &query)?;
+ let rows = graph_sparql_select(graph, scope, &query)?;
Ok(rows
.first()
.and_then(|row| row.get("cnt"))
diff --git a/src/temporal.rs b/src/temporal.rs
index 58a7431c..d08709b3 100644
--- a/src/temporal.rs
+++ b/src/temporal.rs
@@ -109,6 +109,47 @@
//! the only place that distinction can survive. With no `valid_at` it is read
//! like any other graph, because no instant was asked about.
//!
+//! ## Scope is an argument, not a default (#108)
+//!
+//! The two tools that produce VERDICTS, `onto_reason` and `onto_shacl`, used
+//! to read the whole store and had no argument that could change it. The
+//! reasoner read it through `GraphStore::all_triples`, which iterates every
+//! quad and drops the graph name; the validator read it through
+//! `sparql_select_union`, which makes the default graph the union of every
+//! graph. Over the store this module is about, that union is every version of
+//! every entity at once: a state that held at no instant. `onto_temporal_
+//! conflicts` filed the HEK293 example above as a correction, correctly, while
+//! `onto_reason` reported it as a disjointness clash and `onto_shacl` reported
+//! a cardinality violation, both of a moment that never occurred.
+//!
+//! What makes that worse than the defects already fixed here is that nothing
+//! in this project could catch it. A derivation certificate is a claim about
+//! the triples in `asserted.tsv`, and the Lean checker verifies exactly that
+//! claim; over the union of two versions it is a TRUE claim, and `oo-refute`
+//! will accept a machine-checked `cax-dw` refutation drawn from two versions
+//! that never coexisted. The certificate is valid and the graph is wrong, and
+//! a checker cannot see that far.
+//!
+//! So the scope became a value. `resolve` turns a caller's request into a
+//! `crate::graph::ReadScope` and a `ScopeManifest`, under these rules:
+//!
+//! - a store that does not use this vocabulary reads everything, as before;
+//! - `all_versions` reads everything and says so, whatever the descriptions
+//! say, so it is settled before any of them is read;
+//! - a store whose description sits in a NAMED graph, where `validities`
+//! cannot read it, is REFUSED, because every described graph would
+//! otherwise read as timeless and be in scope at every instant;
+//! - a store that uses this vocabulary, with no instant named, is REFUSED,
+//! because an honest refusal beats a confident answer over an arbitrary
+//! scope;
+//! - a snapshot reads the default graph plus the `in_scope` named graphs,
+//! less any graph holding this engine's own materialised inferences, and
+//! the manifest records every one of those decisions.
+//!
+//! The union is still reachable, by asking for it: `all_versions` is a real
+//! question ("does ANY version violate this shape") that was previously
+//! indistinguishable from not having thought about it.
+//!
//! ## Bounded scans
//!
//! Every query behind these tools is capped so a pathological store cannot
@@ -122,7 +163,7 @@
//! and an undescribed graph is timeless and always in scope. Those responses
//! also carry a `warning`.
-use crate::graph::GraphStore;
+use crate::graph::{GraphStore, ReadScope};
use chrono::{DateTime, Utc};
use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
@@ -297,6 +338,340 @@ impl Scope {
}
}
+/// What a caller asked a verdict-producing run to read (#108).
+///
+/// The three cases are not three settings of one knob. They are three
+/// different things a caller can mean, and the middle one used to be
+/// unsayable while the first two were spelled the same way.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum ScopeRequest {
+ /// No instant named and no opinion offered. Over a store that does not use
+ /// the temporal vocabulary this is the whole store and always was. Over one
+ /// that does, it is REFUSED: see [`resolve`].
+ Unscoped,
+ /// A snapshot. At least one of the two bounds is given; an absent one is
+ /// the axis not being asked about, exactly as in `onto_temporal_snapshot`.
+ Snapshot {
+ valid_at: Option<String>,
+ as_of: Option<String>,
+ },
+ /// Every graph in the store, over a store that HAS versions, asked for
+ /// deliberately. A legitimate thing to want — "does any version of this
+ /// register violate the shape" is a real question — and a different
+ /// question from any snapshot's, so it is said out loud rather than
+ /// arrived at by omission.
+ AllVersions,
+}
+
+impl ScopeRequest {
+ /// Build from the three optional arguments the tools take.
+ ///
+ /// `all_versions` together with either bound is refused rather than
+ /// resolved by precedence: the two say different things about the same
+ /// run, and guessing which one the caller meant is the failure this type
+ /// exists to remove.
+ pub fn from_args(
+ valid_at: Option<&str>,
+ as_of: Option<&str>,
+ all_versions: bool,
+ ) -> anyhow::Result<Self> {
+ let instant = valid_at.is_some() || as_of.is_some();
+ match (all_versions, instant) {
+ (true, true) => anyhow::bail!(
+ "all_versions asks for every version at once and valid_at/as_of asks for one \
+ instant. Those are different questions; pass one of them"
+ ),
+ (true, false) => Ok(ScopeRequest::AllVersions),
+ (false, true) => Ok(ScopeRequest::Snapshot {
+ valid_at: valid_at.map(str::to_string),
+ as_of: as_of.map(str::to_string),
+ }),
+ (false, false) => Ok(ScopeRequest::Unscoped),
+ }
+ }
+}
+
+/// Which graphs a run read, and how they were chosen.
+///
+/// This is the half of #108 that makes the rest defensible. A derivation
+/// certificate is a claim about the triples in `asserted.tsv`; the Lean
+/// checker verifies that claim and has no way to ask where those triples came
+/// from. A run that records its scope turns the selection into evidence that
+/// travels with the certificate, so "the certificate is valid and the graph is
+/// wrong" becomes a statement a reader can check rather than one they have to
+/// trust did not happen.
+#[derive(Clone, Debug)]
+pub struct ScopeManifest {
+ /// `whole-store`, `whole-store-all-versions` or `temporal-snapshot`.
+ pub selector: &'static str,
+ pub valid_at: Option<String>,
+ pub as_of: Option<String>,
+ /// Present only for a snapshot: the named graphs read, in read order.
+ pub graphs: Option<Vec<String>>,
+ /// Present only for a snapshot: named graphs deliberately not read, each
+ /// with the reason.
+ pub excluded: Vec<serde_json::Value>,
+ /// Whether the default graph is in the dataset. True in every scope this
+ /// engine builds: it holds the schema, and a snapshot of the ABox with no
+ /// TBox answers a different question from the one asked.
+ pub default_graph: bool,
+ /// False when a scan behind the selection hit its cap, which makes the
+ /// scope wrong rather than merely short.
+ pub complete: bool,
+ pub warning: Option<String>,
+}
+
+impl ScopeManifest {
+ /// Does this run read a store that keeps VERSIONS?
+ ///
+ /// True for a snapshot and for a deliberate whole-store run over a store
+ /// that uses the temporal vocabulary; false only for a store that does not
+ /// use it at all. It is the question "may this run write its conclusions
+ /// into the store", and the answer is no in both true cases: every graph
+ /// a run could write to is in scope at every instant — the default graph
+ /// because it is timeless, a named inference graph because it carries no
+ /// validity description — so a conclusion written there becomes an axiom
+ /// of every OTHER snapshot. That is true of a snapshot's conclusions, which
+ /// held at one instant, and of a whole-store run's, which held at none.
+ pub fn store_has_versions(&self) -> bool {
+ self.selector != "whole-store"
+ }
+
+ /// The whole store, which is what every run did before #108.
+ fn whole_store(selector: &'static str) -> Self {
+ Self {
+ selector,
+ valid_at: None,
+ as_of: None,
+ graphs: None,
+ excluded: Vec::new(),
+ default_graph: true,
+ complete: true,
+ warning: None,
+ }
+ }
+
+ /// The JSON a report and a certificate carry.
+ ///
+ /// A whole-store run lists no graph names on purpose: "every graph"
+ /// already is the complete answer, and a list would go stale against a
+ /// store that grew between the scan and the run without any reader being
+ /// able to tell.
+ pub fn to_json(&self) -> serde_json::Value {
+ let mut out = serde_json::json!({
+ "selector": self.selector,
+ "default_graph": self.default_graph,
+ "semantics_version": SEMANTICS_VERSION,
+ "complete": self.complete,
+ });
+ if let Some(graphs) = &self.graphs {
+ out["graphs"] = serde_json::json!(graphs);
+ out["graph_count"] = serde_json::json!(graphs.len());
+ } else {
+ out["note"] = serde_json::json!(
+ "every graph in the store, the default graph included. On a store that keeps \
+ several versions of an entity in several named graphs this union is a state \
+ that held at no instant."
+ );
+ }
+ if let Some(v) = &self.valid_at {
+ out["valid_at"] = serde_json::json!(v);
+ }
+ if let Some(v) = &self.as_of {
+ out["as_of"] = serde_json::json!(v);
+ }
+ if !self.excluded.is_empty() {
+ out["excluded"] = serde_json::Value::Array(self.excluded.clone());
+ }
+ if let Some(w) = &self.warning {
+ out["warning"] = serde_json::json!(w);
+ }
+ out
+ }
+
+ /// The tab-separated form written beside a certificate, so the scope
+ /// travels with `asserted.tsv` rather than only in a tool response that
+ /// nobody keeps.
+ pub fn to_tsv(&self) -> String {
+ let mut s = String::from("oo-scope/1\n");
+ s.push_str(&format!("selector\t{}\n", self.selector));
+ s.push_str(&format!("semantics_version\t{SEMANTICS_VERSION}\n"));
+ s.push_str(&format!("default_graph\t{}\n", self.default_graph));
+ s.push_str(&format!("complete\t{}\n", self.complete));
+ if let Some(v) = &self.valid_at {
+ s.push_str(&format!("valid_at\t{v}\n"));
+ }
+ if let Some(v) = &self.as_of {
+ s.push_str(&format!("as_of\t{v}\n"));
+ }
+ match &self.graphs {
+ Some(graphs) => {
+ for g in graphs {
+ s.push_str(&format!("graph\t{g}\n"));
+ }
+ }
+ None => s.push_str("graph\t*\n"),
+ }
+ for row in &self.excluded {
+ let g = row.get("graph").and_then(|v| v.as_str()).unwrap_or("?");
+ let why = row.get("reason").and_then(|v| v.as_str()).unwrap_or("?");
+ s.push_str(&format!("excluded\t{g}\t{why}\n"));
+ }
+ s
+ }
+}
+
+/// The body of the query behind both the probe and the listing: anything the
+/// store says with one of the six temporal predicates.
+fn described_pattern() -> String {
+ format!(
+ "{{ ?g <{NS}validFrom> ?x }} UNION {{ ?g <{NS}validTo> ?x }} \
+ UNION {{ ?g <{NS}recordedAt> ?x }} UNION {{ ?g <{NS}recordedUntil> ?x }} \
+ UNION {{ ?g <{NS}supersedes> ?x }} UNION {{ ?g <{NS}retracts> ?x }}"
+ )
+}
+
+/// Does this store use the temporal vocabulary ANYWHERE, default graph or not?
+///
+/// Runs on every `onto_reason` and every `onto_shacl`, including the
+/// overwhelming majority that are over stores with no versions at all, so it
+/// is one query with no DISTINCT and no ORDER BY: both would force the whole
+/// result to be materialised before the LIMIT could apply, and the answer here
+/// is a boolean that the first row settles.
+fn uses_temporal_vocabulary(graph: &GraphStore) -> anyhow::Result<bool> {
+ let query = format!("SELECT ?g WHERE {{ {} }} LIMIT 1", described_pattern());
+ let parsed: serde_json::Value = serde_json::from_str(&graph.sparql_select_union(&query)?)?;
+ Ok(parsed
+ .get("results")
+ .and_then(|r| r.as_array())
+ .is_some_and(|rows| !rows.is_empty()))
+}
+
+/// Every graph the store DESCRIBES with the temporal vocabulary, whether or
+/// not the description is readable.
+///
+/// Read from the default graph, which is where `Temporal::validities` reads
+/// it, and separately from the union of every graph. The two differing is the
+/// one case that has to be loud: a description sitting in a named graph is
+/// invisible to the temporal layer, so the snapshot it would produce is not
+/// the snapshot the data describes, and answering anyway would be a confident
+/// answer over a scope the store contradicts.
+///
+/// "Graph" here is whatever the description's SUBJECT is, and nothing checks
+/// that it names a graph the store holds. A store that writes
+/// `temporal:validFrom` on a domain entity therefore trips the gate, is told
+/// so, and gets the same answer it always got once it names an instant. The
+/// alternative, intersecting with the named graphs that hold assertions, would
+/// let a described-but-currently-empty graph slip past the gate, and of the
+/// two directions only one of them is safe.
+fn described_graphs(graph: &GraphStore) -> anyhow::Result<(BTreeSet<String>, BTreeSet<String>)> {
+ let query = format!(
+ "SELECT DISTINCT ?g WHERE {{ {} }} ORDER BY ?g LIMIT {VALIDITY_SCAN_LIMIT}",
+ described_pattern()
+ );
+ let read = |raw: String| -> anyhow::Result<BTreeSet<String>> {
+ let parsed: serde_json::Value = serde_json::from_str(&raw)?;
+ Ok(parsed
+ .get("results")
+ .and_then(|r| r.as_array())
+ .map(|rows| {
+ rows.iter()
+ .filter_map(|r| r.get("g").and_then(|v| v.as_str()).map(plain))
+ .collect()
+ })
+ .unwrap_or_default())
+ };
+ let in_default = read(graph.sparql_select(&query)?)?;
+ let anywhere = read(graph.sparql_select_union(&query)?)?;
+ Ok((in_default, anywhere))
+}
+
+/// Resolve what a run should read, refusing rather than choosing (#108).
+///
+/// The contract, in the order the checks run:
+///
+/// * A store that does not use the temporal vocabulary reads the whole store
+/// under every request, and the answer is byte-identical to 1.3.0's.
+/// * `AllVersions` reads the whole store and says so in the manifest, so the
+/// union is a stated choice rather than a default. Settled first, because
+/// no fact about the descriptions can make that answer wrong.
+/// * A store whose temporal description sits outside the default graph is
+/// REFUSED, because the temporal layer reads validity from the default
+/// graph and would treat every described graph as timeless.
+/// * A bi-temporal store with no instant named is REFUSED. The union of every
+/// version is a state that held at no instant, and a verdict over it is
+/// neither what was true then nor what is true now.
+/// * A snapshot reads the default graph plus the in-scope named graphs, minus
+/// any graph holding this engine's own materialised inferences.
+pub fn resolve(
+ graph: &Arc<GraphStore>,
+ request: &ScopeRequest,
+) -> anyhow::Result<(ReadScope, ScopeManifest)> {
+ // The cheap half first: most stores do not use this vocabulary at all, and
+ // for those the gate is one bounded query and no behaviour change.
+ if !uses_temporal_vocabulary(graph)? {
+ return Ok((
+ ReadScope::AllGraphs,
+ ScopeManifest::whole_store("whole-store"),
+ ));
+ }
+ // `AllVersions` is settled before anything is read about the descriptions,
+ // and deliberately: it reads every graph whatever any description says, so
+ // no description can make its answer wrong, and refusing it for a
+ // description the temporal layer cannot reach would close the one escape
+ // hatch a store in that state has.
+ if matches!(request, ScopeRequest::AllVersions) {
+ return Ok((
+ ReadScope::AllGraphs,
+ ScopeManifest::whole_store("whole-store-all-versions"),
+ ));
+ }
+ let (in_default, anywhere) = described_graphs(graph)?;
+ let unreadable: Vec<&String> = anywhere.difference(&in_default).collect();
+ if !unreadable.is_empty() {
+ anyhow::bail!(
+ "temporal description out of reach: {n} graph(s) are described with the temporal \
+ vocabulary ({NS}) in a NAMED graph, and this engine reads validity from the DEFAULT \
+ graph only (see the module documentation of src/temporal.rs). Those descriptions do \
+ not reach onto_temporal_snapshot, so every one of those graphs would be treated as \
+ timeless and put in scope at every instant. Move the description into the default \
+ graph. First: {sample}",
+ n = unreadable.len(),
+ sample = unreadable
+ .iter()
+ .take(3)
+ .map(|g| g.as_str())
+ .collect::<Vec<_>>()
+ .join(", "),
+ );
+ }
+ match request {
+ // Answered above, before the descriptions were read at all.
+ ScopeRequest::AllVersions => Ok((
+ ReadScope::AllGraphs,
+ ScopeManifest::whole_store("whole-store-all-versions"),
+ )),
+ ScopeRequest::Unscoped => anyhow::bail!(
+ "temporal scope not specified. This store describes {n} named graph(s) with the \
+ temporal vocabulary ({NS}), so reading every graph means reading every version at \
+ once: a state that held at no instant, and a verdict over it is neither what was \
+ true then nor what is true now. Pass valid_at (what was TRUE then) and/or as_of \
+ (what was KNOWN then) to run over a snapshot, or all_versions=true to say that the \
+ union of every version is what you meant. Described graphs: {sample}",
+ n = in_default.len(),
+ sample = in_default
+ .iter()
+ .take(3)
+ .map(|g| g.as_str())
+ .collect::<Vec<_>>()
+ .join(", "),
+ ),
+ ScopeRequest::Snapshot { valid_at, as_of } => {
+ Temporal::new(graph.clone()).read_scope(valid_at.as_deref(), as_of.as_deref())
+ }
+ }
+}
+
#[derive(Clone, Debug, Default)]
pub struct Validity {
pub graph: String,
@@ -1863,6 +2238,82 @@ impl Temporal {
Ok(out.to_string())
}
+ /// The dataset a run at this instant may read, and the record of how it
+ /// was chosen (#108).
+ ///
+ /// Three decisions are taken here and each is visible in the manifest:
+ ///
+ /// * **Membership** is exactly the snapshot's `in_scope` set. Nothing is
+ /// added, and the two tools cannot drift because both call `scope()`.
+ /// * **The default graph is in**, wholesale. It holds the schema, and a
+ /// snapshot of the ABox with no TBox answers a question nobody asked;
+ /// it also holds the validity metadata, which therefore enters the
+ /// reasoner's closure and SHACL's focus-node counts. That is a real
+ /// cost, stated in `docs/trusted-computing-base.md` rather than fixed
+ /// here, because the alternatives (filtering by predicate namespace, or
+ /// a named schema graph) each decide for the user where their schema
+ /// lives.
+ /// * **This engine's own inferences are out.** A named graph holding
+ /// materialised inferences has no validity description, so it is
+ /// timeless and in scope at every instant; reading it would make run
+ /// N's conclusions run N+1's assertions inside the one path whose whole
+ /// point is that `asserted.tsv` lists assertions. It is dropped and the
+ /// drop is recorded, never silent.
+ ///
+ /// Nothing is copied: the manifest is a list of graph names, and both
+ /// readers (`GraphStore::triples_in_scope` for the reasoner, a dataset
+ /// specification for SPARQL) select rather than materialise, so a scoped
+ /// run costs no extra memory and cross-graph joins keep working.
+ pub fn read_scope(
+ &self,
+ valid_at: Option<&str>,
+ as_of: Option<&str>,
+ ) -> anyhow::Result<(ReadScope, ScopeManifest)> {
+ let at = argument("valid_at", valid_at)?;
+ let of = argument("as_of", as_of)?;
+ let mut scope = self.scope(at, of)?;
+
+ let mut excluded: Vec<serde_json::Value> = Vec::new();
+ excluded.extend(scope.excluded.iter().cloned());
+ excluded.extend(scope.invalid.iter().cloned());
+ excluded.extend(scope.retracted.iter().cloned());
+
+ let mut named = Vec::with_capacity(scope.graphs.len());
+ for g in std::mem::take(&mut scope.graphs) {
+ if g == crate::reason::INFERRED_GRAPH {
+ excluded.push(serde_json::json!({
+ "graph": g,
+ "reason": "materialised inferences from an earlier run, not assertions",
+ }));
+ continue;
+ }
+ named.push(g);
+ }
+
+ let warning = scope.warning().map(|w| {
+ format!(
+ "{w} This run READ that scope, so its verdict is about the wrong set of graphs."
+ )
+ });
+ let manifest = ScopeManifest {
+ selector: "temporal-snapshot",
+ valid_at: valid_at.map(str::to_string),
+ as_of: as_of.map(str::to_string),
+ graphs: Some(named.clone()),
+ excluded,
+ default_graph: true,
+ complete: scope.complete(),
+ warning,
+ };
+ Ok((
+ ReadScope::Graphs {
+ default_graph: true,
+ named,
+ },
+ manifest,
+ ))
+ }
+
/// Run a query against only the graphs in temporal scope.
///
/// The query is wrapped rather than rewritten: its pattern is evaluated
diff --git a/tests/shacl_test.rs b/tests/shacl_test.rs
index 4d012767..5d39e1b6 100644
--- a/tests/shacl_test.rs
+++ b/tests/shacl_test.rs
@@ -885,12 +885,19 @@ fn test_the_default_graph_is_still_read() {
#[test]
fn test_the_report_names_the_scope_it_selected_over() {
// A verdict that does not say what it selected over cannot be replayed or
- // compared against the next one. The key is added before temporal scoping
- // arrives rather than on the run where it first matters.
+ // compared against the next one. This used to assert the bare string
+ // `all_graphs`, a placeholder put in before temporal scoping arrived so
+ // the key would not appear for the first time on the run where it
+ // mattered. That run has arrived (#108), so the key now carries the
+ // manifest and this asserts the manifest.
let store = store_from_trig("@prefix ex: <http://example.org/> . ex:a a ex:Thing .");
let report = ShaclValidator::validate(&store, ONE_SHAPE).unwrap();
let v: serde_json::Value = serde_json::from_str(&report).unwrap();
- assert_eq!(v["scope"], "all_graphs", "report: {v}");
+ assert_eq!(v["scope"]["selector"], "whole-store", "report: {v}");
+ assert_eq!(v["scope"]["default_graph"], true, "report: {v}");
+ // A whole-store run lists no graph names: "every graph" is already the
+ // complete answer, and a list would go stale against a store that grew.
+ assert!(v["scope"].get("graphs").is_none(), "report: {v}");
}
// Range constraints. Before these were implemented, a shape carrying
diff --git a/tests/temporal_scope_test.rs b/tests/temporal_scope_test.rs
new file mode 100644
index 00000000..2ef74622
--- /dev/null
+++ b/tests/temporal_scope_test.rs
@@ -0,0 +1,627 @@
+//! Graph scope for the verdict-producing tools (#108).
+//!
+//! The defect: `Reasoner::run` read the store through `GraphStore::all_triples`,
+//! which iterates every quad and drops the graph name, and `ShaclValidator::
+//! validate` read it through `sparql_select_union`, which makes the default
+//! graph the union of every graph. On a store that keeps one entity's versions
+//! in one named graph each, both read every version at once and judged a state
+//! that held at no instant. Neither had an argument that could change it.
+//!
+//! Why it needed its own gate rather than the ones already here: a certificate
+//! over such a run is CORRECT. `oo-cert` verifies that each derivation follows
+//! from the triples in `asserted.tsv`, and it does; `oo-refute` verifies that
+//! the premises of a `cax-dw` clash are in `asserted.tsv`, and they are. The
+//! graph in `asserted.tsv` is the thing that is wrong, and no checker can see
+//! that far. The tests below that name a certificate are testing the one
+//! failure this project's gates are blind to.
+//!
+//! Every test here fails on the tree before the fix. Four of them fail by
+//! returning a confident wrong answer (`clash`, `conforms: false`, a written
+//! `refutation.tsv`, a certificate with no scope); the rest fail because the
+//! argument they pass did not exist.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::reason::{InferenceTarget, Reasoner};
+use open_ontologies::shacl::ShaclValidator;
+use open_ontologies::temporal::{ScopeRequest, Temporal};
+use oxigraph::io::RdfFormat;
+use std::sync::Arc;
+
+/// The module's own example, bi-temporal: one cell line, adherent until
+/// 1 May 2026 and suspension from 1 May 2026. The two periods are half-open
+/// and MEET, so they share no instant. At no moment was HEK293 both.
+const TWO_VERSIONS: &str = r#"
+@prefix : <https://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#> .
+
+:g1 { :HEK293 a :AdherentCellLine . }
+:g2 { :HEK293 a :SuspensionCellLine . }
+{
+ :AdherentCellLine a owl:Class .
+ :SuspensionCellLine a owl:Class ; owl:disjointWith :AdherentCellLine .
+
+ :g1 t:validFrom "2024-01-01"^^xsd:date ;
+ t:validTo "2026-05-01"^^xsd:date ;
+ t:recordedAt "2024-01-05T09:00:00Z"^^xsd:dateTime .
+ :g2 t:validFrom "2026-05-01"^^xsd:date ;
+ t:recordedAt "2026-05-02T09:00:00Z"^^xsd:dateTime .
+}
+"#;
+
+/// The same store with the disagreement carried by a datatype property, so a
+/// SHACL cardinality constraint can be written over it.
+const TWO_VERSIONS_SHACL: &str = r#"
+@prefix : <https://example.org/> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+
+:g1 { :HEK293 a :CellLine ; :growthMode "adherent" . }
+:g2 { :HEK293 a :CellLine ; :growthMode "suspension" . }
+{
+ :g1 t:validFrom "2024-01-01"^^xsd:date ;
+ t:validTo "2026-05-01"^^xsd:date ;
+ t:recordedAt "2024-01-05T09:00:00Z"^^xsd:dateTime .
+ :g2 t:validFrom "2026-05-01"^^xsd:date ;
+ t:recordedAt "2026-05-02T09:00:00Z"^^xsd:dateTime .
+}
+"#;
+
+/// One growth mode at a time. True at every instant; false only of the union
+/// of every version, which is a state the register never held.
+const ONE_MODE: &str = r#"
+@prefix sh: <http://www.w3.org/ns/shacl#> .
+@prefix : <https://example.org/> .
+
+:CellLineShape a sh:NodeShape ;
+ sh:targetClass :CellLine ;
+ sh:property [ sh:path :growthMode ; sh:maxCount 1 ] .
+"#;
+
+/// No temporal vocabulary anywhere. Everything about a run over this store has
+/// to be exactly what it was before #108.
+const NO_TEMPORAL: &str = r#"
+@prefix : <https://example.org/> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+
+:g1 { :HEK293 a :CellLine ; :growthMode "adherent" . }
+{ :CellLine a owl:Class . }
+"#;
+
+fn store(trig: &str) -> Arc<GraphStore> {
+ let g = Arc::new(GraphStore::new());
+ g.load_content(trig, RdfFormat::TriG).expect("TriG parses");
+ g
+}
+
+fn json(s: &str) -> serde_json::Value {
+ serde_json::from_str(s).expect("tool output is JSON")
+}
+
+fn at(valid_at: &str) -> ScopeRequest {
+ ScopeRequest::Snapshot {
+ valid_at: Some(valid_at.to_string()),
+ as_of: None,
+ }
+}
+
+/// A fresh directory per certificate, named for the test that asked for it, so
+/// two tests running in parallel cannot read each other's files.
+struct CertDir(std::path::PathBuf);
+
+impl CertDir {
+ fn new(name: &str) -> Self {
+ let dir = std::env::temp_dir().join(format!("oo-108-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ Self(dir)
+ }
+ fn path(&self) -> &std::path::Path {
+ &self.0
+ }
+ fn read(&self, file: &str) -> Option<String> {
+ std::fs::read_to_string(self.0.join(file)).ok()
+ }
+}
+
+impl Drop for CertDir {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+}
+
+// ── The data, and what the temporal layer already said about it ─────────────
+
+/// Quoted so nothing below can be read as a disagreement about the DATA. The
+/// one tool that knew about valid time got this right before the fix and after
+/// it; the two that produce verdicts did not.
+#[test]
+fn the_temporal_layer_agrees_the_two_versions_never_overlap() {
+ let c = json(&Temporal::new(store(TWO_VERSIONS)).conflicts().unwrap());
+ assert_eq!(
+ c["contradiction_count"], 0,
+ "the two periods meet and share no instant, so this is a correction, not a \
+ contradiction: {c}"
+ );
+}
+
+// ── The refusal ─────────────────────────────────────────────────────────────
+
+#[test]
+fn reasoning_over_temporal_data_with_no_snapshot_is_refused() {
+ let e = Reasoner::run_full(
+ &store(TWO_VERSIONS),
+ "owl-rl",
+ false,
+ InferenceTarget::DefaultGraph,
+ None,
+ )
+ .expect_err("a bi-temporal store with no instant named must not be answered");
+ let msg = e.to_string();
+ assert!(
+ msg.contains("temporal scope not specified") && msg.contains("valid_at"),
+ "the refusal has to name the way out, or it is a dead end: {msg}"
+ );
+}
+
+#[test]
+fn shacl_over_temporal_data_with_no_snapshot_is_refused() {
+ let e = ShaclValidator::validate(&store(TWO_VERSIONS_SHACL), ONE_MODE)
+ .expect_err("a bi-temporal store with no instant named must not be validated");
+ assert!(
+ e.to_string().contains("temporal scope not specified"),
+ "{e}"
+ );
+}
+
+#[test]
+fn a_horn_run_over_temporal_data_with_no_snapshot_is_refused() {
+ // The user-supplied-rules path reads the store the same way and writes the
+ // same kind of certificate, so it gets the same gate. Refused BEFORE the
+ // rule table is read, which is why a path that does not exist is fine here.
+ let dir = CertDir::new("horn");
+ let e = Reasoner::run_horn(
+ &store(TWO_VERSIONS),
+ std::path::Path::new("/nonexistent/rules.tsv"),
+ dir.path(),
+ )
+ .expect_err("the Horn path must be gated too");
+ assert!(
+ e.to_string().contains("temporal scope not specified"),
+ "the scope is resolved before the rule table is read: {e}"
+ );
+}
+
+/// The second door. `onto_reason_incremental` reads the union through
+/// `sparql_select_union` and materialises into the default graph, so leaving
+/// it ungated would have left a way to get the old behaviour, written into the
+/// store, by using a different tool. It has no snapshot form and does not
+/// pretend to: the refusal names `onto_reason` for that.
+#[test]
+fn incremental_reasoning_over_temporal_data_with_no_snapshot_is_refused() {
+ use open_ontologies::reason_incremental::{IncrementalReasoner, parse_ntriples};
+ let delta = parse_ntriples(
+ "<https://example.org/HEK293> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> \
+ <https://example.org/AdherentCellLine> .",
+ );
+ let store = store(TWO_VERSIONS);
+ let e = IncrementalReasoner::run(&store, &delta, true)
+ .expect_err("the incremental path must not be a way around the gate");
+ let msg = e.to_string();
+ assert!(
+ msg.contains("temporal scope not specified") && msg.contains("no snapshot form"),
+ "{msg}"
+ );
+ // And it is not a dead end: the union is reachable by saying so.
+ let out = json(
+ &IncrementalReasoner::run_scoped(&store, &delta, false, true)
+ .expect("all_versions says the union was meant"),
+ );
+ assert_eq!(out["ok"], serde_json::Value::Bool(true), "{out}");
+}
+
+#[test]
+fn asking_for_one_instant_and_for_every_version_at_once_is_refused() {
+ let e = ScopeRequest::from_args(Some("2026-01-01"), None, true)
+ .expect_err("two different questions must not be resolved by precedence");
+ assert!(e.to_string().contains("different questions"), "{e}");
+}
+
+/// The temporal layer reads validity from the DEFAULT graph. A description
+/// sitting in a named graph is invisible to it, so every described graph would
+/// read as timeless and be in scope at every instant: a confident answer over
+/// a scope the store contradicts.
+#[test]
+fn a_temporal_description_out_of_reach_is_refused_rather_than_ignored() {
+ let s = store(
+ r#"
+@prefix : <https://example.org/> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+:g1 { :HEK293 a :CellLine . }
+:meta { :g1 t:validFrom "2024-01-01"^^xsd:date . }
+"#,
+ );
+ let e = ShaclValidator::validate_scoped(&s, ONE_MODE, &at("2025-01-01"))
+ .expect_err("metadata the temporal layer cannot read must not be silently skipped");
+ let msg = e.to_string();
+ assert!(
+ msg.contains("temporal description out of reach") && msg.contains("timeless"),
+ "{msg}"
+ );
+}
+
+// ── The scoped answer ───────────────────────────────────────────────────────
+
+#[test]
+fn a_snapshot_reasons_over_one_version_and_finds_no_clash() {
+ for instant in ["2025-01-01", "2026-06-01"] {
+ let out = json(
+ &Reasoner::run_scoped(
+ &store(TWO_VERSIONS),
+ "owl-rl",
+ false,
+ InferenceTarget::DefaultGraph,
+ None,
+ &at(instant),
+ )
+ .unwrap(),
+ );
+ assert!(
+ out.get("inconsistency").is_none(),
+ "at {instant} exactly one version is in scope, so there is no disjointness clash \
+ to find: {out}"
+ );
+ assert_eq!(out["scope"]["graph_count"], 1, "at {instant}: {out}");
+ }
+}
+
+#[test]
+fn a_snapshot_reads_the_version_that_was_true_then_and_no_other() {
+ let early = json(
+ &Reasoner::run_scoped(
+ &store(TWO_VERSIONS),
+ "owl-rl",
+ false,
+ InferenceTarget::DefaultGraph,
+ None,
+ &at("2025-01-01"),
+ )
+ .unwrap(),
+ );
+ let late = json(
+ &Reasoner::run_scoped(
+ &store(TWO_VERSIONS),
+ "owl-rl",
+ false,
+ InferenceTarget::DefaultGraph,
+ None,
+ &at("2026-06-01"),
+ )
+ .unwrap(),
+ );
+ assert_eq!(early["scope"]["graphs"][0], "https://example.org/g1", "{early}");
+ assert_eq!(late["scope"]["graphs"][0], "https://example.org/g2", "{late}");
+}
+
+#[test]
+fn shacl_conforms_at_each_instant() {
+ for instant in ["2025-01-01", "2026-06-01"] {
+ let report = json(
+ &ShaclValidator::validate_scoped(&store(TWO_VERSIONS_SHACL), ONE_MODE, &at(instant))
+ .unwrap(),
+ );
+ assert_eq!(
+ report["conforms"],
+ serde_json::Value::Bool(true),
+ "HEK293 had exactly one growth mode at {instant}: {report}"
+ );
+ assert_eq!(report["scope"]["selector"], "temporal-snapshot", "{report}");
+ }
+}
+
+/// The union answer is not wrong to want; it was wrong to arrive at by
+/// omission. Asked for by name it is available, and the report says which
+/// question was answered.
+#[test]
+fn every_version_at_once_is_still_reachable_and_is_labelled() {
+ let report = json(
+ &ShaclValidator::validate_scoped(
+ &store(TWO_VERSIONS_SHACL),
+ ONE_MODE,
+ &ScopeRequest::AllVersions,
+ )
+ .unwrap(),
+ );
+ assert_eq!(
+ report["conforms"],
+ serde_json::Value::Bool(false),
+ "across every version there are two growth modes: {report}"
+ );
+ assert_eq!(
+ report["scope"]["selector"], "whole-store-all-versions",
+ "and the report has to say that is the question it answered: {report}"
+ );
+}
+
+// ── The scope as evidence ───────────────────────────────────────────────────
+
+#[test]
+fn a_certificate_records_which_graphs_it_read() {
+ let dir = CertDir::new("scope");
+ let out = json(
+ &Reasoner::run_scoped(
+ &store(TWO_VERSIONS_SHACL),
+ "rdfs",
+ false,
+ InferenceTarget::DefaultGraph,
+ Some(dir.path()),
+ &at("2025-01-01"),
+ )
+ .unwrap(),
+ );
+ assert_eq!(
+ out["certificate"]["scope"]["selector"], "temporal-snapshot",
+ "{out}"
+ );
+ let tsv = dir.read("scope.tsv").expect("scope.tsv sits beside asserted.tsv");
+ assert!(tsv.starts_with("oo-scope/1\n"), "{tsv}");
+ assert!(tsv.contains("graph\thttps://example.org/g1\n"), "{tsv}");
+ assert!(
+ !tsv.contains("graph\thttps://example.org/g2\n"),
+ "g2 was out of scope at that instant and must not be listed as read: {tsv}"
+ );
+ assert!(tsv.contains("valid_at\t2025-01-01\n"), "{tsv}");
+}
+
+/// An unscoped run over a store with no versions records its scope too. The
+/// key must not appear for the first time on the run where it matters, or a
+/// reader has no baseline to compare against.
+#[test]
+fn an_unscoped_certificate_says_it_read_everything() {
+ let dir = CertDir::new("whole");
+ let out = json(
+ &Reasoner::run_full(
+ &store(NO_TEMPORAL),
+ "rdfs",
+ false,
+ InferenceTarget::DefaultGraph,
+ Some(dir.path()),
+ )
+ .unwrap(),
+ );
+ assert_eq!(out["certificate"]["scope"]["selector"], "whole-store", "{out}");
+ let tsv = dir.read("scope.tsv").expect("scope.tsv is written");
+ assert!(tsv.contains("graph\t*\n"), "{tsv}");
+}
+
+#[test]
+fn a_store_with_no_temporal_vocabulary_is_unaffected() {
+ let out = json(
+ &Reasoner::run_full(
+ &store(NO_TEMPORAL),
+ "owl-rl",
+ false,
+ InferenceTarget::DefaultGraph,
+ None,
+ )
+ .unwrap(),
+ );
+ assert_eq!(out["scope"]["selector"], "whole-store", "{out}");
+ let report = json(&ShaclValidator::validate(&store(NO_TEMPORAL), ONE_MODE).unwrap());
+ assert_eq!(report["conforms"], serde_json::Value::Bool(true), "{report}");
+ assert_eq!(report["scope"]["selector"], "whole-store", "{report}");
+}
+
+// ── The sharp end: a valid certificate about the wrong graph ────────────────
+
+/// `cax-dw` is the ONE clash rule `OOCert.RefuteConditions` has a semantic
+/// condition for, so before the fix the engine wrote a `refutation.tsv` that
+/// `oo-refute check` ACCEPTS: a machine-checked `unsatisfiable_under_
+/// disjointness` over a union of versions that never held at once.
+#[test]
+fn no_machine_checkable_refutation_is_written_over_a_state_that_never_existed() {
+ let dir = CertDir::new("refute");
+ let out = json(
+ &Reasoner::run_scoped(
+ &store(TWO_VERSIONS),
+ "owl-rl",
+ false,
+ InferenceTarget::DefaultGraph,
+ Some(dir.path()),
+ &at("2025-01-01"),
+ )
+ .unwrap(),
+ );
+ assert!(
+ dir.read("refutation.tsv").is_none(),
+ "at 2025-01-01 only the adherent version is in scope, so the graph is consistent and \
+ there is nothing to refute. Report: {out}"
+ );
+ let asserted = dir.read("asserted.tsv").expect("asserted.tsv is written");
+ let membership = "<https://example.org/HEK293>\t\
+ <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\t\
+ <https://example.org/SuspensionCellLine>";
+ assert!(
+ !asserted.contains(membership),
+ "the out-of-scope version's ABox must not be in the graph the certificate is \
+ about:\n{asserted}"
+ );
+ // The DECLARATION `:SuspensionCellLine a owl:Class` and the disjointness
+ // axiom ARE there, and belong there: they sit in the default graph, which
+ // is in every snapshot's scope because the schema is not a version. What a
+ // snapshot removes is the ABox that made the disjointness bite.
+ assert!(asserted.contains("owl#disjointWith"), "{asserted}");
+ // And the validity metadata is there too, because the default graph enters
+ // wholesale. That is the cost of decision 3 on #108, stated in
+ // docs/trusted-computing-base.md rather than hidden: these triples are in
+ // the reasoner's closure and in SHACL's focus-node counts.
+ assert!(asserted.contains("temporal#validFrom"), "{asserted}");
+}
+
+// ── Inferences are not assertions, across runs ──────────────────────────────
+
+/// `docs/trusted-computing-base.md` hazard 5: `all_triples` reads every named
+/// graph, so inferences an earlier run parked in the inference graph come back
+/// as assertions in a later certified run, and `inference_graph: true` does not
+/// stop it. An undescribed graph is also timeless, so the temporal scope would
+/// have put it in at every instant. A scoped run drops it and says so.
+#[test]
+fn an_earlier_runs_inferences_are_not_read_back_as_assertions() {
+ let s = store(
+ r#"
+@prefix : <https://example.org/> .
+@prefix t: <https://open-ontologies.org/temporal#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+:g1 { :HEK293 a :CellLine . }
+<https://open-ontologies.org/graph/inferred> { :HEK293 a :SomethingDerived . }
+{ :g1 t:validFrom "2024-01-01"^^xsd:date . }
+"#,
+ );
+ let dir = CertDir::new("inferred");
+ let out = json(
+ &Reasoner::run_scoped(
+ &s,
+ "rdfs",
+ false,
+ InferenceTarget::DefaultGraph,
+ Some(dir.path()),
+ &at("2025-01-01"),
+ )
+ .unwrap(),
+ );
+ let asserted = dir.read("asserted.tsv").expect("asserted.tsv is written");
+ assert!(
+ !asserted.contains("SomethingDerived"),
+ "an inference from an earlier run is not an assertion of this one:\n{asserted}"
+ );
+ let excluded = out["scope"]["excluded"].as_array().expect("excluded rows");
+ assert!(
+ excluded.iter().any(|r| r["reason"]
+ .as_str()
+ .is_some_and(|s| s.contains("materialised inferences"))),
+ "the drop has to be recorded, not silent: {out}"
+ );
+}
+
+// ── Materialisation under a scope ───────────────────────────────────────────
+
+/// Both directions of the same rule. A snapshot's conclusions held at one
+/// instant and would be read at all of them; an all-versions run's held at
+/// none, and writing THOSE into the timeless default graph is the leak of #108
+/// arriving through the exit instead of the entrance.
+#[test]
+fn no_run_over_a_versioned_store_materialises() {
+ for (name, request) in [
+ ("snapshot", at("2025-01-01")),
+ ("all versions", ScopeRequest::AllVersions),
+ ] {
+ let e = Reasoner::run_scoped(
+ &store(TWO_VERSIONS),
+ "owl-rl",
+ true,
+ InferenceTarget::DefaultGraph,
+ None,
+ &request,
+ )
+ .unwrap_err();
+ assert!(
+ e.to_string()
+ .contains("run over a versioned store does not materialise"),
+ "{name}: {e}"
+ );
+ }
+ // Including through the inference graph, which carries no validity
+ // description and is therefore timeless and in scope at every instant.
+ let e = Reasoner::run_scoped(
+ &store(TWO_VERSIONS),
+ "owl-rl",
+ true,
+ InferenceTarget::Inferred,
+ None,
+ &at("2025-01-01"),
+ )
+ .unwrap_err();
+ assert!(
+ e.to_string().contains("carrying no validity description"),
+ "{e}"
+ );
+ // A store with no versions is untouched: it materialises as it always did.
+ let plain = store(NO_TEMPORAL);
+ let before = plain.triple_count();
+ let out = json(
+ &Reasoner::run_full(&plain, "rdfs", true, InferenceTarget::DefaultGraph, None).unwrap(),
+ );
+ assert!(out.get("dry_run").is_none(), "{out}");
+ assert!(plain.triple_count() >= before, "{out}");
+}
+
+#[test]
+fn a_scoped_run_refuses_the_owl_dl_path_rather_than_ignoring_the_snapshot() {
+ let e = Reasoner::run_scoped(
+ &store(TWO_VERSIONS),
+ "owl-dl",
+ false,
+ InferenceTarget::DefaultGraph,
+ None,
+ &at("2025-01-01"),
+ )
+ .expect_err("the tableaux path has no scoped reader, so a snapshot would be ignored");
+ assert!(e.to_string().contains("owl-dl"), "{e}");
+}
+
+// ── An empty scope is a non-answer, not a pass ──────────────────────────────
+
+#[test]
+fn a_snapshot_selecting_no_graph_does_not_conform_vacuously() {
+ let report = json(
+ &ShaclValidator::validate_scoped(&store(TWO_VERSIONS_SHACL), ONE_MODE, &at("2000-01-01"))
+ .unwrap(),
+ );
+ assert_eq!(
+ report["conforms"],
+ serde_json::Value::Null,
+ "before either version was valid there was no data to validate, and `true` would be \
+ the same lie as reporting it for a constraint that never ran: {report}"
+ );
+ assert!(
+ report["warning"]
+ .as_str()
+ .is_some_and(|w| w.contains("no graphs in scope")),
+ "{report}"
+ );
+ assert_eq!(report["scope"]["graph_count"], 0, "{report}");
+}
+
+// ── The escape a scoped SPARQL constraint must not have ─────────────────────
+
+/// `sh:sparql` runs a query the shapes author wrote, and a query can contain a
+/// `GRAPH` block. Restricting the default graph alone would leave that door
+/// open: the constraint would read the out-of-scope version and report a
+/// violation that is wrong at the instant asked about.
+#[test]
+fn a_sparql_constraint_cannot_name_its_way_out_of_the_scope() {
+ let shapes = r#"
+@prefix sh: <http://www.w3.org/ns/shacl#> .
+@prefix : <https://example.org/> .
+
+:EscapeShape a sh:NodeShape ;
+ sh:targetClass :CellLine ;
+ sh:sparql [
+ sh:message "read an out-of-scope graph" ;
+ sh:select """
+ SELECT $this WHERE {
+ GRAPH <https://example.org/g2> { $this <https://example.org/growthMode> ?m }
+ }
+ """ ;
+ ] .
+"#;
+ let report = json(
+ &ShaclValidator::validate_scoped(&store(TWO_VERSIONS_SHACL), shapes, &at("2025-01-01"))
+ .unwrap(),
+ );
+ assert_eq!(
+ report["violation_count"], 0,
+ "g2 is out of scope at 2025-01-01, so naming it explicitly must read nothing: {report}"
+ );
+}