Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(reasoning): implement SPARQLReasoner.execute_query with store delegation and rdflib fallback (#1243)

cxzg0077996d1ab4bd0
diff --git a/semantica/reasoning/sparql_reasoner.py b/semantica/reasoning/sparql_reasoner.py
index 16be2a9f..f343812b 100644
--- a/semantica/reasoning/sparql_reasoner.py
+++ b/semantica/reasoning/sparql_reasoner.py
@@ -29,14 +29,16 @@ Author: Semantica Contributors
License: MIT
"""
-import re
+import copy
+import json
+import time
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional, Set
+from typing import Any, Dict, List, Optional, Tuple
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
-from .reasoner import Rule, Reasoner
+from .reasoner import Reasoner, Rule
@dataclass
@@ -84,9 +86,8 @@ class SPARQLReasoner:
self.triplet_store = self.config.get("triplet_store")
self.enable_inference = self.config.get("enable_inference", True)
- # Reserved for query caching once a triplet-store execution path
- # lands. execute_query() raises NotImplementedError until then, so
- # the cache cannot be populated through any public path yet.
+ # Cache for executed queries, keyed by (query, options) and
+ # populated by execute_query(); cleared via clear_cache().
self.query_cache: Dict[str, Any] = {}
def expand_query(self, query: str, **options) -> str:
@@ -200,6 +201,16 @@ class SPARQLReasoner:
Returns:
Results with inferences
+
+ Note:
+ The original bindings are preserved verbatim, in order and
+ with their duplicates: SPARQL result rows form a bag, and a
+ query without DISTINCT keeps repeated solutions. Only the
+ *newly inferred* rows are de-duplicated (against each other
+ and against the originals) before being appended. This also
+ guarantees ``inferred_count`` reflects what inference added,
+ rather than shrinking (even below zero) when the original
+ rows contained duplicates.
"""
tracking_id = self.progress_tracker.start_tracking(
module="reasoning",
@@ -208,7 +219,8 @@ class SPARQLReasoner:
)
try:
- inferred_bindings = list(query_results.bindings)
+ original_bindings = list(query_results.bindings)
+ new_bindings: List[Dict[str, Any]] = []
# Apply inference rules
if self.enable_inference:
@@ -219,20 +231,28 @@ class SPARQLReasoner:
for rule in rules:
# Check if rule can be applied to results
- new_bindings = self._apply_rule_to_results(
+ rule_bindings = self._apply_rule_to_results(
rule, query_results.bindings
)
- inferred_bindings.extend(new_bindings)
+ new_bindings.extend(rule_bindings)
- # Remove duplicates
+ # De-duplicate only the inferred rows, against each other
+ # and against the originals (which are kept as-is).
self.progress_tracker.update_tracking(
tracking_id, message="Removing duplicate bindings..."
)
- unique_bindings = self._deduplicate_bindings(inferred_bindings)
+ seen = {self._binding_key(b) for b in original_bindings}
+ added_bindings = []
+ for binding in new_bindings:
+ key = self._binding_key(binding)
+ if key not in seen:
+ seen.add(key)
+ added_bindings.append(binding)
- inferred_count = len(unique_bindings) - len(query_results.bindings)
+ final_bindings = original_bindings + added_bindings
+ inferred_count = len(added_bindings)
result = SPARQLQueryResult(
- bindings=unique_bindings,
+ bindings=final_bindings,
variables=query_results.variables,
metadata={
**query_results.metadata,
@@ -298,7 +318,10 @@ class SPARQLReasoner:
self, rule: Rule, binding: Dict[str, Any]
) -> Optional[Dict[str, Any]]:
"""Generate new binding from rule conclusion."""
- new_binding = binding.copy()
+ # Deep copy: binding values may themselves be mutable dicts
+ # (SPARQL JSON result rows), which must not be shared with the
+ # inferred row.
+ new_binding = copy.deepcopy(binding)
# Parse conclusion
if " is_a " in rule.conclusion:
@@ -313,6 +336,21 @@ class SPARQLReasoner:
return new_binding
+ @staticmethod
+ def _binding_key(binding: Dict[str, Any]) -> Tuple:
+ """Build a hashable key for a binding row.
+
+ Binding values are not guaranteed to be hashable: stores that
+ follow the SPARQL JSON results format return nested dicts
+ (``{"type": ..., "value": ...}``) for each value. Such values
+ are normalized to ``repr()`` so they can participate in the
+ deduplication key (issue: unhashable-dict TypeError).
+ """
+ normalized = tuple(
+ (str(name), repr(binding[name])) for name in sorted(binding, key=str)
+ )
+ return normalized
+
def _deduplicate_bindings(
self, bindings: List[Dict[str, Any]]
) -> List[Dict[str, Any]]:
@@ -321,8 +359,7 @@ class SPARQLReasoner:
unique = []
for binding in bindings:
- # Create hashable representation
- binding_key = tuple(sorted(binding.items()))
+ binding_key = self._binding_key(binding)
if binding_key not in seen:
seen.add(binding_key)
unique.append(binding)
@@ -333,33 +370,661 @@ class SPARQLReasoner:
"""
Execute SPARQL query with reasoning.
- Not implemented: no triplet-store execution path exists yet, so the
- query is refused loudly instead of returning an empty result set
- that callers would read as "no matches" (issue #1083).
+ The query is executed against the configured triplet store via its
+ ``execute_query`` method (validation and optimization are handled
+ by the store's query engine). When the store cannot execute SPARQL
+ natively -- no ``execute_query`` method, or a backend without
+ ``execute_sparql`` -- the triplets are pulled via ``get_triplets``
+ into an in-memory rdflib graph and the query is executed locally.
+
+ Without a triplet store the query is refused loudly instead of
+ returning an empty result set that callers would read as "no
+ matches" (issue #1083).
+
+ Note: the *original* query is executed, not the output of
+ ``expand_query()``: that output annotates the query with rule
+ comments and ``=>`` pseudo-patterns that no SPARQL engine can
+ parse. Inference still runs without rewriting the query:
+
+ * ``is_a`` rules are materialized into an in-memory rdflib
+ graph *before* the query executes, so inferred triples
+ participate in pattern matching. This holds on the fallback
+ path, and also on the native path whenever materializable
+ rules are enabled: a native backend executes the original
+ query text and cannot see rules that were never materialized
+ into it, so the query is routed through the in-memory graph;
+ * afterwards, ``infer_results()`` applies the rules to the
+ *results* as well (rules that could not be materialized are
+ covered by this step).
Args:
query: SPARQL query string
- **options: Additional options
+ **options: Additional options forwarded to the triplet
+ store (e.g. ``graph``, ``graphs``). They only apply
+ on the native execution path; the in-memory rdflib
+ path (the fallback, or the native path when
+ materializable inference rules force it) always queries
+ the full triplet set (a warning is logged when options
+ are dropped).
+
+ Returns:
+ SPARQLQueryResult with bindings and variables
Raises:
- NotImplementedError: always, until a triplet-store execution
- path lands.
+ ProcessingError: No triplet store configured, or the store
+ supports neither SPARQL execution nor triplet retrieval
+ ValidationError: The query is not valid SPARQL
+
+ Note:
+ Results are cached per ``(query, options)``. The cache has
+ no invalidation: it does not observe changes to the store's
+ triplets or to the inference rules, so call
+ ``clear_cache()`` after mutating either.
"""
- raise NotImplementedError(
- "SPARQLReasoner.execute_query() is not implemented: no "
- "triplet-store execution path exists yet. Returning an empty "
- "result set would be misread as 'no matches', so the query "
- "is refused instead."
+ tracking_id = self.progress_tracker.start_tracking(
+ module="reasoning",
+ submodule="SPARQLReasoner",
+ message="Executing SPARQL query",
)
+ try:
+ if self.triplet_store is None:
+ raise ProcessingError(
+ "SPARQLReasoner.execute_query() requires a triplet "
+ "store: pass triplet_store=... when constructing the "
+ "reasoner. Returning an empty result set would be "
+ "misread as 'no matches', so the query is refused "
+ "instead."
+ )
+
+ cache_key = self._cache_key(query, options)
+ if cache_key in self.query_cache:
+ cached_result = self.query_cache[cache_key]
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message="Returned cached result",
+ )
+ return self._copy_result(cached_result, cached=True)
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Executing query on triplet store..."
+ )
+ result = self._execute_on_store(query, **options)
+
+ if self.enable_inference and self.reasoner.rules:
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Applying inference rules..."
+ )
+ result = self.infer_results(result)
+
+ result.metadata.setdefault("cached", False)
+ # Store a private copy: mutating the returned result (or the
+ # cached one) must never corrupt the other.
+ self.query_cache[cache_key] = self._copy_result(result)
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Query executed: {len(result.bindings)} results",
+ )
+ return result
+
+ except (ValidationError, ProcessingError) as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise ProcessingError(f"Query execution failed: {e}") from e
+
def clear_cache(self) -> None:
- """Clear query cache.
+ """Clear the query cache populated by execute_query()."""
+ self.query_cache.clear()
+
+ # ── Execution-path helpers ────────────────────────────────────────────
+
+ def _cache_key(self, query: str, options: Dict[str, Any]) -> str:
+ """Build a deterministic cache key from the query and its options."""
+ try:
+ options_part = json.dumps(options, sort_keys=True, default=str)
+ except (TypeError, ValueError):
+ options_part = str(sorted(options.items(), key=str))
+ return f"{query}\n{options_part}"
+
+ @staticmethod
+ def _copy_result(
+ result: SPARQLQueryResult, cached: Optional[bool] = None
+ ) -> SPARQLQueryResult:
+ """Return a copy whose mutable containers are not shared with
+ ``result``.
- Reserved for when a triplet-store execution path lands: until then,
- ``execute_query()`` raises ``NotImplementedError`` and nothing can
- populate the cache.
+ The copy is deep: binding values and metadata entries can be
+ arbitrarily nested containers themselves (SPARQL JSON results
+ use ``{"type": ..., "value": ...}`` dicts per value, and
+ ``metadata["triples"]`` holds lists of lists). A shallow copy
+ would leave those nested structures shared, so mutation of
+ one result could still reach the other through them.
+ ``cached`` (when given) is recorded on the copy only.
"""
- self.query_cache.clear()
+ metadata = copy.deepcopy(result.metadata)
+ if cached is not None:
+ metadata["cached"] = cached
+ return SPARQLQueryResult(
+ bindings=[copy.deepcopy(binding) for binding in result.bindings],
+ variables=list(result.variables),
+ metadata=metadata,
+ )
+
+ def _execute_on_store(self, query: str, **options) -> SPARQLQueryResult:
+ """Execute the query through the triplet store, with fallback."""
+ store = self.triplet_store
+ execute = getattr(store, "execute_query", None)
+
+ # Only fall back when we can positively determine that the store
+ # backend cannot execute SPARQL; duck-typed stores without a
+ # ``_store_backend`` attribute are trusted to handle the query.
+ backend = getattr(store, "_store_backend", None)
+ backend_blocks_sparql = backend is not None and not callable(
+ getattr(backend, "execute_sparql", None)
+ )
+
+ if callable(execute) and not backend_blocks_sparql:
+ if self._inference_requires_in_memory(store):
+ # Native execution sends the raw query text to the
+ # backend, which cannot see rules that were never
+ # materialized into it: answers that only exist through
+ # inference would be missed. Route the query through
+ # the in-memory graph, which materializes the rules
+ # before the query runs (Codex).
+ self.logger.info(
+ "Inference rules are enabled and materializable: "
+ "executing the query on the in-memory rdflib graph "
+ "so inferred triples participate in matching."
+ )
+ if options:
+ self.logger.warning(
+ "Inference forces the in-memory rdflib graph, "
+ "where query options %s are not applied: the "
+ "fallback always queries the full triplet "
+ "set." % (options,)
+ )
+ return self._execute_on_rdflib_graph(query)
+ raw_result = execute(query, **options)
+ return self._coerce_query_result(raw_result)
+
+ self.logger.info(
+ "Triplet store has no native SPARQL execution path; falling "
+ "back to an in-memory rdflib graph."
+ )
+ if options:
+ self.logger.warning(
+ "Falling back to the in-memory rdflib graph, where query "
+ "options %s are not applied: the fallback always queries "
+ "the full triplet set." % (options,)
+ )
+ return self._execute_on_rdflib_graph(query)
+
+ def _inference_requires_in_memory(self, store: Any) -> bool:
+ """Whether the query must run on the in-memory graph for
+ inference to participate in WHERE matching.
+
+ Native backends execute the original query text, which cannot
+ see rules that were never materialized into the backend's
+ stored triples. When inference is enabled and at least one rule
+ is materializable, the in-memory path answers with inferred
+ triples included. Stores without ``get_triplets`` cannot take
+ that path and keep native execution (inference then only runs
+ at the result level via ``infer_results()``).
+ """
+ if not (self.enable_inference and self.reasoner.rules):
+ return False
+ if not any(
+ self._is_materializable_rule(rule) for rule in self.reasoner.rules
+ ):
+ return False
+ return callable(getattr(store, "get_triplets", None))
+
+ def _is_materializable_rule(self, rule: Rule) -> bool:
+ """Whether ``rule`` fits the ``IF ?x is_a Sub THEN ?x is_a Super``
+ form that triple materialization can express."""
+ conclusion = self._parse_is_a(rule.conclusion)
+ if conclusion is None:
+ return False
+ conclusion_var = conclusion[0]
+ conditions = rule.conditions or []
+ if not conditions:
+ return False
+ for condition in conditions:
+ parsed = self._parse_is_a(condition)
+ if parsed is None or parsed[0] != conclusion_var:
+ return False
+ return True
+
+ def _coerce_query_result(self, raw_result: Any) -> SPARQLQueryResult:
+ """Normalize a store result (QueryResult, dict, or list of
+ binding rows) into SPARQLQueryResult."""
+ if isinstance(raw_result, SPARQLQueryResult):
+ return raw_result
+
+ if isinstance(raw_result, (list, tuple)):
+ # Some stores hand back the raw solution sequence as a list
+ # of binding dicts (the ``bindings`` rows of the SPARQL JSON
+ # results format). Without this branch the list would fall
+ # through to the generic object path below, where
+ # ``getattr(result, "bindings")`` finds nothing and the rows
+ # are silently coerced into an empty result.
+ bindings = [
+ dict(item) for item in raw_result if isinstance(item, dict)
+ ]
+ if len(bindings) != len(raw_result):
+ self.logger.warning(
+ "Triplet store execute_query() returned a sequence "
+ "with %d non-dict items; they were dropped while "
+ "coercing the result to SPARQLQueryResult.",
+ len(raw_result) - len(bindings),
+ )
+ variables: List[str] = []
+ for binding in bindings:
+ for name in binding:
+ name = str(name)
+ if name not in variables:
+ variables.append(name)
+ return SPARQLQueryResult(
+ bindings=bindings,
+ variables=variables,
+ )
+
+ if isinstance(raw_result, dict):
+ bindings = raw_result.get("bindings") or []
+ variables = raw_result.get("variables") or []
+ metadata = dict(raw_result.get("metadata") or {})
+ triples = raw_result.get("triples") or []
+ execution_time = raw_result.get("execution_time") or 0.0
+ else:
+ bindings = getattr(raw_result, "bindings", None) or []
+ variables = getattr(raw_result, "variables", None) or []
+ metadata = dict(getattr(raw_result, "metadata", None) or {})
+ triples = getattr(raw_result, "triples", None) or []
+ execution_time = (
+ getattr(raw_result, "execution_time", 0.0) or 0.0
+ )
+
+ result = SPARQLQueryResult(
+ bindings=list(bindings),
+ variables=list(variables),
+ metadata=metadata,
+ )
+ if execution_time:
+ result.metadata["execution_time"] = execution_time
+ if triples:
+ result.metadata["triples"] = [tuple(t) for t in triples]
+ return result
+
+ def _execute_on_rdflib_graph(self, query: str) -> SPARQLQueryResult:
+ """Execute the query locally on an in-memory rdflib graph built
+ from the store's triplets.
+
+ Inference (``is_a`` rules) is materialized into the graph
+ *before* the query runs, so triples that only exist through
+ inference can still satisfy the query's patterns. Rules that
+ cannot be expressed as ``is_a`` triples are left to
+ ``infer_results()``, which runs on the *results* instead.
+ """
+ try:
+ from rdflib import Graph
+ except ImportError as e:
+ raise ProcessingError(
+ "rdflib is required for the in-memory SPARQL fallback."
+ ) from e
+
+ get_triplets = getattr(self.triplet_store, "get_triplets", None)
+ if not callable(get_triplets):
+ raise ProcessingError(
+ "Triplet store supports neither SPARQL execution "
+ "(execute_query) nor triplet retrieval (get_triplets); "
+ "cannot execute the query."
+ )
+
+ start_time = time.time()
+ graph = Graph()
+ for triplet in get_triplets():
+ subject = self._subject_term(triplet)
+ predicate = self._predicate_term(triplet)
+ obj = self._object_term(triplet)
+ if subject is None or predicate is None or obj is None:
+ continue
+ graph.add((subject, predicate, obj))
+
+ if len(graph) == 0:
+ # An empty graph yields a result set ("no bindings", or
+ # false for ASK) that callers would misread as "no
+ # matches" when it really means "no data": refuse loudly
+ # instead, mirroring the no-store behaviour (issue #1083).
+ raise ProcessingError(
+ "The in-memory rdflib fallback graph is empty: "
+ "get_triplets() returned no usable triples. Executing "
+ "the query would return a result set misread as 'no "
+ "matches', so the query is refused instead."
+ )
+
+ inferred_triples = 0
+ if self.enable_inference and self.reasoner.rules:
+ inferred_triples = self._materialize_inference(graph)
+
+ try:
+ raw_result = graph.query(query)
+ except Exception as e:
+ raise ValidationError(f"Invalid SPARQL query: {e}") from e
+
+ execution_time = time.time() - start_time
+ result = self._rdflib_result_to_sparql_result(raw_result)
+ result.metadata["execution_time"] = execution_time
+ if inferred_triples:
+ result.metadata["inferred_triples"] = inferred_triples
+ return result
+
+ # ── rdflib term construction ───────────────────────────────────────
+
+ _URI_PREFIXES = (
+ "http://",
+ "https://",
+ "urn:",
+ "mailto:",
+ "ftp://",
+ "file://",
+ "tag:",
+ "doi:",
+ )
+
+ @classmethod
+ def _triplet_field(cls, triplet: Any, key: str) -> Any:
+ """Read a field from a Triplet object or a plain dict, *without*
+ coercing it to ``str``.
+
+ Values that are already native RDF terms (``URIRef`` /
+ ``BNode`` / ``Literal``) must survive untouched so the fallback
+ graph keeps their types; ``str()`` here would degrade them to
+ plain literals. ``str()`` coercion is applied later, only for
+ values that genuinely need it.
+ """
+ getter = getattr(triplet, "get", None)
+ if callable(getter):
+ value = getter(key)
+ else:
+ value = getattr(triplet, key, None)
+ return value
+
+ @classmethod
+ def _triplet_metadata(cls, triplet: Any) -> Dict[str, Any]:
+ """Return the triplet's metadata dict (empty when absent)."""
+ metadata = cls._triplet_field(triplet, "metadata")
+ return metadata if isinstance(metadata, dict) else {}
+
+ @classmethod
+ def _node_term(cls, triplet: Any, key: str, blank_prefix_ok: bool = False):
+ """Build the subject or predicate term for the fallback graph.
+
+ Native RDF terms pass through; strings become ``URIRef`` (a
+ ``_:``-prefixed string becomes a blank node when
+ ``blank_prefix_ok`` -- blank nodes are only legal as subjects
+ or objects, not predicates). Non-string values are coerced to
+ their string form, mirroring the previous ``str()`` behaviour.
+ """
+ from rdflib import BNode, Literal, URIRef
+
+ value = cls._triplet_field(triplet, key)
+ if value is None or isinstance(value, (URIRef, BNode)):
+ return value
+ if isinstance(value, Literal):
+ # Literals are not legal subjects/predicates; degrade to a
+ # URIRef of the literal's text.
+ return URIRef(str(value))
+ if blank_prefix_ok and isinstance(value, str) and value.startswith("_:"):
+ return BNode(value[2:])
+ return URIRef(str(value))
+
+ @classmethod
+ def _subject_term(cls, triplet: Any):
+ """Build the subject term (blank-node prefix allowed)."""
+ return cls._node_term(triplet, "subject", blank_prefix_ok=True)
+
+ @classmethod
+ def _predicate_term(cls, triplet: Any):
+ """Build the predicate term (always a URIRef/term, no blanks)."""
+ return cls._node_term(triplet, "predicate")
+
+ @classmethod
+ def _object_term(cls, triplet: Any):
+ """Build the object term, preserving RDF typing information.
+
+ Values that are already native RDF terms pass through
+ unchanged. Otherwise the term is chosen by:
+
+ * ``_:``-prefixed string -> blank node
+ * URI-looking string (known scheme prefixes) -> ``URIRef``
+ * triplet metadata ``lang``/``language`` -> language-tagged
+ ``Literal``
+ * triplet metadata ``datatype``/``literal_datatype`` -> typed
+ ``Literal`` (resolved through ``resolve_datatype_iri``)
+ * anything else -> plain ``Literal`` of ``str(value)``
+
+ This mirrors the triplet-store behaviour (see
+ ``oxigraph_store._object_from_triplet``) so the fallback graph
+ answers typed-literal and language-tag queries the same way
+ the native backend would, instead of flattening every object
+ to an untyped literal.
+ """
+ from rdflib import BNode, Literal, URIRef
+
+ value = cls._triplet_field(triplet, "object")
+ if value is None or isinstance(value, (URIRef, BNode, Literal)):
+ return value
+ if isinstance(value, str) and value.startswith("_:"):
+ return BNode(value[2:])
+ if isinstance(value, str) and value.startswith(cls._URI_PREFIXES):
+ return URIRef(value)
+
+ metadata = cls._triplet_metadata(triplet)
+ language = metadata.get("lang") or metadata.get("language")
+ datatype = metadata.get("datatype") or metadata.get("literal_datatype")
+ text = str(value)
+ if language:
+ return Literal(text, lang=str(language))
+ if datatype:
+ datatype_iri = cls._resolve_datatype_iri(str(datatype))
+ if datatype_iri:
+ return Literal(text, datatype=URIRef(datatype_iri))
+ return Literal(text)
+
+ @staticmethod
+ def _resolve_datatype_iri(datatype: str) -> Optional[str]:
+ """Resolve a datatype name/IRI (e.g. ``xsd:integer``) to a bare
+ IRI string, or ``None`` when it cannot be resolved (the value
+ then stays an untyped literal instead of failing the query)."""
+ try:
+ from ..triplet_store.sparql_escaping import resolve_datatype_iri
+ except ImportError:
+ return None
+ try:
+ iri = resolve_datatype_iri(datatype)
+ except (ValueError, TypeError):
+ return None
+ return iri.strip("<>") if isinstance(iri, str) else None
+
+ # ── inference materialization (fallback path) ─────────────────────
+
+ @staticmethod
+ def _parse_is_a(pattern: Any) -> Optional[Tuple[str, str]]:
+ """Parse ``"?x is_a Class"`` into ``(var, class)``; None when the
+ pattern does not follow that form."""
+ if not isinstance(pattern, str):
+ return None
+ if " is_a " not in pattern:
+ return None
+ var, class_name = pattern.split(" is_a ", 1)
+ var = var.strip().lstrip("?").strip()
+ class_name = class_name.strip()
+ if not var or not class_name:
+ return None
+ return var, class_name
+
+ def _materialize_inference(self, graph: Any) -> int:
+ """Materialize ``is_a`` inference rules into ``graph``.
+
+ Rules of the form ``IF ?x is_a Sub THEN ?x is_a Super`` are
+ turned into extra ``rdf:type`` triples *before* the query runs,
+ so matches that only exist through inference can satisfy the
+ query's WHERE clause (the query itself is never rewritten:
+ ``expand_query`` output is not executable SPARQL). Only
+ ``rdf:type`` triples are matched and only ``rdf:type`` triples
+ are added, so non-type relations are never rewritten to the
+ superclass. Rules whose conditions or conclusion do not fit the
+ ``is_a`` form, or whose variables do not line up, are skipped --
+ they are still handled at the result level by
+ ``infer_results()``.
+
+ Returns the number of inferred triples added.
+ """
+ rules = list(self.reasoner.rules)
+ added_total = 0
+ # Fixpoint iteration: a rule chain (A is_a B, B is_a C) may only
+ # enable another rule after the first one fires. At most one
+ # productive pass per rule is needed.
+ for _ in range(max(1, len(rules))):
+ added_this_pass = 0
+ for rule in rules:
+ added_this_pass += self._materialize_rule(graph, rule)
+ added_total += added_this_pass
+ if added_this_pass == 0:
+ break
+ return added_total
+
+ def _materialize_rule(self, graph: Any, rule: Rule) -> int:
+ """Add the triples inferred by one ``is_a`` rule; 0 when the
+ rule cannot be materialized."""
+ if not self._is_materializable_rule(rule):
+ return 0
+ _, conclusion_class = self._parse_is_a(rule.conclusion)
+ constraints = [
+ self._parse_is_a(condition)[1] for condition in rule.conditions
+ ]
+
+ added = 0
+ for subject, predicate, obj in list(graph):
+ # ``is_a`` rules are rdf:type rewrites: only rdf:type
+ # triples are matched, so a non-type relation whose object
+ # merely shares the class local name
+ # (``:alice :role :Employee``) is never extended to the
+ # superclass.
+ if not self._predicate_is_rdf_type(predicate):
+ continue
+ if not all(
+ self._term_matches_class(obj, class_name)
+ for class_name in constraints
+ ):
+ continue
+ if self._term_matches_class(obj, conclusion_class):
+ continue
+ inferred = (subject, predicate, self._term_for_class(obj, conclusion_class))
+ if inferred not in graph:
+ graph.add(inferred)
+ added += 1
+ return added
+
+ _RDF_TYPE_IRI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"
+
+ @classmethod
+ def _predicate_is_rdf_type(cls, predicate: Any) -> bool:
+ """Whether ``predicate`` is the rdf:type predicate (the full
+ IRI, rdflib ``RDF.type``, or the ``rdf:type`` shorthand)."""
+ text = str(predicate)
+ return text == cls._RDF_TYPE_IRI or text == "rdf:type"
+
+ @staticmethod
+ def _term_matches_class(term: Any, class_name: str) -> bool:
+ """Whether ``term`` denotes ``class_name`` (exact text, or a
+ URI whose local name is ``class_name``)."""
+ text = str(term)
+ if text == class_name:
+ return True
+ for separator in ("#", "/"):
+ index = text.rfind(separator)
+ if index != -1 and text[index + 1:] == class_name:
+ return True
+ return False
+
+ @staticmethod
+ def _term_for_class(term: Any, class_name: str) -> Any:
+ """Build the term for ``class_name`` in the namespace of
+ ``term`` when possible, else a bare ``URIRef``/``Literal``."""
+ from rdflib import Literal, URIRef
+
+ if isinstance(term, Literal):
+ return Literal(class_name)
+ text = str(term)
+ for separator in ("#", "/"):
+ index = text.rfind(separator)
+ if index != -1:
+ return URIRef(text[: index + 1] + class_name)
+ return URIRef(class_name)
+
+ @staticmethod
+ def _rdflib_result_to_sparql_result(
+ raw_result: Any,
+ ) -> SPARQLQueryResult:
+ """Convert an rdflib query result into SPARQLQueryResult."""
+ result_type = getattr(raw_result, "type", None) or "SELECT"
+ metadata = {"executed_via": "rdflib_in_memory"}
+
+ if result_type in ("CONSTRUCT", "DESCRIBE"):
+ triples_graph = getattr(raw_result, "graph", None) or raw_result
+ triples = [(str(s), str(p), str(o)) for s, p, o in triples_graph]
+ return SPARQLQueryResult(
+ bindings=[],
+ variables=[],
+ metadata={
+ **metadata,
+ "result_type": result_type,
+ "triples": triples,
+ },
+ )
+
+ if result_type == "ASK":
+ ask_value = getattr(raw_result, "askAnswer", None)
+ if ask_value is None:
+ ask_value = getattr(raw_result, "boolean", None)
+ if ask_value is None:
+ ask_value = bool(raw_result)
+ return SPARQLQueryResult(
+ bindings=[],
+ variables=[],
+ metadata={
+ **metadata,
+ "result_type": "ASK",
+ "boolean": bool(ask_value),
+ },
+ )
+
+ # SELECT
+ variables = [
+ str(var) for var in (getattr(raw_result, "vars", None) or [])
+ ]
+ bindings = []
+ for row in raw_result:
+ binding = {}
+ for var in (getattr(raw_result, "vars", None) or []):
+ value = row.get(var) if hasattr(row, "get") else None
+ if value is not None:
+ binding[str(var)] = str(value)
+ bindings.append(binding)
+ return SPARQLQueryResult(
+ bindings=bindings,
+ variables=variables,
+ metadata={**metadata, "result_type": "SELECT"},
+ )
def add_inference_rule(self, rule_definition: str, **options) -> Rule:
"""Add inference rule."""
diff --git a/tests/reasoning/test_specialized_reasoners.py b/tests/reasoning/test_specialized_reasoners.py
index 51dbdc9a..5430a43a 100644
--- a/tests/reasoning/test_specialized_reasoners.py
+++ b/tests/reasoning/test_specialized_reasoners.py
@@ -1,8 +1,14 @@
import unittest
-from semantica.reasoning.sparql_reasoner import SPARQLReasoner, SPARQLQueryResult
-from semantica.reasoning.abductive_reasoner import AbductiveReasoner, Observation, HypothesisRanking
-from semantica.reasoning.deductive_reasoner import DeductiveReasoner, Premise, Argument
-from semantica.reasoning.reasoner import Rule
+from types import SimpleNamespace
+
+from semantica.reasoning.abductive_reasoner import (
+ AbductiveReasoner,
+ Observation,
+)
+from semantica.reasoning.deductive_reasoner import DeductiveReasoner, Premise
+from semantica.reasoning.sparql_reasoner import SPARQLQueryResult, SPARQLReasoner
+from semantica.utils.exceptions import ProcessingError
+
class TestSpecializedReasoners(unittest.TestCase):
def test_sparql_reasoner_expand_query(self):
@@ -30,28 +36,184 @@ class TestSpecializedReasoners(unittest.TestCase):
binding_types = [b.get("x_type") for b in inferred.bindings]
self.assertIn("Human", binding_types)
- def test_execute_query_raises_not_implemented(self):
- """Empty results must not pass as a valid answer (issue #1083).
-
- Both branches returned ``SPARQLQueryResult(bindings=[], variables=[])``
- -- with or without a triplet store -- so callers that trust an empty
- result as "no matches" silently drew wrong conclusions. Until a real
- execution path lands, refusing loudly is safer.
- """
+ def test_execute_query_without_store_raises_processing_error(self):
+ """Refuse loudly instead of returning empty results (issue #1083)."""
reasoner = SPARQLReasoner()
- with self.assertRaises(NotImplementedError):
+ with self.assertRaises(ProcessingError):
reasoner.execute_query("SELECT ?s ?p ?o WHERE { ?s ?p ?o }")
- def test_execute_query_with_triplet_store_raises_not_implemented(self):
+ def test_execute_query_with_unusable_store_raises_processing_error(self):
reasoner = SPARQLReasoner(triplet_store=object())
- with self.assertRaises(NotImplementedError):
+ with self.assertRaises(ProcessingError):
reasoner.execute_query("SELECT ?s ?p ?o WHERE { ?s ?p ?o }")
- def test_execute_query_error_explains_why_the_query_is_refused(self):
- reasoner = SPARQLReasoner()
- with self.assertRaises(NotImplementedError) as ctx:
- reasoner.execute_query("SELECT ?s WHERE { ?s ?p ?o }")
- self.assertIn("not implemented", str(ctx.exception))
+ def _fake_store(self):
+ class FakeStore:
+ def __init__(self):
+ self.received = None
+
+ def execute_query(self, query, **options):
+ self.received = (query, options)
+ return {
+ "bindings": [{"x": "John"}],
+ "variables": ["x"],
+ "metadata": {"optimized": True},
+ }
+
+ return FakeStore()
+
+ def _triplet_only_store(self):
+ class TripletOnlyStore:
+ def get_triplets(self):
+ return [
+ SimpleNamespace(
+ subject="urn:alice", predicate="urn:worksAt", object="ACME"
+ ),
+ SimpleNamespace(
+ subject="urn:bob", predicate="urn:worksAt", object="Globex"
+ ),
+ ]
+
+ return TripletOnlyStore()
+
+ def test_execute_query_delegates_to_store(self):
+ store = self._fake_store()
+ reasoner = SPARQLReasoner(triplet_store=store, enable_inference=False)
+
+ result = reasoner.execute_query("SELECT ?x WHERE { ?x a :Person }")
+
+ self.assertEqual(result.bindings, [{"x": "John"}])
+ self.assertEqual(result.variables, ["x"])
+ self.assertEqual(store.received[0], "SELECT ?x WHERE { ?x a :Person }")
+ self.assertTrue(result.metadata.get("optimized"))
+
+ def test_execute_query_delegated_result_is_cached(self):
+ reasoner = SPARQLReasoner(
+ triplet_store=self._fake_store(), enable_inference=False
+ )
+ query = "SELECT ?x WHERE { ?x a :Person }"
+
+ first = reasoner.execute_query(query)
+ second = reasoner.execute_query(query)
+
+ self.assertFalse(first.metadata.get("cached"))
+ self.assertTrue(second.metadata.get("cached"))
+ self.assertEqual(second.bindings, first.bindings)
+
+ def test_execute_query_applies_result_level_inference(self):
+ reasoner = SPARQLReasoner(
+ triplet_store=self._fake_store(), enable_inference=True
+ )
+ reasoner.add_inference_rule("IF ?x is_a Person THEN ?x is_a Human")
+
+ result = reasoner.execute_query("SELECT ?x WHERE { ?x a :Person }")
+
+ binding_types = [b.get("x_type") for b in result.bindings]
+ self.assertIn("Human", binding_types)
+
+ def test_execute_query_falls_back_to_rdflib_memory_graph(self):
+ reasoner = SPARQLReasoner(
+ triplet_store=self._triplet_only_store(), enable_inference=False
+ )
+
+ result = reasoner.execute_query("SELECT ?s ?o WHERE { ?s <urn:worksAt> ?o }")
+
+ self.assertEqual(
+ result.bindings,
+ [
+ {"s": "urn:alice", "o": "ACME"},
+ {"s": "urn:bob", "o": "Globex"},
+ ],
+ )
+ self.assertEqual(result.metadata.get("executed_via"), "rdflib_in_memory")
+
+ def test_execute_query_rdflib_fallback_ask(self):
+ reasoner = SPARQLReasoner(
+ triplet_store=self._triplet_only_store(), enable_inference=False
+ )
+
+ result = reasoner.execute_query("ASK { ?s <urn:worksAt> ?o }")
+
+ self.assertTrue(result.metadata.get("boolean"))
+
+ def test_execute_query_skips_delegation_when_backend_lacks_sparql(self):
+ store = self._fake_store()
+ store._store_backend = object() # backend without execute_sparql
+ reasoner = SPARQLReasoner(triplet_store=store, enable_inference=False)
+
+ # No get_triplets either, so the rdflib fallback must refuse loudly
+ # instead of silently executing on the store's backend.
+ with self.assertRaises(ProcessingError):
+ reasoner.execute_query("SELECT ?s ?p ?o WHERE { ?s ?p ?o }")
+
+ def test_execute_query_cached_result_is_isolated_from_returned_result(self):
+ """Mutating a returned result must not corrupt the cache."""
+ store = self._fake_store()
+ reasoner = SPARQLReasoner(
+ triplet_store=store, enable_inference=False
+ )
+ query = "SELECT ?x WHERE { ?x a :Person }"
+
+ first = reasoner.execute_query(query)
+ first.bindings.append({"x": "Injected"})
+ first.bindings[0]["x"] = "Mutated"
+ first.metadata["cached"] = True
+
+ second = reasoner.execute_query(query)
+
+ self.assertTrue(second.metadata.get("cached"))
+ self.assertEqual(second.bindings, [{"x": "John"}])
+
+ def test_execute_query_cache_key_distinguishes_options(self):
+ store = self._fake_store()
+ reasoner = SPARQLReasoner(
+ triplet_store=store, enable_inference=False
+ )
+ query = "SELECT ?x WHERE { ?x a :Person }"
+
+ reasoner.execute_query(query, graph="urn:g1")
+ second = reasoner.execute_query(query, graph="urn:g2")
+
+ # Different options: the second call must hit the store again
+ # with its own options instead of returning the cached result.
+ self.assertFalse(second.metadata.get("cached"))
+ self.assertEqual(store.received[1], {"graph": "urn:g2"})
+
+ def test_execute_query_rdflib_fallback_coerces_non_string_values(self):
+ """Non-string triplet values must not be silently dropped."""
+
+ class MixedStore:
+ def get_triplets(self):
+ return [
+ SimpleNamespace(
+ subject="urn:alice", predicate="urn:age", object=42
+ )
+ ]
+
+ reasoner = SPARQLReasoner(
+ triplet_store=MixedStore(), enable_inference=False
+ )
+
+ result = reasoner.execute_query(
+ "SELECT ?o WHERE { ?s <urn:age> ?o }"
+ )
+
+ self.assertEqual(result.bindings, [{"o": "42"}])
+
+ def test_execute_query_rdflib_fallback_construct(self):
+ reasoner = SPARQLReasoner(
+ triplet_store=self._triplet_only_store(), enable_inference=False
+ )
+
+ result = reasoner.execute_query(
+ "CONSTRUCT { ?s <urn:employer> ?o } WHERE { ?s <urn:worksAt> ?o }"
+ )
+
+ self.assertEqual(result.metadata.get("result_type"), "CONSTRUCT")
+ self.assertIn(
+ ("urn:alice", "urn:employer", "ACME"),
+ result.metadata.get("triples", []),
+ )
def test_abductive_reasoner_generate_hypotheses(self):
reasoner = AbductiveReasoner()
@@ -99,5 +261,405 @@ class TestSpecializedReasoners(unittest.TestCase):
self.assertEqual(len(proof.steps), 1)
self.assertEqual(proof.steps[0].statement, "Child(Jane, John)")
+class TestExecuteQueryReviewFixes(unittest.TestCase):
+ """Regression tests for the bot-review fixes on PR #1243."""
+
+ RDF_TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"
+
+ def _triplet(self, subject, predicate, obj, metadata=None):
+ return SimpleNamespace(
+ subject=subject, predicate=predicate, object=obj, metadata=metadata
+ )
+
+ def _store(self, triplets):
+ class TripletOnlyStore:
+ def get_triplets(self):
+ return list(triplets)
+
+ return TripletOnlyStore()
+
+ def test_execute_query_coerces_list_of_binding_dicts(self):
+ """Stores returning a list of binding rows keep their rows (Qodo)."""
+
+ class ListStore:
+ def execute_query(self, query, **options):
+ return [{"x": "a"}, "junk", {"y": "b"}]
+
+ reasoner = SPARQLReasoner(triplet_store=ListStore(), enable_inference=False)
+
+ result = reasoner.execute_query("SELECT ?x ?y WHERE { ?x ?y ?z }")
+
+ self.assertEqual(result.bindings, [{"x": "a"}, {"y": "b"}])
+ self.assertEqual(result.variables, ["x", "y"])
+
+ def test_execute_query_empty_fallback_graph_raises_processing_error(self):
+ """An empty fallback graph must be refused, not read as 'no matches'."""
+ reasoner = SPARQLReasoner(
+ triplet_store=self._store([]), enable_inference=False
+ )
+
+ with self.assertRaises(ProcessingError):
+ reasoner.execute_query("SELECT ?s ?p ?o WHERE { ?s ?p ?o }")
+
+ def test_execute_query_fallback_graph_empty_after_invalid_triplets(self):
+ """Triplets dropped for missing fields still leave a usable store:
+ the empty graph must be refused the same way."""
+ reasoner = SPARQLReasoner(
+ triplet_store=self._store([self._triplet(None, "urn:p", "urn:v")]),
+ enable_inference=False,
+ )
+
+ with self.assertRaises(ProcessingError):
+ reasoner.execute_query("SELECT ?s WHERE { ?s ?p ?o }")
+
+ def test_execute_query_fallback_preserves_typed_literals(self):
+ """Typed literals answer typed-literal queries (Codex/Qodo)."""
+ reasoner = SPARQLReasoner(
+ triplet_store=self._store(
+ [
+ self._triplet(
+ "urn:alice",
+ "urn:age",
+ "42",
+ metadata={"datatype": "xsd:integer"},
+ ),
+ self._triplet("urn:bob", "urn:age", "42"),
+ ]
+ ),
+ enable_inference=False,
+ )
+
+ result = reasoner.execute_query(
+ 'SELECT ?s WHERE { ?s <urn:age> "42"^^xsd:integer }'
+ )
+
+ self.assertEqual(result.bindings, [{"s": "urn:alice"}])
+
+ def test_execute_query_fallback_literal_datatype_key(self):
+ """The ``literal_datatype`` metadata key types the literal too."""
+ reasoner = SPARQLReasoner(
+ triplet_store=self._store(
+ [
+ self._triplet(
+ "urn:carol",
+ "urn:age",
+ "42",
+ metadata={"literal_datatype": "xsd:integer"},
+ )
+ ]
+ ),
+ enable_inference=False,
+ )
+
+ result = reasoner.execute_query(
+ 'SELECT ?s WHERE { ?s <urn:age> "42"^^xsd:integer }'
+ )
+
+ self.assertEqual(result.bindings, [{"s": "urn:carol"}])
+
+ def test_execute_query_fallback_unknown_datatype_degrades_to_plain_literal(self):
+ """An unresolvable datatype degrades instead of failing the query."""
+ reasoner = SPARQLReasoner(
+ triplet_store=self._store(
+ [
+ self._triplet(
+ "urn:alice",
+ "urn:age",
+ "42",
+ metadata={"datatype": "not-a-real-prefix:x"},
+ )
+ ]
+ ),
+ enable_inference=False,
+ )
+
+ result = reasoner.execute_query('SELECT ?s WHERE { ?s <urn:age> "42" }')
+
+ self.assertEqual(result.bindings, [{"s": "urn:alice"}])
+
+ def test_execute_query_fallback_preserves_language_tags(self):
+ """Language-tagged literals answer language-tagged queries."""
+ reasoner = SPARQLReasoner(
+ triplet_store=self._store(
+ [
+ self._triplet(
+ "urn:alice",
+ "urn:label",
+ "hello",
+ metadata={"lang": "en"},
+ ),
+ self._triplet(
+ "urn:bob",
+ "urn:label",
+ "hello",
+ metadata={"language": "fr"},
+ ),
+ ]
+ ),
+ enable_inference=False,
+ )
+
+ result = reasoner.execute_query(
+ 'SELECT ?s WHERE { ?s <urn:label> "hello"@en }'
+ )
+
+ self.assertEqual(result.bindings, [{"s": "urn:alice"}])
+
+ def test_execute_query_fallback_supports_blank_node_subjects(self):
+ reasoner = SPARQLReasoner(
+ triplet_store=self._store(
+ [self._triplet("_:b1", "urn:worksAt", "ACME")]
+ ),
+ enable_inference=False,
+ )
+
+ result = reasoner.execute_query("SELECT ?s WHERE { ?s <urn:worksAt> ?o }")
+
+ self.assertEqual([b["s"] for b in result.bindings], ["b1"])
+
+ def test_infer_results_preserves_duplicate_original_bindings(self):
+ """Original rows keep SPARQL bag semantics (Qodo): duplicates in,
+ duplicates out; only inferred rows are de-duplicated."""
+ reasoner = SPARQLReasoner()
+ reasoner.add_inference_rule("IF ?x is_a Person THEN ?x is_a Human")
+
+ results = SPARQLQueryResult(
+ bindings=[{"x": "John"}, {"x": "John"}], variables=["x"]
+ )
+
+ inferred = reasoner.infer_results(results)
+
+ originals = [b for b in inferred.bindings if "x_type" not in b]
+ self.assertEqual(originals, [{"x": "John"}, {"x": "John"}])
+ self.assertEqual(inferred.metadata["original_count"], 2)
+ self.assertEqual(inferred.metadata["inferred_count"], 1)
+
+ def test_infer_results_handles_unhashable_binding_values(self):
+ """Binding rows with dict values (SPARQL JSON form) must not crash
+ the de-duplication with TypeError (Codex)."""
+ reasoner = SPARQLReasoner()
+ reasoner.add_inference_rule("IF ?x is_a Person THEN ?x is_a Human")
+
+ results = SPARQLQueryResult(
+ bindings=[{"x": {"nested": [1]}}], variables=["x"]
+ )
+
+ inferred = reasoner.infer_results(results)
+
+ self.assertEqual(inferred.bindings[0]["x"], {"nested": [1]})
+ self.assertEqual(inferred.metadata["inferred_count"], 1)
+ # The inferred row must not share mutable state with the original.
+ inferred.bindings[1]["x"]["nested"].append(99)
+ self.assertEqual(inferred.bindings[0]["x"], {"nested": [1]})
+
+ def test_execute_query_cache_isolates_nested_structures(self):
+ """Cached results are deep-copied: nested binding values and
+ metadata entries must never be shared (Qodo/Codex)."""
+
+ class NestedStore:
+ def execute_query(self, query, **options):
+ return {
+ "bindings": [{"x": {"nested": [1]}}],
+ "variables": ["x"],
+ "metadata": {"triples": [("urn:s", "urn:p", "urn:o")]},
+ }
+
+ reasoner = SPARQLReasoner(
+ triplet_store=NestedStore(), enable_inference=False
+ )
+ query = "SELECT ?x WHERE { ?x ?p ?o }"
+
+ first = reasoner.execute_query(query)
+ first.bindings[0]["x"]["nested"].append(99)
+ first.metadata["triples"].append("junk")
+
+ second = reasoner.execute_query(query)
+ self.assertTrue(second.metadata.get("cached"))
+ second.bindings[0]["x"]["nested"].append(99)
+ second.metadata["triples"].append("junk")
+
+ third = reasoner.execute_query(query)
+ self.assertEqual(third.bindings, [{"x": {"nested": [1]}}])
+ self.assertEqual(
+ third.metadata["triples"], [("urn:s", "urn:p", "urn:o")]
+ )
+
+ def test_execute_query_fallback_materializes_is_a_rules(self):
+ """Matches that only exist through inference satisfy the WHERE
+ clause: rules are materialized before the query runs (Qodo)."""
+ reasoner = SPARQLReasoner(
+ triplet_store=self._store(
+ [
+ self._triplet(
+ "urn:alice", self.RDF_TYPE, "http://example.org/Employee"
+ )
+ ]
+ ),
+ enable_inference=True,
+ )
+ reasoner.add_inference_rule("IF ?x is_a Employee THEN ?x is_a Person")
+
+ result = reasoner.execute_query(
+ "SELECT ?s WHERE { ?s a <http://example.org/Person> }"
+ )
+
+ self.assertEqual(result.bindings, [{"s": "urn:alice"}])
+ self.assertEqual(result.metadata.get("inferred_triples"), 1)
+
+ def test_execute_query_fallback_materialization_reaches_fixpoint(self):
+ """Rule chains fire through fixpoint iteration, one pass at a time."""
+ reasoner = SPARQLReasoner(
+ triplet_store=self._store(
+ [
+ self._triplet(
+ "urn:alice", self.RDF_TYPE, "http://example.org/Employee"
+ )
+ ]
+ ),
+ enable_inference=True,
+ )
+ reasoner.add_inference_rule("IF ?x is_a Employee THEN ?x is_a Manager")
+ reasoner.add_inference_rule("IF ?x is_a Manager THEN ?x is_a Person")
+
+ result = reasoner.execute_query(
+ "SELECT ?s WHERE { ?s a <http://example.org/Person> }"
+ )
+
+ self.assertEqual(result.bindings, [{"s": "urn:alice"}])
+ self.assertEqual(result.metadata.get("inferred_triples"), 2)
+
+ def test_execute_query_fallback_skips_unmaterializable_rules(self):
+ """Rules whose conditions are not plain ``is_a`` patterns cannot be
+ materialized into triples; they are skipped instead of breaking the
+ query (result-level inference still handles them)."""
+ reasoner = SPARQLReasoner(
+ triplet_store=self._store(
+ [self._triplet("urn:alice", "urn:worksAt", "ACME")]
+ ),
+ enable_inference=True,
+ )
+ reasoner.add_inference_rule("IF ?x worksAt ACME THEN ?x is_a Employee")
+
+ result = reasoner.execute_query(
+ "SELECT ?s ?o WHERE { ?s <urn:worksAt> ?o }"
+ )
+
+ self.assertEqual(result.bindings, [{"s": "urn:alice", "o": "ACME"}])
+ self.assertNotIn("inferred_triples", result.metadata)
+
+
+ def test_execute_query_does_not_extend_non_type_triples(self):
+ """is_a materialization only fires on rdf:type triples: a
+ non-type relation whose object shares the class local name must
+ not be rewritten to the superclass (Codex)."""
+ reasoner = SPARQLReasoner(
+ triplet_store=self._store(
+ [
+ self._triplet(
+ "urn:alice", self.RDF_TYPE, "http://example.org/Employee"
+ ),
+ self._triplet(
+ "urn:alice", "urn:role", "http://example.org/Employee"
+ ),
+ ]
+ ),
+ enable_inference=True,
+ )
+ reasoner.add_inference_rule("IF ?x is_a Employee THEN ?x is_a Person")
+
+ result = reasoner.execute_query("SELECT ?s ?o WHERE { ?s <urn:role> ?o }")
+
+ self.assertEqual(
+ result.bindings, [{"s": "urn:alice", "o": "http://example.org/Employee"}]
+ )
+ # Only the rdf:type triple was extended, not the urn:role relation.
+ self.assertEqual(result.metadata.get("inferred_triples"), 1)
+
+ def test_execute_query_non_type_triples_do_not_satisfy_class_patterns(self):
+ """A relation like ``:alice :role :Employee`` must not make
+ ``?s a :Person`` match: class patterns only answer through
+ rdf:type triples."""
+ reasoner = SPARQLReasoner(
+ triplet_store=self._store(
+ [
+ self._triplet(
+ "urn:alice", "urn:role", "http://example.org/Employee"
+ )
+ ]
+ ),
+ enable_inference=True,
+ )
+ reasoner.add_inference_rule("IF ?x is_a Employee THEN ?x is_a Person")
+
+ result = reasoner.execute_query(
+ "SELECT ?s WHERE { ?s a <http://example.org/Person> }"
+ )
+
+ self.assertEqual(result.bindings, [])
+
+ def test_execute_query_native_path_materializes_inference_first(self):
+ """Native backends cannot see rules that were never stored: when
+ materializable is_a rules are enabled, the query runs on the
+ in-memory graph so inferred answers are not missed (Codex)."""
+
+ test_case = self
+
+ class NativeStore:
+ def get_triplets(self):
+ return [
+ test_case._triplet(
+ "urn:alice", test_case.RDF_TYPE, "http://example.org/Employee"
+ )
+ ]
+
+ def execute_query(self, query, **options):
+ # The backend has no inferred triples stored: without
+ # the fix this (empty) native result is what callers see.
+ return {"bindings": [], "variables": ["s"]}
+
+ reasoner = SPARQLReasoner(
+ triplet_store=NativeStore(), enable_inference=True
+ )
+ reasoner.add_inference_rule("IF ?x is_a Employee THEN ?x is_a Person")
+
+ result = reasoner.execute_query(
+ "SELECT ?s WHERE { ?s a <http://example.org/Person> }"
+ )
+
+ self.assertEqual(result.bindings, [{"s": "urn:alice"}])
+ self.assertEqual(result.metadata.get("executed_via"), "rdflib_in_memory")
+ self.assertEqual(result.metadata.get("inferred_triples"), 1)
+
+ def test_execute_query_keeps_native_path_when_rules_not_materializable(self):
+ """Stores with native execution keep it when the enabled rules
+ cannot be materialized (those rules only ever ran at the result
+ level)."""
+
+ class NativeStore:
+ def __init__(self):
+ self.received = None
+
+ def get_triplets(self):
+ return []
+
+ def execute_query(self, query, **options):
+ self.received = (query, options)
+ return {"bindings": [{"x": "John"}], "variables": ["x"]}
+
+ store = NativeStore()
+ reasoner = SPARQLReasoner(triplet_store=store, enable_inference=True)
+ reasoner.add_inference_rule("IF ?x worksAt ACME THEN ?x is_a Employee")
+
+ result = reasoner.execute_query("SELECT ?x WHERE { ?x a :Person }")
+
+ # The native result is kept and the non-materializable rule still
+ # applies at the result level (adding the x_type annotation row).
+ self.assertEqual(
+ result.bindings, [{"x": "John"}, {"x": "John", "x_type": "Employee"}]
+ )
+ self.assertEqual(store.received[0], "SELECT ?x WHERE { ?x a :Person }")
+
+
if __name__ == "__main__":
+
unittest.main()