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(context): filter retrieved context by active fact and source support (#1556)
cxzg007d46529adb316
diff --git a/docs/reference/context.md b/docs/reference/context.mdindex 96be2fa3..af03997b 100644--- a/docs/reference/context.md+++ b/docs/reference/context.md@@ -857,6 +857,143 @@ for r in results:```+## Support-Aware Retrieval (`truth_filter`)++Cached vector or memory content can outlive the evidence that originally+supported it. `ContextRetriever.retrieve(..., truth_filter=...)` accepts an+opt-in `TruthMaintenanceContextFilter` that removes candidates whose declared+dependencies are no longer supported, **before** ranking, while the stored+records themselves are never modified.++The example below runs standalone with no model, database, or network —+only `semantica` itself:++```python+from semantica.context import ContextRetriever, TruthMaintenanceContextFilter+from semantica.reasoning import FactSupport, Rule, TruthMaintenanceSession++# A tiny read-only store standing in for any real vector backend.+class StaticVectorStore:+ def __init__(self, rows):+ self.rows = [dict(row) for row in rows]++ def search(self, *, query, limit):+ return self.rows[:limit]++def annotated_row(identifier, fact, score, text):+ """One record whose content depends on one live fact."""+ return {+ "id": identifier,+ "score": score,+ "content": text,+ "metadata": {+ "truth_maintenance": {+ "schema_version": 1,+ "session_id": "employment-session-1",+ "required_facts": [fact],+ "required_support_ids": [],+ }+ },+ }++rules = [+ Rule(+ rule_id="employment",+ name="employment",+ conditions=["Employed(?x)"],+ conclusion="Eligible(?x)",+ ),+]+session = TruthMaintenanceSession(rules=rules)+session.apply(assertions=[FactSupport("v1", "Employed(Alice)")])++store = StaticVectorStore([+ annotated_row("cached", "Eligible(Alice)", 0.9, "Alice is eligible"),+])+retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+gate = TruthMaintenanceContextFilter(session, session_id="employment-session-1")++checked = retriever.retrieve("eligibility", truth_filter=gate)+assert [result.content for result in checked] == ["Alice is eligible"]+assert (+ checked[0].metadata["truth_maintenance_validation"]["version"]+ == session.version+)++# The supporting evidence is withdrawn. The vector record stays stored,+# but it no longer reaches the caller through the checked retrieval.+session.apply(retractions=["v1"])+checked = retriever.retrieve("eligibility", truth_filter=gate)+assert checked == []+assert store.rows[0]["content"] == "Alice is eligible" # record untouched+```++### Manual annotation semantics++The filter only validates what the application explicitly wrote into store+metadata. It never infers dependencies, and it never annotates records on+your behalf:++- Each candidate must carry `metadata["truth_maintenance"]` with exactly four+ keys: `schema_version` (currently `1`), `session_id` (must equal the+ filter's `session_id`), `required_facts`, and `required_support_ids`.+ At least one fact or support ID must be declared.+- A candidate is kept only if every entry of `required_facts` is in the+ snapshot's `facts` **and** every entry of `required_support_ids` is in the+ snapshot's active supports. Unannotated candidates and candidates with malformed annotations+ are removed whole — a record ID or node ID is never a trust signal.++### Source-specific citations++Two records may assert the same conclusion but cite different sources.+`required_support_ids` binds each record to the evidence it actually used, so+withdrawing one support invalidates only the records citing it, while records+backed by an alternative derivation or an explicit support are kept.++### Graph bundles++For candidates retrieved from a `ContextGraph`, the root record **and** every+member of `related_entities` / `related_relationships` must carry the same+annotation shape on their own `metadata`. If the root or any attachment is+unsupported, the entire candidate is excluded — a result never keeps its prose+while silently dropping a stale attachment.++### Behavior details++- Filtering happens before ranking and before the legacy merge: a+ high-scoring stale record cannot crowd out valid lower-scoring records,+ and dependency metadata survives merging.+- Survivors are returned as deep copies stamped with+ `metadata["truth_maintenance_validation"]` (`session_id`, `version`).+ Original candidates and stored records are never modified.+- Each call validates against one immutable snapshot; if the session commits+ a new version while retrieval is in flight, `retrieve` raises+ `ProcessingError` instead of returning mixed-version results.+- Vector, memory, and graph sources are filtered in the same pass: construct+ the retriever with `memory_store=` or `knowledge_graph=` and pass+ `truth_filter=` to `retrieve`, or to the `search`, `vector_search`, and+ `graph_search` delegates (they forward to `retrieve`). `memory_search`+ bypasses `retrieve` and does **not** apply the filter — use `retrieve` when+ memory results must be grounded.++### Unsupported entry points++The filter is supported only by `ContextRetriever.retrieve(mode="local", ...)`+(the default mode) and delegates that use that path. Passing `truth_filter` to+`retrieve` with `mode="global"`, `"drift"`, or `"hybrid"` raises `ValidationError`+before retrieval starts. Those modes and direct `retrieve_global` /+`retrieve_drift` calls are outside the dependency-validation guarantee.++`truth_filter` is intentionally **not** accepted on `AgentContext.retrieve`,+`AgentContext.query_with_reasoning`, or `ContextRetriever.query_with_reasoning`+— passing it there raises `ValidationError` immediately. Assemble the+verified context yourself with `ContextRetriever.retrieve(...,+truth_filter=...)` and feed it to the model.++See [Truth Maintenance](/reference/truth_maintenance) for the session model+behind the filter.++## Data Structures<AccordionGroup>diff --git a/docs/reference/truth_maintenance.md b/docs/reference/truth_maintenance.mdindex 4295768f..f7b0cb48 100644--- a/docs/reference/truth_maintenance.md+++ b/docs/reference/truth_maintenance.md@@ -113,14 +113,26 @@ Returns a `FactExplanation` for the current state:- `facts`: frozenset of all currently believed facts (explicit plus derived).- `version`: the commit counter described above.+- `snapshot()`: returns a `TruthMaintenanceSnapshot` — a frozen dataclass+ with `version`, `facts`, and `active_supports` (tuple sorted by support ID).+ The snapshot is a full detached copy: later `apply()` batches never change+ an existing snapshot.-Returned snapshots (`MaintenanceDelta`, `FactExplanation`, `Derivation`) are frozen dataclasses with immutable collections; mutating caller-owned rules or previously returned results cannot mutate the session.+All read-only views (`facts`, `version`, `snapshot()`, `explain()`) leave the+session state unchanged. Returned snapshots (`MaintenanceDelta`,+`FactExplanation`, `Derivation`, `TruthMaintenanceSnapshot`) are frozen+dataclasses with immutable collections; mutating caller-owned rules or+previously returned results cannot mutate the session.## Cost Model-- **Deletion propagation** and **affected-rule matching** are incremental: a deletion-only batch uses dependency indexes without rescanning all rules; insertions reevaluate only rules reachable from newly active predicates.-- **Staging copies the whole session state** per `apply()` batch to guarantee atomic commits, and the session retains the **support catalog in memory** for the session lifetime (including withdrawn supports, so IDs stay bound).+- **Deletion propagation** and **affected-rule matching** are targeted: a deletion-only batch uses dependency indexes to compute the affected fact set, then re-matches only the rules whose body predicates intersect that set (the affectedness scan itself walks the rule list, so cost still grows with rule count); insertions reevaluate only rules reachable from newly active predicates.+- **Staging copies the whole session state** for each *effective* `apply()` batch to guarantee atomic commits (an empty or already-applied batch is a no-op and stages nothing), and the session retains the **support catalog in memory** for the session lifetime (including withdrawn supports, so IDs stay bound).+- **Each `snapshot()` call copies the full committed state again** (facts, active supports, version), so consumers such as+ [`TruthMaintenanceContextFilter`](/reference/context#support-aware-retrieval-truth_filter)+ pay one whole-state copy per filtered retrieval. Do not call it in a tight+ loop when a single shared read is enough.- The copy-on-update and catalog costs are per-batch whole-state costs; do not assume end-to-end latency is strictly proportional to the affected subgraph. Measure before relying on performance.@@ -138,4 +150,5 @@ Returned snapshots (`MaintenanceDelta`, `FactExplanation`, `Derivation`) are fro## Links- [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/context/__init__.py b/semantica/context/__init__.pyindex 9bebf243..0b2d1c2e 100644--- a/semantica/context/__init__.py+++ b/semantica/context/__init__.py@@ -117,6 +117,7 @@ from .context_retriever import (from .decision_context import DecisionContextfrom .entity_linker import EntityLink, EntityLinker, LinkedEntityfrom .erasure import ErasureCoordinator, ErasureReceipt+from .truth_maintenance_filter import TruthMaintenanceContextFilter# Decision tracking importsfrom .decision_models import (@@ -175,6 +176,7 @@ __all__ = ["ContextRetriever","RetrievedContext","TemporalGraphRetriever",+ "TruthMaintenanceContextFilter",# Cross-store erasure"ErasureCoordinator","ErasureReceipt",diff --git a/semantica/context/agent_context.py b/semantica/context/agent_context.pyindex 4323a63e..839e23db 100644--- a/semantica/context/agent_context.py+++ b/semantica/context/agent_context.py@@ -74,6 +74,7 @@ Production Use Cases:from datetime import datetime, timedeltafrom typing import Any, Dict, List, Optional, Tuple, Union+from ..utils.exceptions import ValidationErrorfrom ..utils.helpers import classify_path_distancefrom ..utils.logging import get_loggerfrom .agent_memory import AgentMemory@@ -533,7 +534,8 @@ class AgentContext:include_relationships: Include relationships in results (default: False)expand_graph: Use graph expansion (default: True)deduplicate: Deduplicate results (default: True)- **kwargs: Additional filters (type, date_range, etc.)+ **kwargs: Additional filters (type, date_range, etc.); ``truth_filter`` is+ rejected here, use ``ContextRetriever.retrieve`` directlyReturns:List of context dicts with content, score, source, and metadata@@ -545,6 +547,14 @@ class AgentContext:>>> # Force vector-only retrieval>>> results = context.retrieve("Python", use_graph=False)"""+ if kwargs.get("truth_filter") is not None:+ raise ValidationError(+ "truth_filter is not supported on AgentContext.retrieve; use "+ "ContextRetriever.retrieve(..., truth_filter=...) directly and "+ "assemble the verified context yourself",+ validation_context={"method": "AgentContext.retrieve"},+ )+# Auto-detect strategyif use_graph is None:use_graph = self.knowledge_graph is not None and self._retriever is not None@@ -612,7 +622,8 @@ class AgentContext:llm_provider: LLM provider instance (from semantica.llms)max_results: Maximum context results to retrieve (default: 10)max_hops: Maximum graph traversal hops (default: 2)- **kwargs: Additional retrieval options+ **kwargs: Additional retrieval options; ``truth_filter`` is rejected here,+ use ``ContextRetriever.retrieve`` directly insteadReturns:Dictionary with:@@ -631,6 +642,17 @@ class AgentContext:... )>>> print(result['response'])"""+ if kwargs.get("truth_filter") is not None:+ raise ValidationError(+ "truth_filter is not supported on "+ "AgentContext.query_with_reasoning; use "+ "ContextRetriever.retrieve(..., truth_filter=...) directly and "+ "assemble the verified context before reasoning",+ validation_context={+ "method": "AgentContext.query_with_reasoning"+ },+ )+if not self._retriever:# Fallback if retriever not availablereturn {diff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.pyindex 6cdff454..ef96d22a 100644--- a/semantica/context/context_graph.py+++ b/semantica/context/context_graph.py@@ -1053,6 +1053,12 @@ class ContextGraph:"weight": edge.weight,"hop": next_hop,}+ # Expose the merged node metadata so consumers such as+ # support-aware retrieval can validate annotations on+ # neighbor attachments instead of dropping them blindly.+ entry_metadata: Dict[str, Any] = dict(node.properties or {})+ entry_metadata.update(node.metadata or {})+ entry["metadata"] = entry_metadataif include_distance_metadata:entry["distance_band"] = classify_path_distance(next_hop)entry["confidence_decay"] = next_decaydiff --git a/semantica/context/context_retriever.py b/semantica/context/context_retriever.pyindex 495bda13..67d5c931 100644--- a/semantica/context/context_retriever.py+++ b/semantica/context/context_retriever.py@@ -88,6 +88,8 @@ from ..kg.path_finder import PathFinderfrom ..kg.centrality_calculator import CentralityCalculatorfrom ..kg.community_detector import CommunityDetectorfrom ..kg.similarity_calculator import SimilarityCalculator+from ..utils.exceptions import ValidationError+from .truth_maintenance_filter import TruthMaintenanceContextFiltertry:from ..kg.temporal_query import TemporalGraphQuery as _TemporalGraphQueryfrom ..kg.temporal_model import parse_temporal_value as _parse_temporal_value@@ -212,6 +214,7 @@ class ContextRetriever:use_graph_expansion: Optional[bool] = None,min_relevance_score: float = 0.0,mode: str = "local",+ truth_filter: Optional[TruthMaintenanceContextFilter] = None,**options,) -> List[RetrievedContext]:"""@@ -223,6 +226,10 @@ class ContextRetriever:use_graph_expansion: Use graph expansion (overrides config)min_relevance_score: Minimum relevance scoremode: Retrieval mode ('local', 'global', 'drift', 'hybrid')+ truth_filter: Optional truth-maintenance filter for local mode only;+ candidates are validated against a session snapshot before+ ranking and the snapshot version is re-checked before+ results are returned**options: Additional options:- entity_ids: Filter by entity IDs- node_types: Filter by node types@@ -232,6 +239,15 @@ class ContextRetriever:List of retrieved context items"""norm_mode = str(mode).lower().strip()+ if truth_filter is not None and norm_mode != "local":+ raise ValidationError(+ "truth_filter is supported only with mode='local'; "+ "other retrieval modes do not validate truth dependencies",+ validation_context={+ "method": "ContextRetriever.retrieve",+ "mode": norm_mode,+ },+ )if norm_mode == "global":return self.retrieve_global(query,@@ -287,6 +303,18 @@ class ContextRetriever:)try:+ if truth_filter is not None and not isinstance(+ truth_filter, TruthMaintenanceContextFilter+ ):+ raise ValidationError(+ "truth_filter must be a TruthMaintenanceContextFilter "+ "instance",+ validation_context={"method": "ContextRetriever.retrieve"},+ )+ snapshot = (+ truth_filter.snapshot() if truth_filter is not None else None+ )+use_expansion = (use_graph_expansionif use_graph_expansion is not None@@ -329,7 +357,13 @@ class ContextRetriever:self.progress_tracker.update_tracking(tracking_id, message="Ranking and merging results...")- ranked_results = self._rank_and_merge(all_results, query)+ if snapshot is not None:+ all_results = truth_filter.filter_contexts(+ all_results, snapshot=snapshot+ )+ ranked_results = self._rank_and_merge(+ all_results, query, merge_duplicates=snapshot is None+ )# Filter by minimum scoreeff_min_score = (@@ -341,6 +375,9 @@ class ContextRetriever:r for r in ranked_results if r.score >= eff_min_score]+ if snapshot is not None:+ truth_filter.assert_current(snapshot)+self.progress_tracker.stop_tracking(tracking_id,status="completed",@@ -562,8 +599,10 @@ class ContextRetriever:content = res.get("content") or res.get("node", {}).get("content")- metadata = res.get("metadata") or res.get("node", {}).get(- "metadata"+ metadata = (+ res.get("metadata")+ or res.get("node", {}).get("metadata")+ or res.get("node", {}).get("properties"))score = res.get("score", 0.0)@@ -763,6 +802,12 @@ class ContextRetriever:related_entities.append(e)break+ # Cap relationship attachments before rendering prose so the+ # validated bundle and the rendered content stay aligned: the+ # filter only sees the first 10 relationships, so the prose+ # must describe no more than those 10.+ related_relationships = related_relationships[:10]+# Generate comprehensive content from entity and relationshipsentity_display = entity.get('name', entity_id)@@ -876,7 +921,7 @@ class ContextRetriever:**entity.get("metadata", {}),},related_entities=related_entities[:10], # Limit entities- related_relationships=related_relationships[:10], # Limit relationships+ related_relationships=related_relationships, # Already capped above))@@ -949,7 +994,11 @@ class ContextRetriever:return []def _rank_and_merge(- self, results: List[RetrievedContext], query: str+ self,+ results: List[RetrievedContext],+ query: str,+ *,+ merge_duplicates: bool = True,) -> List[RetrievedContext]:"""Rank and merge results from multiple sources with GraphRAG optimization."""def is_graph_source(s: Optional[str]) -> bool:@@ -1037,7 +1086,7 @@ class ContextRetriever:all_results = vector_results + graph_results + memory_results + other_results- for result in all_results:+ for result in (all_results if merge_duplicates else []):# For graph results, deduplicate by entity IDif is_graph_source(result.source):entity_id = result.metadata.get("node_id")@@ -1085,13 +1134,18 @@ class ContextRetriever:existing.metadata.update(result.metadata)# Combine deduplicated results- merged_results = list(seen_entities.values()) + [- r for r in seen_content.values()- if (- not is_graph_source(r.source)- or r.metadata.get("node_id") not in seen_entities- )- ]+ if merge_duplicates:+ merged_results = list(seen_entities.values()) + [+ r for r in seen_content.values()+ if (+ not is_graph_source(r.source)+ or r.metadata.get("node_id") not in seen_entities+ )+ ]+ else:+ # Grounded retrieval: every validated candidate is kept; merging+ # could mix provenance across rows that reference the same node.+ merged_results = list(all_results)# Re-rank with query relevance boostif self.vector_store and hasattr(self.vector_store, 'embed'):@@ -1225,6 +1279,8 @@ class ContextRetriever:"id": target_id,"type": node.get("type"),"content": node.get("content"),+ "metadata": node.get("metadata")+ or node.get("properties"),"relationship": edge.get("type"),"hop": hop + 1,}@@ -1243,6 +1299,8 @@ class ContextRetriever:"id": source_id,"type": node.get("type"),"content": node.get("content"),+ "metadata": node.get("metadata")+ or node.get("properties"),"relationship": edge.get("type"),"hop": hop + 1,}@@ -1773,7 +1831,8 @@ Answer:"""``{at_time}`` and ``{source}`` placeholders are substituted;any other braces are left as-is. Defaults to``"[Graph context valid as of: {at_time} UTC | Source: {source}]"``.- **kwargs: Additional retrieval options passed to ``retrieve()``+ **kwargs: Additional retrieval options passed to ``retrieve()``; ``truth_filter`` is+ rejected here, use ``retrieve()`` directly insteadReturns:Dictionary with:@@ -1792,6 +1851,15 @@ Answer:"""... )>>> print(result['response'])"""+ if kwargs.get("truth_filter") is not None:+ raise ValidationError(+ "truth_filter is not supported on query_with_reasoning; use "+ "ContextRetriever.retrieve(..., truth_filter=...) directly and "+ "assemble the verified context before reasoning",+ validation_context={+ "method": "ContextRetriever.query_with_reasoning"+ },+ )tracking_id = self.progress_tracker.start_tracking(file=None,module="context",diff --git a/semantica/context/truth_maintenance_filter.py b/semantica/context/truth_maintenance_filter.pynew file mode 100644index 00000000..86905e86--- /dev/null+++ b/semantica/context/truth_maintenance_filter.py@@ -0,0 +1,258 @@+"""Grounded context filtering against truth maintenance snapshots.++This module validates cached :class:`~semantica.context.context_retriever.RetrievedContext`+items against an immutable :class:`~semantica.reasoning.TruthMaintenanceSnapshot`+before they are ranked or merged. Candidates whose declared dependencies are no+longer supported by the session are removed, while program-integration errors+(wrong argument types, stale snapshots) raise explicit exceptions.++The filter is deliberately decoupled from the retrieval stack: it only sees+candidates plus a snapshot that the caller obtained from the same filter.+"""++from __future__ import annotations++from collections.abc import Iterable, Sequence+from copy import deepcopy+from typing import TYPE_CHECKING, Any, List, Tuple++from semantica.reasoning import TruthMaintenanceSession, TruthMaintenanceSnapshot+from semantica.reasoning._truth_maintenance_validation import validate_fact_text+from semantica.utils.exceptions import ProcessingError, ValidationError++if TYPE_CHECKING: # pragma: no cover - import kept out of runtime cycle+ from .context_retriever import RetrievedContext++_ANNOTATION_SCHEMA_VERSION = 1+_ANNOTATION_KEYS = frozenset(+ {+ "schema_version",+ "session_id",+ "required_facts",+ "required_support_ids",+ }+)+++def _validated_dependencies(+ annotation: Any,+ *,+ filter_session_id: str,+) -> Tuple[frozenset, frozenset]:+ """Validate a ``truth_maintenance`` annotation and normalize its sets.++ Returns the normalized (facts, support_ids) pair. Any violation of the+ schema raises ``ValueError``; the caller translates that into per-candidate+ exclusion.+ """++ if not isinstance(annotation, dict):+ raise ValueError("truth_maintenance annotation must be a dict")+ keys = set(annotation.keys())+ if keys != set(_ANNOTATION_KEYS):+ raise ValueError(+ "truth_maintenance annotation must contain exactly "+ "schema_version, session_id, required_facts, "+ "required_support_ids"+ )++ schema_version = annotation["schema_version"]+ if isinstance(schema_version, bool) or not isinstance(schema_version, int):+ raise ValueError("schema_version must be an integer")+ if schema_version != _ANNOTATION_SCHEMA_VERSION:+ raise ValueError("unsupported truth_maintenance schema_version")++ session_id = annotation["session_id"]+ if not isinstance(session_id, str) or not session_id or session_id.strip() != session_id:+ raise ValueError("session_id must be a non-empty string without surrounding whitespace")+ if session_id != filter_session_id:+ raise ValueError("annotation belongs to a different truth maintenance session")++ raw_facts = annotation["required_facts"]+ raw_supports = annotation["required_support_ids"]+ for raw_value in (raw_facts, raw_supports):+ if not isinstance(raw_value, list):+ raise ValueError("dependency lists must be lists")+ if not raw_facts and not raw_supports:+ raise ValueError("at least one required fact or support id must be declared")++ facts = set()+ for raw_fact in raw_facts:+ if not isinstance(raw_fact, str):+ raise ValueError("required_facts entries must be strings")+ try:+ facts.add(validate_fact_text(raw_fact))+ except ValidationError as exc:+ raise ValueError(f"invalid required fact: {exc.message}") from exc++ support_ids = set()+ for raw_support in raw_supports:+ if not isinstance(raw_support, str):+ raise ValueError("required_support_ids entries must be strings")+ if not raw_support or raw_support.strip() != raw_support:+ raise ValueError(+ "support ids must be non-empty strings without surrounding whitespace"+ )+ support_ids.add(raw_support)++ return frozenset(facts), frozenset(support_ids)+++def _attachment_metadata(member: Any) -> Any:+ """Return the metadata dict of a graph attachment member."""++ if not isinstance(member, dict):+ raise ValueError("graph attachments must be dicts")+ metadata = member.get("metadata")+ if not isinstance(metadata, dict):+ raise ValueError("graph attachments must carry a metadata dict")+ return metadata+++class TruthMaintenanceContextFilter:+ """Validate retrieved context dependencies against truth snapshots.++ The filter is bound to one :class:`TruthMaintenanceSession` and one+ ``session_id``. ``filter_contexts`` performs pure candidate validation+ against a snapshot; it never reads the live session state while the+ session may still be mutating. ``assert_current`` closes the race window+ by re-checking the session version after retrieval completed.+ """++ def __init__(+ self,+ session: TruthMaintenanceSession,+ *,+ session_id: str,+ ):+ if not isinstance(session, TruthMaintenanceSession):+ raise ValidationError(+ "session must be a TruthMaintenanceSession instance",+ validation_context={"session_type": type(session).__name__},+ )+ if not isinstance(session_id, str) or not session_id or session_id.strip() != session_id:+ raise ValidationError(+ "session_id must be a non-empty string without surrounding whitespace",+ validation_context={"session_id": session_id},+ )+ self._session = session+ self._session_id = session_id++ @property+ def session_id(self) -> str:+ """Identity of the truth maintenance session this filter guards."""++ return self._session_id++ def snapshot(self) -> TruthMaintenanceSnapshot:+ """Return an immutable snapshot of the bound session."""++ return self._session.snapshot()++ def filter_contexts(+ self,+ candidates: Iterable[Any],+ *,+ snapshot: TruthMaintenanceSnapshot,+ ) -> List[RetrievedContext]:+ """Return the grounded subset of ``candidates``.++ Each candidate must be a :class:`RetrievedContext`. Its root+ annotation and the annotation of every graph attachment must validate+ and be fully supported by ``snapshot``. Passing candidates are returned+ as deep copies stamped with the actual validation credentials;+ originals are never modified. Invalid annotations remove the whole+ candidate without failing the call.+ """++ from .context_retriever import RetrievedContext++ active_ids = frozenset(+ support.support_id for support in snapshot.active_supports+ )+ results: List[RetrievedContext] = []+ for candidate in candidates:+ if not isinstance(candidate, RetrievedContext):+ raise ValidationError(+ "candidates must be RetrievedContext instances",+ validation_context={"candidate_type": type(candidate).__name__},+ )+ if self._candidate_is_grounded(candidate, snapshot=snapshot, active_ids=active_ids):+ copied = deepcopy(candidate)+ copied.metadata["truth_maintenance_validation"] = {+ "session_id": self._session_id,+ "version": snapshot.version,+ }+ results.append(copied)+ return results++ def assert_current(self, snapshot: TruthMaintenanceSnapshot) -> None:+ """Raise ``ProcessingError`` if the session moved past ``snapshot``."""++ current_version = self._session.version+ if snapshot.version != current_version:+ raise ProcessingError(+ "truth maintenance session changed during retrieval; "+ "snapshot is stale",+ processing_context={+ "expected": snapshot.version,+ "actual": current_version,+ },+ expected=snapshot.version,+ actual=current_version,+ )++ def _candidate_is_grounded(+ self,+ candidate: RetrievedContext,+ *,+ snapshot: TruthMaintenanceSnapshot,+ active_ids: frozenset,+ ) -> bool:+ try:+ root_metadata = candidate.metadata+ if not isinstance(root_metadata, dict):+ # A malformed store record must remove only this candidate,+ # never abort the whole filtered retrieval.+ return False+ root_facts, root_supports = _validated_dependencies(+ root_metadata.get("truth_maintenance"),+ filter_session_id=self._session_id,+ )+ entity_facts, entity_supports = self._validate_attachments(+ candidate.related_entities+ )+ rel_facts, rel_supports = self._validate_attachments(+ candidate.related_relationships+ )+ except ValueError:+ return False++ required_facts = root_facts | entity_facts | rel_facts+ required_supports = root_supports | entity_supports | rel_supports+ if not required_facts.issubset(snapshot.facts):+ return False+ if not required_supports.issubset(active_ids):+ return False+ return True++ def _validate_attachments(+ self, attachments: Any+ ) -> Tuple[frozenset, frozenset]:+ """Validate attachment annotations and accumulate their dependencies."""++ facts: set = set()+ support_ids: set = set()+ if not isinstance(attachments, Sequence) or isinstance(+ attachments, (str, bytes, bytearray)+ ):+ raise ValueError("graph attachments must be lists")+ for member in attachments:+ metadata = _attachment_metadata(member)+ member_facts, member_supports = _validated_dependencies(+ metadata.get("truth_maintenance"),+ filter_session_id=self._session_id,+ )+ facts.update(member_facts)+ support_ids.update(member_supports)+ return frozenset(facts), frozenset(support_ids)\ No newline at end of filediff --git a/semantica/reasoning/__init__.py b/semantica/reasoning/__init__.pyindex 5893e3d8..6005da06 100644--- a/semantica/reasoning/__init__.py+++ b/semantica/reasoning/__init__.py@@ -48,6 +48,7 @@ from .truth_maintenance_types import (FactExplanation,FactSupport,MaintenanceDelta,+ TruthMaintenanceSnapshot,)__all__ = [@@ -87,6 +88,7 @@ __all__ = ["Derivation","FactExplanation","MaintenanceDelta",+ "TruthMaintenanceSnapshot",# Explanation"ExplanationGenerator","Explanation",diff --git a/semantica/reasoning/truth_maintenance.py b/semantica/reasoning/truth_maintenance.pyindex f8533867..f12a4020 100644--- a/semantica/reasoning/truth_maintenance.py+++ b/semantica/reasoning/truth_maintenance.py@@ -28,6 +28,7 @@ from .truth_maintenance_types import (FactExplanation,FactSupport,MaintenanceDelta,+ TruthMaintenanceSnapshot,)__all__ = ["TruthMaintenanceSession"]@@ -173,6 +174,25 @@ class TruthMaintenanceSession:"""Monotonic commit counter; unchanged for net-zero updates."""return self._version+ def snapshot(self) -> TruthMaintenanceSnapshot:+ """Return an immutable, detached view of the current committed state.++ The snapshot is a full copy: later ``apply`` batches never change an+ existing snapshot. Reading it obeys the same caller-serialized+ access contract as the rest of the session API.+ """+ state = self._state+ return TruthMaintenanceSnapshot(+ version=self._version,+ facts=frozenset(state.active_facts),+ active_supports=tuple(+ sorted(+ state.active_supports.values(),+ key=lambda support: support.support_id,+ )+ ),+ )+def explain(self, fact: str) -> FactExplanation:"""Explain one fact: explicit supports plus retained derivations."""canonical = validate_fact_text(fact)diff --git a/semantica/reasoning/truth_maintenance_types.py b/semantica/reasoning/truth_maintenance_types.pyindex 2a2d66e0..044bef4d 100644--- a/semantica/reasoning/truth_maintenance_types.py+++ b/semantica/reasoning/truth_maintenance_types.py@@ -14,6 +14,7 @@ __all__ = ["FactExplanation","FactSupport","MaintenanceDelta",+ "TruthMaintenanceSnapshot",]@@ -56,6 +57,20 @@ class MaintenanceDelta:removed_supports: Tuple[FactSupport, ...]+@dataclass(frozen=True)+class TruthMaintenanceSnapshot:+ """Immutable, detached view of one committed session state.++ Returned by :meth:`TruthMaintenanceSession.snapshot`. The collections+ and support records are copies detached from live session state, so+ later ``apply`` batches never change an existing snapshot.+ """++ version: int+ facts: FrozenSet[str]+ active_supports: Tuple[FactSupport, ...]++@dataclass(frozen=True)class _RuleSnapshot:"""Internal immutable copy of the subset of Rule the session relies on.diff --git a/tests/context/test_grounded_context_retrieval.py b/tests/context/test_grounded_context_retrieval.pynew file mode 100644index 00000000..9f9225d7--- /dev/null+++ b/tests/context/test_grounded_context_retrieval.py@@ -0,0 +1,777 @@+"""Grounded retrieval coordination: filtering before ranking and version gating."""++from copy import deepcopy++import pytest+from semantica.context import (+ AgentContext,+ ContextGraph,+ ContextRetriever,+ RetrievedContext,+ TruthMaintenanceContextFilter,+)+from semantica.reasoning import FactSupport, Rule, TruthMaintenanceSession+from semantica.utils.exceptions import ProcessingError, ValidationError+from semantica.vector_store import VectorStore++SESSION_ID = "employment-session-1"+++class StaticVectorStore:+ def __init__(self, rows):+ self.rows = deepcopy(rows)+ self.calls = 0++ def search(self, *, query, limit):+ self.calls += 1+ return deepcopy(self.rows[:limit])+++def row(identifier, fact, score, text):+ return {+ "id": identifier,+ "score": score,+ "content": text,+ "metadata": {+ "truth_maintenance": {+ "schema_version": 1,+ "session_id": SESSION_ID,+ "required_facts": [fact],+ "required_support_ids": [],+ }+ },+ }+++def make_session(*rules):+ return TruthMaintenanceSession(rules=list(rules))+++def make_gate(session):+ return TruthMaintenanceContextFilter(session, session_id=SESSION_ID)++[email protected]("mode", ["local", " LOCAL "])+def test_invalid_candidate_is_removed_before_top_k(mode):+ session = make_session()+ session.apply(assertions=[FactSupport("live", "Current(x)")])+ store = StaticVectorStore([+ row("stale", "Old(x)", 0.99, "stale assertion"),+ row("live", "Current(x)", 0.6, "current assertion"),+ ])+ gate = make_gate(session)+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ result = retriever.retrieve(+ "assertion", max_results=1, truth_filter=gate, mode=mode+ )+ assert [r.content for r in result] == ["current assertion"]+ assert len(store.rows) == 2+ assert (+ result[0].metadata["truth_maintenance_validation"]["version"]+ == session.version+ )++[email protected]("mode", ["global", "drift", "hybrid", " GLOBAL "])+def test_nonlocal_modes_reject_truth_filter_before_retrieval(mode, monkeypatch):+ store = StaticVectorStore([])+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ gate = make_gate(make_session())+ backend_calls = []++ def unvalidated_backend(*args, **kwargs):+ backend_calls.append(kwargs)+ return [RetrievedContext(content="unsupported claim", score=1.0)]++ monkeypatch.setattr(retriever, "retrieve_global", unvalidated_backend)+ monkeypatch.setattr(retriever, "retrieve_drift", unvalidated_backend)+ with pytest.raises(ValidationError, match="truth_filter.*local"):+ retriever.retrieve("assertion", mode=mode, truth_filter=gate)+ assert backend_calls == []+ assert store.calls == 0+++def test_duplicate_text_prefixes_are_both_kept():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ shared = "same first hundred characters " * 4+ store = StaticVectorStore([+ row("one", "A(x)", 0.8, shared + " tail one"),+ row("two", "A(x)", 0.7, shared + " tail two"),+ ])+ gate = make_gate(session)+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ result = retriever.retrieve("query", max_results=5, truth_filter=gate)+ assert sorted(r.content[-8:] for r in result) == ["tail one", "tail two"]+++def test_same_graph_node_id_candidates_are_not_merged():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = make_gate(session)+ retriever = ContextRetriever(use_graph_expansion=False)++ def graph_candidate(node_id, extra_metadata, entities):+ return gate.filter_contexts(+ [RetrievedContext(+ content=f"node {node_id}",+ score=0.8,+ source=f"graph:{node_id}",+ metadata={+ "node_id": node_id,+ "truth_maintenance": {+ "schema_version": 1,+ "session_id": SESSION_ID,+ "required_facts": ["A(x)"],+ "required_support_ids": [],+ },+ **extra_metadata,+ },+ related_entities=entities,+ )],+ snapshot=gate.snapshot(),+ )[0]++ first = graph_candidate("n1", {"marker": "first"}, [{"id": "e1", "metadata": {+ "truth_maintenance": {+ "schema_version": 1,+ "session_id": SESSION_ID,+ "required_facts": [],+ "required_support_ids": ["s1"],+ }+ }}])+ second = graph_candidate("n1", {"marker": "second"}, [{"id": "e2", "metadata": {+ "truth_maintenance": {+ "schema_version": 1,+ "session_id": SESSION_ID,+ "required_facts": [],+ "required_support_ids": ["s1"],+ }+ }}])++ merged = retriever._rank_and_merge(+ [first, second], "query", merge_duplicates=False+ )+ assert len(merged) == 2+ markers = sorted(c.metadata["marker"] for c in merged)+ assert markers == ["first", "second"]+ entity_ids = {e["id"] for c in merged for e in c.related_entities}+ assert entity_ids == {"e1", "e2"}+++def test_default_merge_duplicates_keeps_original_dedup():+ retriever = ContextRetriever(use_graph_expansion=False)+ first = RetrievedContext(+ content="shared content", score=0.9, source="vector:a"+ )+ second = RetrievedContext(+ content="shared content", score=0.5, source="vector:b"+ )+ merged = retriever._rank_and_merge([first, second], "query")+ assert len(merged) == 1+++class MutatingVectorStore(StaticVectorStore):+ """Vector store whose search mutates the session mid-retrieval."""++ def __init__(self, rows, session, on_search):+ super().__init__(rows)+ self.session = session+ self.on_search = on_search++ def search(self, *, query, limit):+ results = super().search(query=query, limit=limit)+ self.on_search(self.session)+ return results+++def test_fact_change_during_search_raises_processing_error():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ store = MutatingVectorStore(+ [row("live", "A(x)", 0.9, "live")],+ session,+ lambda s: s.apply(retractions=["s1"]),+ )+ gate = make_gate(session)+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ with pytest.raises(ProcessingError):+ retriever.retrieve("query", max_results=5, truth_filter=gate)+++def test_support_only_change_during_search_raises_processing_error():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ store = MutatingVectorStore(+ [row("live", "A(x)", 0.9, "live")],+ session,+ lambda s: s.apply(+ assertions=[FactSupport("s2", "A(x)")], retractions=["s1"]+ ),+ )+ gate = make_gate(session)+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ with pytest.raises(ProcessingError):+ retriever.retrieve("query", max_results=5, truth_filter=gate)+++def test_noop_apply_during_search_succeeds():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ store = MutatingVectorStore(+ [row("live", "A(x)", 0.9, "live")],+ session,+ lambda s: s.apply(assertions=[]),+ )+ gate = make_gate(session)+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ result = retriever.retrieve("query", max_results=5, truth_filter=gate)+ assert [r.content for r in result] == ["live"]+++def test_failed_apply_during_search_does_not_fail_retrieval():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])++ def failed_apply(s):+ with pytest.raises(ValidationError):+ s.apply(assertions=[FactSupport("bad", "NotAFact")])++ store = MutatingVectorStore(+ [row("live", "A(x)", 0.9, "live")], session, failed_apply+ )+ gate = make_gate(session)+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ result = retriever.retrieve("query", max_results=5, truth_filter=gate)+ assert [r.content for r in result] == ["live"]+++def test_rerank_embed_callback_change_raises_processing_error():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])++ class EmbeddingMutatingStore(StaticVectorStore):+ def embed(self, text):+ session.apply(retractions=["s1"])+ return [0.1, 0.2]++ store = EmbeddingMutatingStore([row("live", "A(x)", 0.9, "live")])+ gate = make_gate(session)+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ with pytest.raises(ProcessingError):+ retriever.retrieve("query", max_results=5, truth_filter=gate)+++def test_invalid_truth_filter_type_raises_validation_error():+ store = StaticVectorStore([])+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ with pytest.raises(ValidationError):+ retriever.retrieve("query", max_results=5, truth_filter="gate")+++def test_filter_none_matches_default_behavior():+ rows = [+ {"id": "a", "score": 0.9, "content": "first", "metadata": {}},+ {"id": "b", "score": 0.4, "content": "second", "metadata": {}},+ ]+ default_results = ContextRetriever(+ vector_store=StaticVectorStore(rows), use_graph_expansion=False+ ).retrieve("query", max_results=5)+ none_results = ContextRetriever(+ vector_store=StaticVectorStore(rows), use_graph_expansion=False+ ).retrieve("query", max_results=5, truth_filter=None)+ assert [r.content for r in default_results] == [r.content for r in none_results]+++def test_all_invalid_candidates_return_empty_without_recall():+ session = make_session()+ store = StaticVectorStore([+ row("stale1", "Old(x)", 0.99, "stale one"),+ row("stale2", "Gone(x)", 0.9, "stale two"),+ ])+ gate = make_gate(session)+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ assert retriever.retrieve("query", max_results=5, truth_filter=gate) == []+ assert store.calls == 1+++def test_old_validation_stamp_is_overwritten_by_current_check():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ session.apply(retractions=["s1"])+ session.apply(assertions=[FactSupport("s2", "A(x)")])+ stale_row = row("live", "A(x)", 0.9, "live")+ stale_row["metadata"]["truth_maintenance_validation"] = {+ "session_id": "someone-else",+ "version": 99,+ }+ store = StaticVectorStore([stale_row])+ gate = make_gate(session)+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ result = retriever.retrieve("query", max_results=5, truth_filter=gate)+ assert result[0].metadata["truth_maintenance_validation"] == {+ "session_id": SESSION_ID,+ "version": session.version,+ }+++def test_empty_store_returns_empty_list():+ session = make_session()+ store = StaticVectorStore([])+ gate = make_gate(session)+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ assert retriever.retrieve("query", max_results=5, truth_filter=gate) == []+++class ExplodingLLM:+ """LLM fake; any call means the entry point failed to reject first."""++ def generate(self, prompt):+ raise AssertionError("llm provider must not be called")+++class ExplodingRetriever:+ """Retriever fake; any call means the entry point failed to reject first."""++ def retrieve(self, *args, **kwargs):+ raise AssertionError("retriever must not be called")++ def query_with_reasoning(self, *args, **kwargs):+ raise AssertionError("retriever must not be called")+++class ExplodingMemory:+ """Memory fake; any call means the entry point failed to reject first."""++ def retrieve(self, *args, **kwargs):+ raise AssertionError("memory store must not be called")+++class StaticMemoryStore:+ """Memory source fake returning plain dict rows."""++ def __init__(self, rows):+ self.rows = deepcopy(rows)++ def retrieve(self, *, query, max_results):+ return deepcopy(self.rows[:max_results])+++class MutatingMemoryStore(StaticMemoryStore):+ """Memory source fake whose retrieve mutates the session mid-retrieval."""++ def __init__(self, rows, session, on_retrieve):+ super().__init__(rows)+ self.session = session+ self.on_retrieve = on_retrieve++ def retrieve(self, *, query, max_results):+ results = super().retrieve(query=query, max_results=max_results)+ self.on_retrieve(self.session)+ return results+++class StaticGraphStore:+ """Graph source fake: root row plus neighbor rows with annotations."""++ def __init__(self, root_row, neighbors):+ self.root_row = deepcopy(root_row)+ self.neighbors = deepcopy(neighbors)++ def query(self, query):+ return [deepcopy(self.root_row)]++ def get_neighbors(self, node_id, *, hops):+ return deepcopy(self.neighbors)+++class MutatingGraphStore(StaticGraphStore):+ """Graph source fake whose query mutates the session mid-retrieval."""++ def __init__(self, root_row, neighbors, session, on_query):+ super().__init__(root_row, neighbors)+ self.session = session+ self.on_query = on_query++ def query(self, query):+ results = super().query(query)+ self.on_query(self.session)+ return results+++def make_agent_context(with_graph):+ # Built without a graph so construction stays hermetic in environments+ # where optional KG embedding dependencies are absent; the graph branch+ # is enabled afterwards together with the injected fake retriever.+ context = AgentContext(+ vector_store=VectorStore(backend="inmemory", dimension=64),+ knowledge_graph=None,+ decision_tracking=True,+ kg_algorithms=False,+ vector_store_features=False,+ )+ if with_graph:+ context.knowledge_graph = ContextGraph()+ return context+++def test_retriever_query_with_reasoning_rejects_truth_filter():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ retriever = ContextRetriever(+ vector_store=StaticVectorStore([row("live", "A(x)", 0.9, "live")]),+ use_graph_expansion=False,+ )+ with pytest.raises(ValidationError):+ retriever.query_with_reasoning(+ "query",+ llm_provider=ExplodingLLM(),+ max_results=5,+ truth_filter=make_gate(session),+ )+++def test_agent_context_retrieve_rejects_truth_filter_with_graph():+ context = make_agent_context(with_graph=True)+ context._retriever = ExplodingRetriever()+ with pytest.raises(ValidationError):+ context.retrieve("query", truth_filter=make_gate(make_session()))+++def test_agent_context_retrieve_rejects_truth_filter_without_graph():+ context = make_agent_context(with_graph=False)+ context._memory = ExplodingMemory()+ with pytest.raises(ValidationError):+ context.retrieve("query", truth_filter=make_gate(make_session()))+++def test_agent_context_query_with_reasoning_rejects_truth_filter():+ context = make_agent_context(with_graph=True)+ context._retriever = ExplodingRetriever()+ with pytest.raises(ValidationError):+ context.query_with_reasoning(+ "query",+ llm_provider=ExplodingLLM(),+ truth_filter=make_gate(make_session()),+ )+++def test_search_delegates_truth_filter():+ session = make_session()+ session.apply(assertions=[FactSupport("live", "Current(x)")])+ store = StaticVectorStore([+ row("stale", "Old(x)", 0.99, "stale assertion"),+ row("live", "Current(x)", 0.6, "current assertion"),+ ])+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ result = retriever.search(+ "assertion", max_results=1, truth_filter=make_gate(session)+ )+ assert [r.content for r in result] == ["current assertion"]+++def test_vector_search_delegates_truth_filter():+ session = make_session()+ session.apply(assertions=[FactSupport("live", "Current(x)")])+ store = StaticVectorStore([+ row("stale", "Old(x)", 0.99, "stale assertion"),+ row("live", "Current(x)", 0.6, "current assertion"),+ ])+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ result = retriever.vector_search(+ "assertion", max_results=1, truth_filter=make_gate(session)+ )+ assert [r.content for r in result] == ["current assertion"]+++def test_graph_search_delegates_truth_filter():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ graph = StaticGraphStore(+ row("live", "A(x)", 0.9, "root content"),+ [row("n1", "A(x)", 0.5, "neighbor")],+ )+ retriever = ContextRetriever(knowledge_graph=graph, use_graph_expansion=True)+ result = retriever.graph_search(+ "query", max_results=5, truth_filter=make_gate(session)+ )+ assert [r.content for r in result] == ["root content"]+ assert result[0].source == "graph:live"+ assert (+ result[0].metadata["truth_maintenance_validation"]["version"]+ == session.version+ )+++def test_memory_source_candidates_are_filtered():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ memory = StaticMemoryStore([+ row("stale", "Old(x)", 0.99, "stale memory"),+ row("live", "A(x)", 0.6, "live memory"),+ ])+ retriever = ContextRetriever(memory_store=memory, use_graph_expansion=False)+ result = retriever.retrieve(+ "query", max_results=5, truth_filter=make_gate(session)+ )+ assert [r.content for r in result] == ["live memory"]+ assert result[0].source == "memory:live"+ assert (+ result[0].metadata["truth_maintenance_validation"]["version"]+ == session.version+ )+++def test_graph_root_with_unsupported_neighbor_dependency_is_excluded():+ # A root whose attachment annotation declares an unsupported fact is+ # excluded as a whole: PR2 does not trim attachments and keep the root.+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ graph = StaticGraphStore(+ row("live", "A(x)", 0.9, "root content"),+ [row("n1", "Missing(x)", 0.5, "neighbor")],+ )+ retriever = ContextRetriever(knowledge_graph=graph, use_graph_expansion=True)+ assert (+ retriever.retrieve(+ "query", max_results=5, truth_filter=make_gate(session)+ )+ == []+ )+++def test_graph_search_does_not_invent_annotations_from_node_id():+ # Unannotated graph nodes are excluded: node_id is not a trust signal and+ # PR2 does not auto-annotate nodes during retrieval.+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ unannotated_root = {+ "id": "plain",+ "type": "fact",+ "score": 0.9,+ "content": "plain content",+ "metadata": {},+ }+ graph = StaticGraphStore(unannotated_root, [])+ retriever = ContextRetriever(knowledge_graph=graph, use_graph_expansion=True)+ assert (+ retriever.graph_search(+ "query", max_results=5, truth_filter=make_gate(session)+ )+ == []+ )++[email protected]("source_kind", ["vector", "memory", "graph"])[email protected]("apply_kind", ["noop", "failed", "retraction"])+def test_apply_state_during_multi_source_retrieval(source_kind, apply_kind):+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = make_gate(session)++ if apply_kind == "noop":++ def mutate(target_session):+ target_session.apply(assertions=[])++ elif apply_kind == "failed":++ def mutate(target_session):+ with pytest.raises(ValidationError):+ target_session.apply(assertions=[FactSupport("bad", "NotAFact")])++ else:++ def mutate(target_session):+ target_session.apply(retractions=["s1"])++ live_row = row("live", "A(x)", 0.9, "live")+ if source_kind == "vector":+ retriever = ContextRetriever(+ vector_store=MutatingVectorStore([live_row], session, mutate),+ use_graph_expansion=False,+ )+ elif source_kind == "memory":+ retriever = ContextRetriever(+ memory_store=MutatingMemoryStore([live_row], session, mutate),+ use_graph_expansion=False,+ )+ else:+ retriever = ContextRetriever(+ knowledge_graph=MutatingGraphStore(live_row, [], session, mutate),+ use_graph_expansion=True,+ )++ if apply_kind == "retraction":+ with pytest.raises(ProcessingError):+ retriever.retrieve("query", max_results=5, truth_filter=gate)+ else:+ result = retriever.retrieve("query", max_results=5, truth_filter=gate)+ assert [r.content for r in result] == ["live"]+++class RecordingLLM:+ def __init__(self):+ self.prompts = []++ def generate(self, prompt):+ self.prompts.append(prompt)+ return "recorded"+++def test_agent_receives_no_withdrawn_conclusion():+ session = TruthMaintenanceSession(rules=[+ Rule("employment", "employment", ["Employed(?x)"], "Eligible(?x)"),+ ])+ session.apply(assertions=[FactSupport("v1", "Employed(Alice)")])+ store = StaticVectorStore([+ row("cached", "Eligible(Alice)", 0.9, "Alice is eligible"),+ ])+ retriever = ContextRetriever(vector_store=store, use_graph_expansion=False)+ gate = make_gate(session)+ llm = RecordingLLM()++ def answer():+ checked = retriever.retrieve("eligibility", truth_filter=gate)+ context = "\n".join(result.content for result in checked)+ return llm.generate("Use only this checked context:\n" + context)++ answer()+ session.apply(retractions=["v1"])+ answer()+ assert "Alice is eligible" in llm.prompts[0]+ assert "Alice is eligible" not in llm.prompts[1]+ assert store.rows[0]["content"] == "Alice is eligible"+ assert store.calls == 2+++def graph_annotation(fact="A(x)", supports=()):+ return {+ "schema_version": 1,+ "session_id": SESSION_ID,+ "required_facts": [fact],+ "required_support_ids": list(supports),+ }+++def test_dict_graph_prose_only_describes_relationships_the_filter_validates():+ # The filter validates at most 10 relationship attachments, so the+ # rendered prose must not describe relationships beyond that cap:+ # content and validated attachments have to stay aligned.+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = make_gate(session)++ entities = [+ {+ "id": "hub",+ "name": "hub",+ "type": "fact",+ "metadata": {"truth_maintenance": graph_annotation()},+ }+ ]+ relationships = []+ for i in range(10):+ spoke = f"spoke{i}"+ entities.append(+ {+ "id": spoke,+ "name": spoke,+ "type": "fact",+ "metadata": {"truth_maintenance": graph_annotation()},+ }+ )+ relationships.append(+ {+ "source": "hub",+ "target": spoke,+ "type": "capped",+ "metadata": {"truth_maintenance": graph_annotation()},+ }+ )+ entities.append(+ {+ "id": "overflow",+ "name": "overflow",+ "type": "fact",+ "metadata": {"truth_maintenance": graph_annotation()},+ }+ )+ relationships.append(+ {+ "source": "hub",+ "target": "overflow",+ "type": "overflowed",+ "metadata": {"truth_maintenance": graph_annotation()},+ }+ )++ retriever = ContextRetriever(+ knowledge_graph={"entities": entities, "relationships": relationships},+ use_graph_expansion=True,+ )+ result = retriever.graph_search("hub", max_results=5, truth_filter=gate)++ assert len(result) == 1+ candidate = result[0]+ assert len(candidate.related_relationships) == 10+ assert "overflow" not in candidate.content+++def test_context_graph_annotations_survive_query_and_neighbor_paths():+ # End-to-end through a real ContextGraph: add_node stores the+ # annotation in node properties, query() exposes it via to_dict()+ # (properties key), and get_neighbors entries must carry a metadata+ # dict so the filter can validate neighbor attachments instead of+ # dropping every graph candidate.+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = make_gate(session)++ graph = ContextGraph()+ graph.add_node(+ "root", "fact", "root content", truth_maintenance=graph_annotation()+ )+ graph.add_node(+ "neighbor",+ "fact",+ "neighbor content",+ truth_maintenance=graph_annotation(),+ )+ graph.add_edge("root", "neighbor", "supports")++ retriever = ContextRetriever(knowledge_graph=graph, use_graph_expansion=True)+ result = retriever.graph_search("root", max_results=5, truth_filter=gate)++ assert len(result) == 1+ stamped = result[0]+ assert stamped.source == "graph:root"+ assert stamped.content == "root content"+ assert (+ stamped.metadata["truth_maintenance_validation"]["version"]+ == session.version+ )+ assert stamped.related_entities[0]["id"] == "neighbor"+++def test_context_graph_stale_neighbor_annotation_excludes_candidate():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = make_gate(session)++ graph = ContextGraph()+ graph.add_node(+ "root", "fact", "root content", truth_maintenance=graph_annotation()+ )+ graph.add_node(+ "neighbor",+ "fact",+ "neighbor content",+ truth_maintenance=graph_annotation(fact="Missing(x)"),+ )+ graph.add_edge("root", "neighbor", "supports")++ retriever = ContextRetriever(knowledge_graph=graph, use_graph_expansion=True)+ assert (+ retriever.graph_search("root", max_results=5, truth_filter=gate) == []+ )diff --git a/tests/context/test_truth_maintenance_filter.py b/tests/context/test_truth_maintenance_filter.pynew file mode 100644index 00000000..55b77e36--- /dev/null+++ b/tests/context/test_truth_maintenance_filter.py@@ -0,0 +1,458 @@+"""Pure filtering contract for truth maintenance context dependencies."""+++from copy import deepcopy++import pytest+from semantica.context import RetrievedContext, TruthMaintenanceContextFilter+from semantica.reasoning import FactSupport, Rule, TruthMaintenanceSession+from semantica.utils.exceptions import ProcessingError, ValidationError++SESSION_ID = "employment-session-1"+++def item(facts, supports=(), text="Alice is eligible"):+ return RetrievedContext(+ content=text,+ score=0.9,+ source="vector:cached",+ metadata={+ "truth_maintenance": {+ "schema_version": 1,+ "session_id": SESSION_ID,+ "required_facts": list(facts),+ "required_support_ids": list(supports),+ }+ },+ )+++def make_session(*rules):+ return TruthMaintenanceSession(rules=list(rules))+++def test_last_support_withdrawal_excludes_cached_conclusion():+ session = make_session(Rule("ab", "ab", ["A(?x)"], "B(?x)"))+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ cached = item(["B(x)"])+ session.apply(assertions=[FactSupport("old", "A(x)")])+ assert len(gate.filter_contexts([cached], snapshot=gate.snapshot())) == 1+ session.apply(retractions=["old"])+ assert gate.filter_contexts([cached], snapshot=gate.snapshot()) == []+++def test_source_replacement_invalidates_citation_but_keeps_fact():+ session = make_session()+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ session.apply(assertions=[FactSupport("old", "A(x)")])+ session.apply(+ assertions=[FactSupport("new", "A(x)")], retractions=["old"]+ )+ results = gate.filter_contexts(+ [+ item(["A(x)"], text="A holds"),+ item(["A(x)"], supports=["old"], text="A according to old"),+ ],+ snapshot=gate.snapshot(),+ )+ assert [r.content for r in results] == ["A holds"]+++# --- constructor validation ---+++def test_constructor_rejects_non_session():+ with pytest.raises(ValidationError):+ TruthMaintenanceContextFilter(object(), session_id=SESSION_ID)+++def test_constructor_rejects_blank_session_id():+ session = make_session()+ with pytest.raises(ValidationError):+ TruthMaintenanceContextFilter(session, session_id="")+ with pytest.raises(ValidationError):+ TruthMaintenanceContextFilter(session, session_id=" ")+++def test_session_id_is_read_only():+ session = make_session()+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ with pytest.raises(AttributeError):+ gate.session_id = "other"+++# --- schema validation ---+++def invalid_annotation(**overrides):+ base = {+ "schema_version": 1,+ "session_id": SESSION_ID,+ "required_facts": ["A(x)"],+ "required_support_ids": [],+ }+ base.update(overrides)+ return base+++ "annotation",+ [+ pytest.param(+ {k: v for k, v in invalid_annotation().items() if k != "schema_version"},+ id="missing-field",+ ),+ pytest.param(+ invalid_annotation() | {"extra": 1},+ id="extra-field",+ ),+ pytest.param(+ invalid_annotation(schema_version=True),+ id="bool-schema-version",+ ),+ pytest.param(+ invalid_annotation(schema_version=2),+ id="unknown-schema-version",+ ),+ pytest.param(+ invalid_annotation(session_id="other-session"),+ id="wrong-session",+ ),+ pytest.param(+ invalid_annotation(required_facts="A(x)"),+ id="facts-not-list",+ ),+ pytest.param(+ invalid_annotation(required_support_ids="old"),+ id="supports-not-list",+ ),+ pytest.param(+ invalid_annotation(required_facts=[], required_support_ids=[]),+ id="both-empty",+ ),+ pytest.param(+ invalid_annotation(required_facts=[None]),+ id="non-string-fact",+ ),+ pytest.param(+ invalid_annotation(required_facts=[["A(x)"]]),+ id="nested-fact",+ ),+ pytest.param(+ invalid_annotation(+ required_facts=[],+ required_support_ids=["gone"],+ ),+ id="unknown-support-id",+ ),+ ],+)+def test_invalid_annotation_removes_candidate(annotation):+ session = make_session()+ session.apply(assertions=[FactSupport("old", "A(x)")])+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ candidate = RetrievedContext(+ content="stale", score=0.9, metadata={"truth_maintenance": annotation}+ )+ assert gate.filter_contexts([candidate], snapshot=gate.snapshot()) == []+++def test_missing_truth_maintenance_metadata_removes_candidate():+ session = make_session()+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ plain = RetrievedContext(content="no annotations", score=0.5)+ assert gate.filter_contexts([plain], snapshot=gate.snapshot()) == []+++def test_non_dict_truth_maintenance_metadata_removes_candidate():+ session = make_session()+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ candidate = RetrievedContext(+ content="broken", score=0.5, metadata={"truth_maintenance": "yes"}+ )+ assert gate.filter_contexts([candidate], snapshot=gate.snapshot()) == []+++def test_non_retrieved_context_candidate_raises():+ session = make_session()+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ with pytest.raises(ValidationError):+ gate.filter_contexts([object()], snapshot=gate.snapshot())+++def test_whitespace_fact_is_normalized():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ candidate = item([" A( x ) "])+ results = gate.filter_contexts([candidate], snapshot=gate.snapshot())+ assert len(results) == 1+++def test_duplicate_dependencies_are_normalized():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ candidate = item(["A(x)", "A(x)"], supports=["s1", "s1"])+ results = gate.filter_contexts([candidate], snapshot=gate.snapshot())+ assert len(results) == 1+++# --- dependency semantics ---+++def test_and_semantics_requires_every_fact():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ both = item(["A(x)", "B(x)"])+ assert gate.filter_contexts([both], snapshot=gate.snapshot()) == []+++def test_or_via_multiple_rules_keeps_conclusion():+ session = make_session(+ Rule("ab", "ab", ["A(?x)"], "B(?x)"),+ Rule("cb", "cb", ["C(?x)"], "B(?x)"),+ )+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ cached = item(["B(x)"])+ session.apply(assertions=[FactSupport("c1", "C(x)")])+ assert len(gate.filter_contexts([cached], snapshot=gate.snapshot())) == 1+++def test_direct_assertion_and_derived_fact_together():+ session = make_session(Rule("ab", "ab", ["A(?x)"], "B(?x)"))+ session.apply(assertions=[FactSupport("a1", "A(x)")])+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ candidate = item(["A(x)", "B(x)"])+ results = gate.filter_contexts([candidate], snapshot=gate.snapshot())+ assert len(results) == 1+++def test_retract_then_reactivate_restores_candidate():+ session = make_session()+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ candidate = item(["A(x)"])+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ assert len(gate.filter_contexts([candidate], snapshot=gate.snapshot())) == 1+ session.apply(retractions=["s1"])+ assert gate.filter_contexts([candidate], snapshot=gate.snapshot()) == []+ session.apply(assertions=[FactSupport("s2", "A(x)")])+ assert len(gate.filter_contexts([candidate], snapshot=gate.snapshot())) == 1+++# --- graph bundle handling ---+++def attachment(metadata=None):+ return {"id": "n1", "content": "node", "metadata": metadata or {}}+++def bundle(root_metadata, related_entities):+ return RetrievedContext(+ content="root",+ score=0.9,+ metadata=root_metadata,+ related_entities=related_entities,+ )+++def test_graph_bundle_requires_every_attachment_annotation():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ root = {"truth_maintenance": invalid_annotation()}+ valid_attachment = attachment(+ {"truth_maintenance": invalid_annotation(+ required_facts=[], required_support_ids=["s1"])}+ )+ unannotated_attachment = attachment()+ assert gate.filter_contexts(+ [bundle(root, [valid_attachment, unannotated_attachment])],+ snapshot=gate.snapshot(),+ ) == []+ assert len(+ gate.filter_contexts(+ [bundle(root, [valid_attachment])], snapshot=gate.snapshot()+ )+ ) == 1+++def test_graph_bundle_stale_attachment_removes_whole_candidate():+ session = make_session()+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ root = {"truth_maintenance": invalid_annotation()}+ stale_attachment = attachment(+ {"truth_maintenance": invalid_annotation(+ required_facts=["Old(x)"], required_support_ids=[])}+ )+ assert gate.filter_contexts(+ [bundle(root, [stale_attachment])], snapshot=gate.snapshot()+ ) == []+++def test_graph_bundle_non_list_related_fields_remove_candidate():+ session = make_session()+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ candidate = RetrievedContext(+ content="root",+ score=0.9,+ metadata={"truth_maintenance": invalid_annotation()},+ related_entities="not-a-list",+ )+ assert gate.filter_contexts([candidate], snapshot=gate.snapshot()) == []+++def test_graph_bundle_member_without_metadata_dict_removes_candidate():+ session = make_session()+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ root = {"truth_maintenance": invalid_annotation()}+ bad_member = attachment()+ bad_member.pop("metadata")+ assert gate.filter_contexts(+ [bundle(root, [bad_member])], snapshot=gate.snapshot()+ ) == []+++# --- copy semantics ---+++def test_passing_candidate_is_deep_copied_and_stamped():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ original = item(["A(x)"])+ results = gate.filter_contexts([original], snapshot=gate.snapshot())+ assert len(results) == 1+ stamped = results[0]+ assert stamped is not original+ assert stamped.metadata is not original.metadata+ assert stamped.metadata["truth_maintenance_validation"] == {+ "session_id": SESSION_ID,+ "version": session.version,+ }+ # Original is untouched by stamping and by later mutation of the copy.+ assert "truth_maintenance_validation" not in original.metadata+ stamped.metadata["truth_maintenance"]["session_id"] = "tampered"+ stamped.content = "tampered"+ assert original.metadata["truth_maintenance"]["session_id"] == SESSION_ID+ assert original.content == "Alice is eligible"+++def test_old_validation_stamp_is_overwritten_not_trusted():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ original = item(["A(x)"])+ original.metadata["truth_maintenance_validation"] = {+ "session_id": "someone-else",+ "version": 99,+ }+ results = gate.filter_contexts([original], snapshot=gate.snapshot())+ assert results[0].metadata["truth_maintenance_validation"] == {+ "session_id": SESSION_ID,+ "version": session.version,+ }+++def test_related_attachments_are_copied_not_shared():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ annotated = attachment(+ {"truth_maintenance": invalid_annotation(+ required_facts=[], required_support_ids=["s1"])}+ )+ entities = [deepcopy(annotated)]+ original = RetrievedContext(+ content="root",+ score=0.9,+ metadata={"truth_maintenance": invalid_annotation()},+ related_entities=entities,+ related_relationships=[deepcopy(annotated)],+ )+ results = gate.filter_contexts([original], snapshot=gate.snapshot())+ stamped = results[0]+ assert stamped.related_entities is not original.related_entities+ assert stamped.related_entities[0] is not original.related_entities[0]+ stamped.related_entities[0]["content"] = "tampered"+ assert original.related_entities[0]["content"] == "node"+++def test_score_and_fields_are_preserved():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ original = item(["A(x)"], text="kept text")+ original.score = 0.42+ original.source = "graph:expanded"+ results = gate.filter_contexts([original], snapshot=gate.snapshot())+ stamped = results[0]+ assert stamped.score == 0.42+ assert stamped.source == "graph:expanded"+ assert stamped.content == "kept text"+++# --- snapshot delegation and version gate ---+++def test_snapshot_delegates_to_session():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ snap = gate.snapshot()+ assert snap == session.snapshot()+++def test_assert_current_accepts_matching_version():+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ gate.assert_current(gate.snapshot())+++def test_assert_current_raises_processing_error_on_version_change():+ session = make_session()+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ stale = gate.snapshot()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ with pytest.raises(ProcessingError) as excinfo:+ gate.assert_current(stale)+ details = excinfo.value.details if hasattr(excinfo.value, "details") else {}+ assert details.get("expected") == stale.version+ assert details.get("actual") == session.version+++def test_assert_current_noop_apply_does_not_bump_version():+ session = make_session()+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ snap = gate.snapshot()+ session.apply(assertions=[])+ gate.assert_current(snap)+++def test_empty_input_returns_empty_list():+ session = make_session()+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ assert gate.filter_contexts([], snapshot=gate.snapshot()) == []+++# --- malformed root metadata ---+++ "broken_metadata",+ [None, ["truth_maintenance"], 42],+ ids=["none", "list", "int"],+)+def test_non_dict_root_metadata_removes_candidate_without_raising(broken_metadata):+ # A store record whose top-level metadata is not a dict must remove only+ # that candidate; the malformed record must never abort the whole call.+ session = make_session()+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ gate = TruthMaintenanceContextFilter(session, session_id=SESSION_ID)+ broken = item(["A(x)"], text="broken record")+ broken.metadata = broken_metadata+ valid = item(["A(x)"], text="valid record")+ results = gate.filter_contexts([broken, valid], snapshot=gate.snapshot())+ assert [r.content for r in results] == ["valid record"]diff --git a/tests/reasoning/test_truth_maintenance_snapshot.py b/tests/reasoning/test_truth_maintenance_snapshot.pynew file mode 100644index 00000000..74284a18--- /dev/null+++ b/tests/reasoning/test_truth_maintenance_snapshot.py@@ -0,0 +1,104 @@+"""Snapshot isolation and versioning tests for TruthMaintenanceSession."""++from dataclasses import FrozenInstanceError++import pytest+from semantica.reasoning import FactSupport, Rule, TruthMaintenanceSession+from semantica.utils.exceptions import ValidationError+++def test_snapshot_is_detached_after_retraction():+ session = TruthMaintenanceSession(rules=[])+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ before = session.snapshot()+ session.apply(retractions=["s1"])+ assert before.version == 1+ assert before.facts == frozenset({"A(x)"})+ assert before.active_supports == (FactSupport("s1", "A(x)"),)+ assert session.snapshot().facts == frozenset()+ with pytest.raises(FrozenInstanceError):+ before.version = 42+++def test_empty_session_snapshot():+ session = TruthMaintenanceSession(rules=[])+ snapshot = session.snapshot()+ assert snapshot.version == 0+ assert snapshot.facts == frozenset()+ assert snapshot.active_supports == ()+++def test_snapshot_supports_are_sorted_by_support_id():+ session = TruthMaintenanceSession(rules=[])+ session.apply(+ assertions=[+ FactSupport("s3", "C(x)"),+ FactSupport("s1", "A(x)"),+ FactSupport("s2", "B(x)"),+ ]+ )+ snapshot = session.snapshot()+ assert [support.support_id for support in snapshot.active_supports] == [+ "s1",+ "s2",+ "s3",+ ]+++def test_support_replacement_changes_version_and_supports_not_facts():+ session = TruthMaintenanceSession(rules=[])+ session.apply(assertions=[FactSupport("old", "A(x)")])+ session.apply(+ assertions=[FactSupport("new", "A(x)")], retractions=["old"]+ )+ snapshot = session.snapshot()+ assert snapshot.version == 2+ assert snapshot.facts == frozenset({"A(x)"})+ assert snapshot.active_supports == (FactSupport("new", "A(x)"),)+++def test_noop_apply_keeps_version_and_snapshot():+ session = TruthMaintenanceSession(rules=[])+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ before = session.snapshot()+ delta = session.apply() # empty batch is a no-op+ assert delta.version == before.version+ after = session.snapshot()+ assert after.version == before.version+ assert after.facts == before.facts+ assert after.active_supports == before.active_supports+++def test_failed_apply_leaves_snapshot_unchanged():+ session = TruthMaintenanceSession(rules=[])+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ before = session.snapshot()+ with pytest.raises(ValidationError):+ session.apply(retractions=["s1", 42]) # malformed retraction id+ after = session.snapshot()+ assert after.version == before.version+ assert after.facts == before.facts+ assert after.active_supports == before.active_supports+++def test_snapshot_includes_derived_facts():+ session = TruthMaintenanceSession(+ rules=[Rule("ab", "ab", ["A(?x)"], "B(?x)")]+ )+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ snapshot = session.snapshot()+ assert snapshot.facts == frozenset({"A(x)", "B(x)"})+ assert snapshot.active_supports == (FactSupport("s1", "A(x)"),)+++def test_snapshot_detached_from_mutation_of_returned_collections():+ session = TruthMaintenanceSession(rules=[])+ session.apply(assertions=[FactSupport("s1", "A(x)")])+ snapshot = session.snapshot()+ # facts is a frozenset, active_supports is a tuple: both immutable by+ # construction; verify a later apply does not reflect into the snapshot.+ session.apply(retractions=["s1"])+ session.apply(assertions=[FactSupport("s2", "B(x)")])+ assert snapshot.facts == frozenset({"A(x)"})+ assert snapshot.active_supports == (FactSupport("s1", "A(x)"),)+ assert snapshot.version == 1\ No newline at end of file