Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat(reasoning): project bitemporal graph evidence into truth maintenance (#1675)
cxzg007b14a2b8d2f98
diff --git a/docs/docs.json b/docs/docs.jsonindex 8d0fda41..1fc129fe 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -207,6 +207,7 @@"reference/semantic_extract","reference/reasoning","reference/truth_maintenance",+ "reference/temporal_truth_maintenance","reference/ontology"]},diff --git a/docs/reference/temporal.md b/docs/reference/temporal.mdindex 71718c8d..6800a25c 100644--- a/docs/reference/temporal.md+++ b/docs/reference/temporal.md@@ -4,6 +4,11 @@ description: "Bi-temporal facts, point-in-time snapshots, Allen interval algebraicon: "clock"---+For rule-backed conclusions that must follow evidence expiration and corrections,+see [Temporal Truth Maintenance](/reference/temporal_truth_maintenance). The opt-in+adapter uses independent `valid_at` and `known_at` coordinates and keeps historical+queries separate from the live reasoning state.+Temporal Intelligence gives your knowledge graph a complete understanding of *when* — not just what is true, but when it was true in the real world, when it was recorded, and how facts have evolved over time.Shipped across **v0.3.0** (context temporal validity) and **v0.4.0** (full temporal stack), the system covers five layers:diff --git a/docs/reference/temporal_truth_maintenance.md b/docs/reference/temporal_truth_maintenance.mdnew file mode 100644index 00000000..fc9edbb0--- /dev/null+++ b/docs/reference/temporal_truth_maintenance.md@@ -0,0 +1,205 @@+---+title: "Temporal Truth Maintenance"+description: "Maintain derived facts over independent valid-time and known-time graph slices."+icon: "clock"+---++`TemporalTruthMaintenanceAdapter` connects explicitly annotated temporal graph+relationships to a [truth-maintenance session](/reference/truth_maintenance).+It turns changes in the selected evidence into one batch of source assertions+and retractions. Conclusions survive while they have another active support.++The two query coordinates are independent:++- **`valid_at`**: the time the claim applies to in the world.+- **`known_at`**: the time at which the evidence was recorded and not yet superseded.++This allows “what did we believe then?” and “what do we now believe about then?”+to have different answers. It does not change `TemporalGraphQuery` or its existing+`time_axis="both"` behavior, which checks both axes at the same timestamp.++## Example: a late correction and expiration++This example needs no database, embedding model or LLM:++```python+from copy import deepcopy++from semantica.reasoning import Rule, TemporalTruthMaintenanceAdapter++adapter = TemporalTruthMaintenanceAdapter(rules=[+ Rule("eligibility", "Eligibility", ["Employed(?x)"], "Eligible(?x)"),+])+original = {+ "source": "alice",+ "target": "acme",+ "type": "EMPLOYED_BY",+ "valid_from": "2026-09-01T00:00:00Z",+ "valid_until": "2026-09-30T00:00:00Z",+ "recorded_at": "2026-09-01T00:00:00Z",+ "metadata": {+ "truth_maintenance": {+ "support_id": "hr-v1:employment",+ "fact": "Employed(Alice)",+ },+ },+}+graph = {+ "entities": [{"id": "alice"}, {"id": "acme"}],+ "relationships": [original],+}+adapter.sync(graph, valid_at="2026-09-15", known_at="2026-09-15")+assert "Eligible(Alice)" in adapter.facts++# On September 20, we learn employment actually ended on September 10.+# Keep the old claim and close its transaction interval, not its valid interval.+corrected_graph = deepcopy(graph)+corrected_graph["relationships"][0]["superseded_at"] = "2026-09-20"+revision = deepcopy(original)+revision["valid_until"] = "2026-09-10"+revision["recorded_at"] = "2026-09-20"+revision["metadata"]["truth_maintenance"]["support_id"] = "hr-v2:employment"+corrected_graph["relationships"].append(revision)++delta = adapter.sync(+ corrected_graph, valid_at="2026-09-15", known_at="2026-09-20",+)+assert delta.removed_facts == frozenset({"Employed(Alice)", "Eligible(Alice)"})++then = adapter.query_at(valid_at="2026-09-15", known_at="2026-09-15")+with_correction = adapter.query_at(valid_at="2026-09-15", known_at="2026-09-20")+assert "Eligible(Alice)" in then.facts+assert not with_correction.facts+assert then.explain("Employed(Alice)").explicit_support_ids == ("hr-v1:employment",)+assert not adapter.facts # Historical queries did not move the live state.++# Explicitly move through the corrected valid-time boundary.+adapter.advance(valid_at="2026-09-09", known_at="2026-09-20")+assert "Eligible(Alice)" in adapter.facts+expired = adapter.advance(valid_at="2026-09-10", known_at="2026-09-20")+assert "Eligible(Alice)" in expired.removed_facts+assert graph["relationships"][0]["valid_until"] == "2026-09-30T00:00:00Z"+```++## Graph input and history++Pass a dictionary containing `entities` and `relationships`; callers with a+`ContextGraph` can export `to_kg_dict()` first and pass the result unchanged.+The caller must supply and retain the full managed evidence history, including+superseded relationship versions.+Exporting only an active view cannot reconstruct evidence that it omits.++With `ContextGraph`, the annotation and the bounds are ordinary keyword+arguments: `graph.add_edge(source, target, relation_type, valid_from=...,+valid_until=..., recorded_at=..., truth_maintenance={"support_id": ...,+"fact": ...})`. Extra keyword arguments are stored in edge metadata, so do not+wrap them in an explicit `metadata=` dictionary.++Each managed relationship has a `metadata.truth_maintenance` dictionary with+exactly `support_id` and `fact`. The fact uses PR1's canonical atom grammar; no+relation label is automatically translated into a rule predicate. A support ID+identifies **one source assertion revision**. Use distinct IDs for different+facts from the same document and for later revisions. Unannotated relationships+are ignored; malformed annotations raise `ValidationError`.++Temporal fields are read from each record itself and, when present, from its+`metadata` and `properties` dictionaries. That second location matters because+`ContextGraph` keeps everything except the valid-time bounds inside `metadata`+(entities also expose it through `properties`), so `to_kg_dict()` output works+without rewriting. A field supplied in more than one place must denote the same+instant; conflicting duplicates raise `TemporalValidationError`.++| Field | Meaning | Default for managed evidence |+|---|---|---|+| `valid_from` | Inclusive valid-time start | Unbounded past |+| `valid_until` | Exclusive valid-time end | Unbounded future |+| `recorded_at` | Inclusive known-time start | Required explicitly |+| `superseded_at` | Exclusive known-time end | Unbounded future |++Relationship endpoints are read from `source`/`target` or from the canonical+`source_id`/`target_id` emitted by `to_kg_dict()`. Supplying both forms with+different values raises `ValidationError` instead of silently preferring one.++Null upper bounds, `"OPEN"`, and `TemporalBound.OPEN` mean unbounded future.+Finite intervals require `start < end`. Times use the existing temporal parser:+ISO strings, datetimes and numeric Unix timestamps are accepted; naive datetimes+are treated as UTC. Booleans are rejected. There is no day/second truncation.+No default value is taken from the wall clock.++Retained records cannot disappear from a later `sync()`. Their fact, endpoints,+relation type, valid interval and recorded time cannot be rewritten. An open+`superseded_at` may be closed once; a closed interval cannot be reopened or+changed. Corrections close an old revision and add a new one. To withdraw a+source from the current known-time view, close its transaction interval and+advance `known_at` to or past that boundary. Physically removing a row is rejected.++The adapter accepts the source's explicit transaction history as authoritative;+it does not infer arrival times, resolve conflicting evidence or assign a+replacement relationship automatically.++Entity IDs must be unique strings. If the graph includes entities, every managed+edge needs existing endpoints, and both endpoints must be active at both query+coordinates. Entity scaffolding with no temporal fields is timeless. Its retained+time fields follow the same immutability/transaction-closing rules. Relationship-only+graphs are supported, but cannot later acquire endpoint constraints on the same+adapter: doing so would reinterpret retained history. Create a new adapter when+changing that mode. Predicate arity is checked across all retained evidence,+including records that are inactive at the requested coordinates.++## API++### `TemporalTruthMaintenanceAdapter(rules=...)`++Owns a new session with copied, fixed PR1 rules. No externally mutable session is+accepted. All PR1 rule restrictions, including non-recursion and absence of side+effects, apply. Access must be caller-serialized.++### `sync(graph, *, valid_at, known_at) -> MaintenanceDelta`++Validate and ingest the retained evidence projection. Diff its selected support+IDs against the currently active ones and apply one PR1 batch. A source replacement+for the same fact has support changes without intermediate fact churn.++Validation or reasoning failure leaves retained evidence, live facts, clocks and+counters unchanged. Input dictionaries are not mutated or retained by reference.+Non-temporal attributes and unrelated metadata are not part of the managed projection.++### `advance(*, valid_at, known_at) -> MaintenanceDelta`++Select another slice of retained evidence. This is how callers trigger expiration+or activation without modifying the graph. Both forward and backward movement are+allowed. There is no timer: merely waiting does not update the live facts.++### `query_at(*, valid_at, known_at) -> TemporalFactSnapshot`++Build a fresh session for the requested slice and return its facts, active source+supports and direct explanations. The frozen result contains only immutable+values; it exposes `explain(fact)` and remains unchanged by later updates.+It carries `valid_at`, `known_at` and `graph_revision`. It does not change the+live session or pretend that a historical recomputation has a live commit version.++### Live properties and explanation++- `facts`: immutable set of current explicit and inferred facts.+- `explain(fact)`: current PR1 direct sources and derivations.+- `version`: PR1's committed support-set counter. A clock-only change need not increment it.+- `graph_revision`: counter for changes to the normalized retained projection,+ including inactive evidence. It is local to this adapter, not a global graph ID.+- `valid_at`, `known_at`: current UTC coordinates, initially `None`.++For cache identity, distinguish the adapter instance, retained graph revision,+and both time coordinates; do not use the live support version alone.++## Cost and boundaries++Each graph sync normalizes/validates the supplied managed history. Slice selection+scans retained evidence and endpoint lifetimes. PR1 performs its existing update+work and state staging; historical queries recompute a fresh closure and capture+all direct explanations. Retained history grows with evidence revisions. This+implementation does not provide indexed storage-side temporal querying or promise+sublinear update cost.++The adapter does not persist its archive, write conclusions back to the graph,+schedule expiration, modify RETE, support recursive rules, or update RAG prompts+and vector records. Consistency is relative to supplied evidence and fixed rules;+losing support means “not currently derivable,” not “false.”diff --git a/docs/reference/truth_maintenance.md b/docs/reference/truth_maintenance.mdindex f7b0cb48..255a9cd5 100644--- a/docs/reference/truth_maintenance.md+++ b/docs/reference/truth_maintenance.md@@ -149,6 +149,7 @@ previously returned results cannot mutate the session.## Links+- [Temporal Truth Maintenance](/reference/temporal_truth_maintenance) — an opt-in graph adapter for independent valid/known-time slices, expiration and late corrections.- [Reasoning](/reference/reasoning) — the rule engines this session builds on, including the `Rule` representation.- [Context](/reference/context#support-aware-retrieval-truth_filter) — `TruthMaintenanceContextFilter` consumes immutable snapshots to filter retrieved context by active support.- [Ontology](/reference/ontology) — ontology axioms and SHACL constraints.diff --git a/semantica/reasoning/__init__.py b/semantica/reasoning/__init__.pyindex 6005da06..12acf966 100644--- a/semantica/reasoning/__init__.py+++ b/semantica/reasoning/__init__.py@@ -42,6 +42,10 @@ from .temporal_reasoning import (TemporalInterval,TemporalReasoningEngine,)+from .temporal_truth_maintenance import (+ TemporalFactSnapshot,+ TemporalTruthMaintenanceAdapter,+)from .truth_maintenance import TruthMaintenanceSessionfrom .truth_maintenance_types import (Derivation,@@ -89,6 +93,9 @@ __all__ = ["FactExplanation","MaintenanceDelta","TruthMaintenanceSnapshot",+ # Temporal truth maintenance+ "TemporalTruthMaintenanceAdapter",+ "TemporalFactSnapshot",# Explanation"ExplanationGenerator","Explanation",diff --git a/semantica/reasoning/_temporal_support_projection.py b/semantica/reasoning/_temporal_support_projection.pynew file mode 100644index 00000000..10fd19ca--- /dev/null+++ b/semantica/reasoning/_temporal_support_projection.py@@ -0,0 +1,238 @@+"""Normalization and temporal selection for explicitly annotated graph evidence."""++from dataclasses import dataclass, replace+from datetime import datetime, timezone+from typing import Any, Dict, Optional++from ..kg.temporal_model import TemporalBound, parse_temporal_value+from ..kg.temporal_reasoning import TemporalInterval, TemporalReasoningEngine+from ..utils.exceptions import TemporalValidationError, ValidationError+from ._truth_maintenance_validation import parse_atom, validate_fact_text+from .truth_maintenance_types import FactSupport++_BEGINNING = datetime.min.replace(tzinfo=timezone.utc)+_ENGINE = TemporalReasoningEngine()+_MISSING = object()+++def timestamp(value: Any, field: str) -> datetime:+ """Parse an explicit query/bound time, without consulting the wall clock."""+ if value is None or isinstance(value, bool):+ raise TemporalValidationError(f"{field} requires an explicit timestamp")+ try:+ return parse_temporal_value(value)+ except (ValueError, TypeError, OverflowError, OSError) as exc:+ raise TemporalValidationError(f"Invalid {field}") from exc+++def _identifier(value: Any, field: str) -> str:+ if not isinstance(value, str) or not value or value.strip() != value:+ raise ValidationError(f"{field} must be a nonempty, trimmed string")+ return value+++def _end(value: Any, field: str) -> Optional[datetime]:+ if value is None or value is TemporalBound.OPEN or value == "OPEN":+ return None+ return timestamp(value, field)+++@dataclass(frozen=True)+class Window:+ valid_from: datetime+ valid_until: Optional[datetime]+ recorded_at: datetime+ superseded_at: Optional[datetime]++ def active(self, valid_at: datetime, known_at: datetime) -> bool:+ return _ENGINE.active_at(+ TemporalInterval(self.valid_from, self.valid_until or TemporalBound.OPEN),+ valid_at,+ ) and _ENGINE.active_at(+ TemporalInterval(+ self.recorded_at, self.superseded_at or TemporalBound.OPEN+ ),+ known_at,+ )+++@dataclass(frozen=True)+class Evidence:+ support: FactSupport+ source: str+ target: str+ relation_type: Optional[str]+ window: Window+++@dataclass+class Projection:+ entities: Dict[str, Window]+ evidence: Dict[str, Evidence]++ def validate_update(+ self, previous: "Projection", rule_arities: Dict[str, int]+ ) -> None:+ """Retain revision identities and validate even currently inactive facts."""+ if previous.evidence and not previous.entities and self.entities:+ raise ValidationError(+ "Cannot add endpoint constraints to relationship-only history"+ )+ for key, old in previous.entities.items():+ if key not in self.entities:+ raise ValidationError(f"Cannot drop retained entity: {key}")+ _validate_window_revision(old, self.entities[key], key)+ for key, old in previous.evidence.items():+ new = self.evidence.get(key)+ if new is None:+ raise ValidationError(f"Cannot drop retained support: {key}")+ if replace(new, window=old.window) != old:+ raise ValidationError(+ f"Use a new support_id for changed evidence: {key}"+ )+ _validate_window_revision(old.window, new.window, key)+ arities = dict(rule_arities)+ for record in self.evidence.values():+ predicate, terms = parse_atom(record.support.fact)+ arity = len(terms)+ if predicate in arities and arities[predicate] != arity:+ raise ValidationError(f"Conflicting arity for predicate: {predicate}")+ arities[predicate] = arity++ def select(self, valid_at: datetime, known_at: datetime) -> Dict[str, FactSupport]:+ active_entities = {+ key+ for key, window in self.entities.items()+ if window.active(valid_at, known_at)+ }+ return {+ key: record.support+ for key, record in sorted(self.evidence.items())+ if record.window.active(valid_at, known_at)+ and (+ not self.entities+ or (+ record.source in active_entities+ and record.target in active_entities+ )+ )+ }+++def _validate_window_revision(old: Window, new: Window, key: str) -> None:+ if replace(new, superseded_at=old.superseded_at) != old:+ raise ValidationError(f"Cannot rewrite historical temporal fields: {key}")+ if old.superseded_at is not None and old.superseded_at != new.superseded_at:+ raise ValidationError(f"Cannot change a closed transaction interval: {key}")+++def _bound(record: Dict[str, Any], field: str, *, open_ended: bool) -> Any:+ """Resolve one bound from the canonical field and from exported containers.++ ``ContextGraph.to_kg_dict()`` keeps properties other than the valid-time+ bounds inside ``metadata`` (and, for entities, ``properties``), so a bound+ that a caller supplied is only visible there. Duplicates are accepted when+ they denote the same instant and rejected when they disagree.+ """+ resolved: Any = _MISSING+ for container in (record, record.get("metadata"), record.get("properties")):+ if not isinstance(container, dict):+ continue+ value = container.get(field)+ if value is None:+ continue+ parsed = _end(value, field) if open_ended else timestamp(value, field)+ if resolved is not _MISSING and parsed != resolved:+ raise TemporalValidationError(f"Conflicting {field} values")+ resolved = parsed+ return resolved+++def _window(record: Dict[str, Any], *, require_recorded: bool) -> Window:+ start = _bound(record, "valid_from", open_ended=False)+ until = _bound(record, "valid_until", open_ended=True)+ recorded = _bound(record, "recorded_at", open_ended=False)+ superseded = _bound(record, "superseded_at", open_ended=True)+ if require_recorded and recorded is _MISSING:+ raise TemporalValidationError("Managed evidence requires recorded_at")+ window = Window(+ _BEGINNING if start is _MISSING else start,+ None if until is _MISSING else until,+ _BEGINNING if recorded is _MISSING else recorded,+ None if superseded is _MISSING else superseded,+ )+ for lower, upper in (+ (window.valid_from, window.valid_until),+ (window.recorded_at, window.superseded_at),+ ):+ if upper is not None and upper <= lower:+ raise TemporalValidationError("Temporal intervals must have start < end")+ return window+++def _endpoint(relationship: Dict[str, Any], field: str) -> str:+ """Resolve an endpoint from the short key or the canonical exported key.++ ``ContextGraph.to_kg_dict()`` emits ``source_id`` and ``target_id``, while+ hand-written graphs commonly use ``source`` and ``target``. Both are+ accepted; supplying both with different values is rejected rather than+ silently resolved by precedence.+ """+ short = relationship.get(field)+ canonical = relationship.get(f"{field}_id")+ if short is not None and canonical is not None and short != canonical:+ raise ValidationError(f"Conflicting {field} and {field}_id values")+ return _identifier(short if short is not None else canonical, field)+++def normalize_graph(graph: Dict[str, Any]) -> Projection:+ """Copy only explicit evidence and endpoint lifetimes into detached values."""+ if not isinstance(graph, dict):+ raise ValidationError("graph must be an entities/relationships dictionary")+ entities = graph.get("entities", [])+ relationships = graph.get("relationships", [])+ if not isinstance(entities, list) or not isinstance(relationships, list):+ raise ValidationError("entities and relationships must be lists")+ projection = Projection({}, {})+ for entity in entities:+ if not isinstance(entity, dict):+ raise ValidationError("Each entity must be a dictionary")+ key = _identifier(entity.get("id"), "entity id")+ if key in projection.entities:+ raise ValidationError(f"Duplicate entity id: {key}")+ projection.entities[key] = _window(entity, require_recorded=False)+ for relationship in relationships:+ if not isinstance(relationship, dict):+ raise ValidationError("Each relationship must be a dictionary")+ metadata = relationship.get("metadata", {})+ if not isinstance(metadata, dict):+ raise ValidationError("Relationship metadata must be a dictionary")+ if "truth_maintenance" not in metadata:+ continue+ annotation = metadata["truth_maintenance"]+ if not isinstance(annotation, dict) or set(annotation) != {+ "support_id",+ "fact",+ }:+ raise ValidationError("truth_maintenance requires support_id and fact")+ support_id = _identifier(annotation["support_id"], "support_id")+ if support_id in projection.evidence:+ raise ValidationError(f"Duplicate support_id: {support_id}")+ support = FactSupport(support_id, validate_fact_text(annotation["fact"]))+ source = _endpoint(relationship, "source")+ target = _endpoint(relationship, "target")+ if projection.entities and (+ source not in projection.entities or target not in projection.entities+ ):+ raise ValidationError(f"Unknown endpoint for support {support_id}")+ relation_type = relationship.get("type")+ if relation_type is not None:+ relation_type = _identifier(relation_type, "relationship type")+ projection.evidence[support_id] = Evidence(+ support,+ source,+ target,+ relation_type,+ _window(relationship, require_recorded=True),+ )+ return projectiondiff --git a/semantica/reasoning/temporal_truth_maintenance.py b/semantica/reasoning/temporal_truth_maintenance.pynew file mode 100644index 00000000..d970efb8--- /dev/null+++ b/semantica/reasoning/temporal_truth_maintenance.py@@ -0,0 +1,148 @@+"""Opt-in projection of bitemporal graph evidence into managed reasoning."""++from copy import deepcopy+from dataclasses import dataclass+from datetime import datetime+from typing import Any, Dict, FrozenSet, Iterable, Optional, Tuple++from ..utils.exceptions import ValidationError+from ._temporal_support_projection import Projection, normalize_graph, timestamp+from ._truth_maintenance_validation import (+ build_rule_snapshots,+ validate_fact_text,+)+from .reasoner import Rule+from .truth_maintenance import TruthMaintenanceSession+from .truth_maintenance_types import (+ FactExplanation,+ FactSupport,+ MaintenanceDelta,+)++__all__ = ["TemporalTruthMaintenanceAdapter", "TemporalFactSnapshot"]+++@dataclass(frozen=True)+class TemporalFactSnapshot:+ """Detached closure for one pair of temporal coordinates and graph revision."""++ valid_at: datetime+ known_at: datetime+ graph_revision: int+ facts: FrozenSet[str]+ active_supports: Tuple[FactSupport, ...]+ explanations: Tuple[FactExplanation, ...]++ def explain(self, fact: str) -> FactExplanation:+ canonical = validate_fact_text(fact)+ for explanation in self.explanations:+ if explanation.fact == canonical:+ return explanation+ return FactExplanation(canonical, False, (), ())+++class TemporalTruthMaintenanceAdapter:+ """Maintain a live closure over explicitly annotated temporal relationships.++ Both ``valid_at`` (when a fact applies) and ``known_at`` (when its evidence+ was known) are explicit. Intervals are half-open with full datetime+ precision. Calls must be serialized by the caller. No background scheduler,+ storage client, graph mutation, or language-model call is performed.+ """++ def __init__(self, *, rules: Iterable[Rule]):+ if isinstance(rules, (str, bytes)):+ raise ValidationError("rules must be an iterable of Rule objects")+ try:+ self._rules = deepcopy(tuple(rules))+ except TypeError as exc:+ raise ValidationError("rules must be an iterable of Rule objects") from exc+ self._session = TruthMaintenanceSession(rules=self._rules)+ _, self._rule_arities = build_rule_snapshots(self._rules)+ self._projection = Projection({}, {})+ self._active_supports: Dict[str, FactSupport] = {}+ self._graph_revision = 0+ self._valid_at: Optional[datetime] = None+ self._known_at: Optional[datetime] = None++ @property+ def facts(self) -> FrozenSet[str]:+ return self._session.facts++ @property+ def version(self) -> int:+ """PR1 support-set version; a clock-only change need not increment it."""+ return self._session.version++ @property+ def graph_revision(self) -> int:+ """Revision of retained normalized evidence, including inactive records."""+ return self._graph_revision++ @property+ def valid_at(self) -> Optional[datetime]:+ return self._valid_at++ @property+ def known_at(self) -> Optional[datetime]:+ return self._known_at++ def explain(self, fact: str) -> FactExplanation:+ return self._session.explain(fact)++ def sync(+ self,+ graph: Dict[str, Any],+ *,+ valid_at: Any,+ known_at: Any,+ ) -> MaintenanceDelta:+ """Ingest evidence history and atomically update the selected supports."""+ projection = normalize_graph(graph)+ projection.validate_update(self._projection, self._rule_arities)+ return self._apply(projection, valid_at=valid_at, known_at=known_at)++ def advance(self, *, valid_at: Any, known_at: Any) -> MaintenanceDelta:+ """Explicitly move the live temporal coordinates over retained evidence."""+ return self._apply(self._projection, valid_at=valid_at, known_at=known_at)++ def _apply(+ self,+ projection: Projection,+ *,+ valid_at: Any,+ known_at: Any,+ ) -> MaintenanceDelta:+ valid_time = timestamp(valid_at, "valid_at")+ known_time = timestamp(known_at, "known_at")+ selected = projection.select(valid_time, known_time)+ delta = self._session.apply(+ assertions=[+ value+ for key, value in selected.items()+ if key not in self._active_supports+ ],+ retractions=sorted(set(self._active_supports) - set(selected)),+ )+ self._graph_revision += projection != self._projection+ self._projection = projection+ self._active_supports = selected+ self._valid_at = valid_time+ self._known_at = known_time+ return delta++ def query_at(self, *, valid_at: Any, known_at: Any) -> TemporalFactSnapshot:+ """Recompute a historical closure without changing the live session."""+ valid_time = timestamp(valid_at, "valid_at")+ known_time = timestamp(known_at, "known_at")+ selected = self._projection.select(valid_time, known_time)+ historical = TruthMaintenanceSession(rules=self._rules)+ historical.apply(assertions=selected.values())+ return TemporalFactSnapshot(+ valid_time,+ known_time,+ self._graph_revision,+ historical.facts,+ tuple(selected.values()),+ tuple(historical.explain(fact) for fact in sorted(historical.facts)),+ )diff --git a/tests/reasoning/test_temporal_truth_maintenance.py b/tests/reasoning/test_temporal_truth_maintenance.pynew file mode 100644index 00000000..7f6472c0--- /dev/null+++ b/tests/reasoning/test_temporal_truth_maintenance.py@@ -0,0 +1,404 @@+"""Public temporal adapter behavior, using real PR1 and temporal primitives."""++from copy import deepcopy+from dataclasses import FrozenInstanceError+from datetime import datetime, timezone++import pytest++from semantica import reasoning+from semantica.reasoning import FactSupport, Rule+from semantica.utils.exceptions import ProcessingError, ValidationError+++def at(day):+ return datetime(2026, 9, day, tzinfo=timezone.utc)+++def evidence(support_id="hr-v1", fact="Employed(Alice)", **temporal):+ return {+ "source": "alice",+ "target": "acme",+ "type": "EMPLOYED_BY",+ "valid_from": at(1),+ "valid_until": at(30),+ "recorded_at": at(1),+ "metadata": {+ "truth_maintenance": {"support_id": support_id, "fact": fact},+ },+ **temporal,+ }+++def graph(*records):+ return {+ "entities": [{"id": "alice"}, {"id": "acme"}],+ "relationships": list(records),+ }+++def adapter():+ return reasoning.TemporalTruthMaintenanceAdapter(+ rules=[Rule("eligibility", "Eligibility", ["Employed(?x)"], "Eligible(?x)")]+ )+++def test_expiration_retracts_derived_facts_at_exclusive_end():+ managed = adapter()+ source = graph(evidence(valid_until=at(15)))+ original = deepcopy(source)+ delta = managed.sync(source, valid_at=at(14), known_at=at(14))+ assert delta.added_facts == frozenset({"Employed(Alice)", "Eligible(Alice)"})+ assert managed.explain("Eligible(Alice)").active++ delta = managed.advance(valid_at=at(15), known_at=at(15))+ assert delta.removed_supports == (FactSupport("hr-v1", "Employed(Alice)"),)+ assert delta.removed_facts == frozenset({"Employed(Alice)", "Eligible(Alice)"})+ assert managed.facts == frozenset()+ assert managed.graph_revision == 1+ assert source == original+++def test_late_correction_distinguishes_valid_time_from_known_time():+ managed = adapter()+ old = evidence()+ managed.sync(graph(old), valid_at=at(15), known_at=at(15))+ corrected = graph(+ {**old, "superseded_at": at(20)},+ evidence("hr-v2", valid_until=at(10), recorded_at=at(20)),+ )+ delta = managed.sync(corrected, valid_at=at(15), known_at=at(20))+ assert delta.removed_facts == frozenset({"Employed(Alice)", "Eligible(Alice)"})+ live_state = (managed.facts, managed.version, managed.valid_at, managed.known_at)++ then = managed.query_at(valid_at=at(15), known_at=at(15))+ hindsight = managed.query_at(valid_at=at(15), known_at=at(20))+ assert then.facts == frozenset({"Employed(Alice)", "Eligible(Alice)"})+ assert then.explain("Eligible(Alice)").derivations[0].premises == (+ "Employed(Alice)",+ )+ assert then.active_supports == (FactSupport("hr-v1", "Employed(Alice)"),)+ assert hindsight.facts == frozenset()+ assert not hindsight.explain("Eligible(Alice)").active+ assert then.graph_revision == hindsight.graph_revision == 2+ assert live_state == (+ managed.facts,+ managed.version,+ managed.valid_at,+ managed.known_at,+ )+++def test_source_replacement_is_one_batch_without_fact_churn():+ managed = adapter()+ source = graph(+ evidence(superseded_at=at(20)),+ evidence("hr-v2", recorded_at=at(20)),+ )+ managed.sync(source, valid_at=at(10), known_at=at(19))+ previous_version = managed.version+ delta = managed.advance(valid_at=at(10), known_at=at(20))+ assert not delta.added_facts and not delta.removed_facts+ assert delta.removed_supports == (FactSupport("hr-v1", "Employed(Alice)"),)+ assert delta.added_supports == (FactSupport("hr-v2", "Employed(Alice)"),)+ assert managed.version == previous_version + 1+ assert managed.explain("Employed(Alice)").explicit_support_ids == ("hr-v2",)+++def test_an_independent_source_preserves_conclusion_until_both_expire():+ managed = adapter()+ managed.sync(+ graph(evidence(valid_until=at(10)), evidence("other", valid_until=at(20))),+ valid_at=at(9),+ known_at=at(9),+ )+ delta = managed.advance(valid_at=at(10), known_at=at(10))+ assert not delta.removed_facts+ assert managed.explain("Employed(Alice)").explicit_support_ids == ("other",)+ managed.advance(valid_at=at(20), known_at=at(20))+ assert not managed.facts+++def state(managed):+ return (+ managed.facts,+ managed.version,+ managed.graph_revision,+ managed.valid_at,+ managed.known_at,+ managed.query_at(valid_at=at(10), known_at=at(10)),+ )+++ "change",+ [+ "drop",+ "fact",+ "start",+ "end",+ "recorded",+ "source",+ "relation",+ "entity",+ ],+)+def test_existing_evidence_cannot_be_erased_or_rewritten(change):+ managed = adapter()+ source = graph(evidence())+ managed.sync(source, valid_at=at(10), known_at=at(10))+ before = state(managed)+ revised = deepcopy(source)+ record = revised["relationships"][0]+ if change == "drop":+ revised["relationships"] = []+ elif change == "fact":+ record["metadata"]["truth_maintenance"]["fact"] = "Employed(Bob)"+ elif change == "start":+ record["valid_from"] = at(2)+ elif change == "end":+ record["valid_until"] = at(12)+ elif change == "recorded":+ record["recorded_at"] = at(2)+ elif change == "source":+ record["source"] = "acme"+ elif change == "relation":+ record["type"] = "OTHER"+ elif change == "entity":+ revised["entities"] = []+ with pytest.raises(ValidationError):+ managed.sync(revised, valid_at=at(20), known_at=at(20))+ assert state(managed) == before+++def test_closed_transaction_interval_cannot_be_reopened():+ managed = adapter()+ source = graph(evidence(superseded_at=at(20)))+ managed.sync(source, valid_at=at(10), known_at=at(21))+ with pytest.raises(ValidationError):+ managed.sync(graph(evidence()), valid_at=at(10), known_at=at(21))+ assert not managed.facts+ assert managed.query_at(valid_at=at(10), known_at=at(19)).facts+++def test_inactive_records_are_checked_for_rule_arity_and_for_each_other():+ for rules, records in [+ ([Rule("r", "r", ["A(?x)"], "B(?x)")], [evidence(fact="A(x, y)")]),+ ([], [evidence(fact="A(x)"), evidence("other", "A(x, y)")]),+ ]:+ managed = reasoning.TemporalTruthMaintenanceAdapter(rules=rules)+ with pytest.raises(ValidationError):+ managed.sync(graph(*records), valid_at=at(1), known_at="2020-01-01")+ assert managed.graph_revision == managed.version == 0+++ "field,value",+ [+ ("recorded_at", None),+ ("recorded_at", True),+ ("recorded_at", "not-a-date"),+ ("valid_until", at(1)),+ ("valid_until", "2026-08-01"),+ ("superseded_at", at(1)),+ ("valid_from", False),+ ("valid_until", float("nan")),+ ],+)+def test_invalid_time_in_inactive_evidence_does_not_publish(field, value):+ managed = adapter()+ with pytest.raises(ValidationError):+ managed.sync(+ graph(evidence(**{field: value})), valid_at=at(1), known_at="2020-01-01"+ )+ assert managed.version == managed.graph_revision == 0+ assert managed.valid_at is managed.known_at is None+++ "bad_graph",+ [+ None,+ [],+ {"entities": None},+ {"relationships": "rows"},+ graph(evidence(), evidence()),+ {"entities": [{"id": "a"}, {"id": "a"}]},+ {"entities": [{"id": "missing"}], "relationships": [evidence()]},+ graph({**evidence(), "metadata": {"truth_maintenance": None}}),+ graph(evidence(fact="Employed(?x)")),+ graph(evidence(support_id=" ")),+ ],+)+def test_malformed_graph_is_rejected_without_losing_live_state(bad_graph):+ managed = adapter()+ managed.sync(graph(evidence()), valid_at=at(10), known_at=at(10))+ before = state(managed)+ with pytest.raises(ValidationError):+ managed.sync(bad_graph, valid_at=at(11), known_at=at(11))+ assert state(managed) == before+++def test_endpoint_expiry_retracts_support_even_when_edge_is_still_valid():+ managed = adapter()+ source = graph(evidence())+ source["entities"][0]["valid_until"] = at(12)+ managed.sync(source, valid_at=at(11), known_at=at(11))+ assert managed.facts+ managed.advance(valid_at=at(12), known_at=at(12))+ assert not managed.facts+ assert managed.query_at(valid_at=at(11), known_at=at(15)).facts+++def test_endpoint_known_time_is_also_required():+ managed = adapter()+ source = graph(evidence())+ source["entities"][1]["recorded_at"] = at(10)+ managed.sync(source, valid_at=at(11), known_at=at(9))+ assert not managed.facts+ managed.advance(valid_at=at(11), known_at=at(10))+ assert managed.facts+++def test_full_precision_and_timezone_normalization_at_boundary():+ managed = adapter()+ start = "2026-09-10T08:00:00.000001+08:00"+ end = "2026-09-10T00:00:00.000003Z"+ managed.sync(+ graph(evidence(valid_from=start, valid_until=end)),+ valid_at=start,+ known_at=at(10),+ )+ assert managed.valid_at == at(10).replace(microsecond=1)+ managed.advance(valid_at=at(10).replace(microsecond=2), known_at=at(10))+ assert managed.facts+ managed.advance(valid_at=end, known_at=at(10))+ assert not managed.facts+++def test_rules_input_graph_and_historical_results_are_detached():+ rule = Rule("r", "r", ["Employed(?x)"], "Eligible(?x)")+ managed = reasoning.TemporalTruthMaintenanceAdapter(rules=iter([rule]))+ source = graph(evidence())+ managed.sync(source, valid_at=at(10), known_at=at(10))+ snapshot = managed.query_at(valid_at=at(10), known_at=at(10))+ source["relationships"][0]["metadata"]["truth_maintenance"]["fact"] = "Changed(x)"+ rule.conclusion = "Changed(?x)"+ managed.advance(valid_at=at(30), known_at=at(30))+ assert snapshot.facts == frozenset({"Employed(Alice)", "Eligible(Alice)"})+ assert managed.query_at(valid_at=at(10), known_at=at(10)) == snapshot+ with pytest.raises(FrozenInstanceError):+ snapshot.active_supports[0].fact = "Changed(x)"+++def test_source_revision_changes_without_live_support_version_change():+ managed = adapter()+ original = evidence()+ managed.sync(graph(original), valid_at=at(10), known_at=at(10))+ before = managed.version+ delta = managed.sync(+ graph(original, evidence("future", recorded_at=at(20))),+ valid_at=at(11),+ known_at=at(11),+ )+ assert managed.version == before+ assert managed.graph_revision == 2+ assert not delta.added_facts and not delta.added_supports+ assert managed.valid_at == managed.known_at == at(11)+ managed.sync(+ graph(original, evidence("future", recorded_at=at(20))),+ valid_at=at(11),+ known_at=at(11),+ )+ assert managed.graph_revision == 2+++def test_failed_reasoning_batch_rolls_back_projection_clocks_and_history(monkeypatch):+ managed = adapter()+ source = graph(evidence())+ managed.sync(source, valid_at=at(10), known_at=at(10))+ before = state(managed)++ def fail_match(*args):+ raise RuntimeError("injected matcher failure")++ with monkeypatch.context() as patch:+ patch.setattr(managed._session, "_match_rule", fail_match)+ with pytest.raises(ProcessingError):+ managed.sync(+ graph(evidence(), evidence("bob", "Employed(Bob)")),+ valid_at=at(11),+ known_at=at(11),+ )+ assert state(managed) == before+ managed.sync(+ graph(evidence(), evidence("bob", "Employed(Bob)")),+ valid_at=at(11),+ known_at=at(11),+ )+ assert "Eligible(Bob)" in managed.facts+++def test_unannotated_edges_are_not_automatically_promoted_to_facts():+ managed = adapter()+ managed.sync(+ graph({"source": "alice", "target": "acme", "type": "EMPLOYED_BY"}),+ valid_at=at(10),+ known_at=at(10),+ )+ assert not managed.facts+++def test_relationship_only_graph_and_canonical_fact_are_supported():+ managed = adapter()+ managed.sync(+ {"relationships": [evidence(fact=" Employed( Alice ) ")]},+ valid_at=at(10),+ known_at=at(10),+ )+ assert managed.explain("Employed(Alice)").explicit_support_ids == ("hr-v1",)++[email protected]("value", [None, True, "bad-time"])+def test_invalid_query_coordinates_cannot_move_live_state(value):+ managed = adapter()+ managed.sync(graph(evidence()), valid_at=at(10), known_at=at(10))+ before = state(managed)+ with pytest.raises(ValidationError):+ managed.advance(valid_at=value, known_at=at(10))+ with pytest.raises(ValidationError):+ managed.query_at(valid_at=at(10), known_at=value)+ assert state(managed) == before+++def test_adding_endpoint_lifetimes_cannot_reinterpret_relationship_only_history():+ managed = adapter()+ managed.sync({"relationships": [evidence()]}, valid_at=at(10), known_at=at(10))+ revised = graph(evidence())+ revised["entities"][0]["valid_until"] = at(5)+ with pytest.raises(ValidationError):+ managed.sync(revised, valid_at=at(10), known_at=at(10))+ assert managed.query_at(valid_at=at(10), known_at=at(10)).facts++[email protected]("rules", [None, 1, "A(x)"])+def test_invalid_rule_iterable_raises_validation_error(rules):+ with pytest.raises(ValidationError):+ reasoning.TemporalTruthMaintenanceAdapter(rules=rules)+++def test_advancing_backward_reactivates_original_source_without_losing_history():+ managed = adapter()+ managed.sync(graph(evidence(valid_until=at(10))), valid_at=at(9), known_at=at(9))+ managed.advance(valid_at=at(10), known_at=at(10))+ delta = managed.advance(valid_at=at(9), known_at=at(9))+ assert delta.added_supports == (FactSupport("hr-v1", "Employed(Alice)"),)+ assert managed.graph_revision == 1+++def test_empty_history_has_no_implicit_wall_clock_or_facts():+ managed = adapter()+ snapshot = managed.query_at(valid_at=at(1), known_at=at(1))+ assert not snapshot.facts and not snapshot.active_supports+ assert managed.valid_at is managed.known_at is None+ assert managed.version == managed.graph_revision == 0diff --git a/tests/reasoning/test_temporal_truth_maintenance_context_graph.py b/tests/reasoning/test_temporal_truth_maintenance_context_graph.pynew file mode 100644index 00000000..245bda53--- /dev/null+++ b/tests/reasoning/test_temporal_truth_maintenance_context_graph.py@@ -0,0 +1,124 @@+"""Integration: annotated ``ContextGraph`` exports are accepted verbatim.++``ContextGraph.to_kg_dict()`` emits ``source_id``/``target_id`` and keeps+non valid-time bounds inside ``metadata`` (and ``properties`` for entities), so+these tests pin the adapter against the real export instead of hand-written+dictionaries only.+"""++from datetime import datetime, timezone++import pytest++from semantica.reasoning import Rule, TemporalTruthMaintenanceAdapter+from semantica.utils.exceptions import ValidationError++context_graph = pytest.importorskip("semantica.context.context_graph")+ContextGraph = context_graph.ContextGraph+++def at(day, month=9):+ return datetime(2026, month, day, tzinfo=timezone.utc)+++def adapter():+ return TemporalTruthMaintenanceAdapter(+ rules=[Rule("eligibility", "Eligibility", ["Employed(?x)"], "Eligible(?x)")]+ )+++def exported(*, employer_recorded_at=at(1), valid_until=at(30)):+ graph = ContextGraph()+ graph.add_node(+ "alice", "Person", content="Alice", valid_from=at(1), recorded_at=at(1)+ )+ graph.add_node(+ "acme",+ "Company",+ content="Acme",+ valid_from=at(1),+ recorded_at=employer_recorded_at,+ )+ graph.add_edge(+ "alice",+ "acme",+ "EMPLOYED_BY",+ valid_from=at(1),+ valid_until=valid_until,+ recorded_at=at(1),+ truth_maintenance={"support_id": "hr-v1", "fact": "Employed(Alice)"},+ )+ return graph.to_kg_dict()+++def test_export_uses_canonical_endpoint_keys_and_nested_bounds():+ record = exported()+ relationship = record["relationships"][0]+ entity = record["entities"][0]+ assert "source" not in relationship and relationship["source_id"] == "alice"+ assert "target" not in relationship and relationship["target_id"] == "acme"+ assert "recorded_at" not in relationship+ assert relationship["metadata"]["recorded_at"] == at(1)+ assert "recorded_at" not in entity+ assert entity["properties"]["recorded_at"] == at(1)+++def test_exported_context_graph_can_sync_without_manual_rewriting():+ managed = adapter()+ managed.sync(exported(), valid_at=at(10), known_at=at(10))+ assert managed.facts == frozenset({"Employed(Alice)", "Eligible(Alice)"})+ assert managed.explain("Employed(Alice)").explicit_support_ids == ("hr-v1",)+++def test_exported_relationship_expiry_retracts_derived_facts():+ managed = adapter()+ managed.sync(exported(), valid_at=at(10), known_at=at(10))+ managed.advance(valid_at=at(30), known_at=at(30))+ assert not managed.facts+ assert managed.query_at(valid_at=at(10), known_at=at(30)).facts+++def test_exported_relationship_known_time_start_is_honoured():+ managed = adapter()+ managed.sync(exported(), valid_at=at(10), known_at=at(31, month=8))+ assert not managed.facts+ managed.advance(valid_at=at(10), known_at=at(1))+ assert managed.facts+++def test_exported_endpoint_known_time_gates_selection_independently():+ managed = adapter()+ managed.sync(exported(employer_recorded_at=at(5)), valid_at=at(10), known_at=at(3))+ assert not managed.facts+ managed.advance(valid_at=at(10), known_at=at(5))+ assert managed.facts+++def test_conflicting_endpoint_keys_are_rejected():+ record = exported()+ record["relationships"][0]["source"] = "bob"+ with pytest.raises(ValidationError, match="Conflicting source"):+ adapter().sync(record, valid_at=at(10), known_at=at(10))+++def test_matching_duplicate_endpoint_keys_are_accepted():+ record = exported()+ record["relationships"][0]["source"] = "alice"+ managed = adapter()+ managed.sync(record, valid_at=at(10), known_at=at(10))+ assert managed.facts+++def test_conflicting_duplicate_temporal_bounds_are_rejected():+ record = exported()+ record["relationships"][0]["recorded_at"] = at(2)+ with pytest.raises(ValidationError, match="Conflicting recorded_at"):+ adapter().sync(record, valid_at=at(10), known_at=at(10))+++def test_matching_duplicate_temporal_bounds_are_accepted():+ record = exported()+ record["relationships"][0]["recorded_at"] = at(1)+ managed = adapter()+ managed.sync(record, valid_at=at(10), known_at=at(10))+ assert managed.factsdiff --git a/tests/reasoning/test_temporal_truth_maintenance_differential.py b/tests/reasoning/test_temporal_truth_maintenance_differential.pynew file mode 100644index 00000000..c4f81e6c--- /dev/null+++ b/tests/reasoning/test_temporal_truth_maintenance_differential.py@@ -0,0 +1,142 @@+"""Temporal update sequences checked against integer-time selection + full closure.++The oracle never calls production temporal parsers/interval predicates. PR1's+independent inference oracle is tested separately; here a fresh PR1 session+checks that each projected update equals full recomputation for that slice.+"""++import random+from copy import deepcopy+from datetime import datetime, timedelta, timezone++import pytest++from semantica.reasoning import (+ FactSupport,+ Rule,+ TemporalTruthMaintenanceAdapter,+ TruthMaintenanceSession,+)++EPOCH = datetime(2026, 9, 1, tzinfo=timezone.utc)+++def moment(day):+ return EPOCH + timedelta(days=day)+++def source_graph(rows):+ return {+ "entities": [+ {"id": "person", "valid_from": moment(0), "valid_until": moment(25)},+ {"id": "org", "recorded_at": moment(0)},+ ],+ "relationships": [+ {+ "source": "person",+ "target": "org",+ "type": "ASSERTS",+ "valid_from": moment(row["start"]),+ "valid_until": moment(row["end"]),+ "recorded_at": moment(row["known"]),+ "superseded_at": (+ None if row["closed"] is None else moment(row["closed"])+ ),+ "metadata": {+ "truth_maintenance": {+ "support_id": row["id"],+ "fact": row["fact"],+ }+ },+ }+ for row in rows+ ],+ }+++def oracle(rows, rules, valid, known):+ selected = {+ row["id"]: FactSupport(row["id"], row["fact"])+ for row in rows+ if 0 <= valid < 25+ and known >= 0+ and row["start"] <= valid < row["end"]+ and row["known"] <= known+ and (row["closed"] is None or known < row["closed"])+ }+ rebuilt = TruthMaintenanceSession(rules=rules)+ rebuilt.apply(assertions=selected.values())+ return selected, rebuilt++[email protected]("seed", range(12))+def test_live_and_historical_closures_match_independent_time_selection(seed):+ rng = random.Random(seed)+ rules = [+ Rule("ad", "ad", ["A(?x)"], "D(?x)"),+ Rule("bcd", "bcd", ["B(?x)", "C(?x)"], "D(?x)"),+ Rule("de", "de", ["D(?x)"], "E(?x)"),+ ]+ managed = TemporalTruthMaintenanceAdapter(rules=rules)+ rows = []+ old_supports, old_facts = {}, frozenset()+ version = 0+ for step in range(1, 31):+ # Some transactions close a retained record and introduce a revision;+ # others add independent evidence or only move the live coordinates.+ closable = [+ row for row in rows if row["closed"] is None and row["known"] < step+ ]+ if closable and rng.random() < 0.5:+ rng.choice(closable)["closed"] = step+ if not rows or rng.random() < 0.75:+ start = rng.randrange(0, 23)+ rows.append(+ {+ "id": f"s{step}",+ "fact": f"{rng.choice('ABCD')}({rng.choice('xy')})",+ "start": start,+ "end": start + rng.randrange(1, 12),+ "known": step,+ "closed": None,+ }+ )+ valid = rng.randrange(0, 35)+ source = source_graph(rows)+ unchanged_source = deepcopy(source)+ delta = managed.sync(source, valid_at=moment(valid), known_at=moment(step))+ expected_supports, rebuilt = oracle(rows, rules, valid, step)+ if old_supports != expected_supports:+ version += 1+ assert delta.version == managed.version == version, (seed, step)+ assert managed.facts == rebuilt.facts, (seed, step)+ assert delta.added_facts == rebuilt.facts - old_facts+ assert delta.removed_facts == old_facts - rebuilt.facts+ assert set(delta.added_supports) == set(expected_supports.values()) - set(+ old_supports.values()+ )+ assert set(delta.removed_supports) == set(old_supports.values()) - set(+ expected_supports.values()+ )+ for fact in managed.facts:+ assert managed.explain(fact) == rebuilt.explain(fact)+ assert source == unchanged_source++ historical_valid, historical_known = rng.randrange(0, 35), rng.randrange(+ 0, step + 1+ )+ historical = managed.query_at(+ valid_at=moment(historical_valid), known_at=moment(historical_known)+ )+ expected_history, history_rebuilt = oracle(+ rows, rules, historical_valid, historical_known+ )+ assert historical.facts == history_rebuilt.facts+ assert set(historical.active_supports) == set(expected_history.values())+ for fact in historical.facts:+ assert historical.explain(fact) == history_rebuilt.explain(fact)+ assert managed.facts == rebuilt.facts+ assert managed.version == version+ assert managed.valid_at == moment(valid)+ assert managed.known_at == moment(step)+ old_supports, old_facts = expected_supports, rebuilt.facts