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
fix: RDF4JStore serializes plain literals as invalid IRIs
KaifAhmad1d98135d9b5fe
diff --git a/semantica/triplet_store/rdf4j_store.py b/semantica/triplet_store/rdf4j_store.pyindex 4cc0f99a..005c22bc 100644--- a/semantica/triplet_store/rdf4j_store.py+++ b/semantica/triplet_store/rdf4j_store.py@@ -26,7 +26,9 @@ Author: Semantica ContributorsLicense: MIT"""+import refrom typing import Any, Dict, List, Optional+from urllib.parse import urlparseimport requestsfrom rdflib import Graph, Literal@@ -503,23 +505,49 @@ class RDF4JStore:self.logger.error(f"Delete triplet failed: {e}")raise ProcessingError(f"Delete triplet failed: {e}")+ def _is_uri_value(self, value: str) -> bool:+ """+ Detect if a value should be serialized as an IRI.++ Byte-for-byte copy of BlazegraphStore._is_uri_value, so both backends+ agree on which triplet objects are IRIs vs. literals.+ """+ if not isinstance(value, str) or not value:+ return False+ if value.startswith("<") and value.endswith(">"):+ return True+ parsed = urlparse(value)+ if parsed.scheme not in {"http", "https", "urn"}:+ return False+ # Reject strings that only look like URIs (e.g. "http not a uri")+ return not re.search(r"\s", value)+def _format_object_for_ntriples(self, triplet: Triplet) -> str:"""Format triplet object as IRI or literal based on metadata."""obj = triplet.objectmetadata = triplet.metadata or {}++ if self._is_uri_value(obj):+ if obj.startswith("<") and obj.endswith(">"):+ inner = obj[1:-1]+ if " " in inner or ">" in inner:+ raise ValueError(f"IRI contains invalid characters: {obj!r}")+ return obj+ return f"<{obj}>"++ escaped = sparql_escaping.escape_literal(obj)datatype = metadata.get("datatype") or metadata.get("literal_datatype")language = metadata.get("lang") or metadata.get("language")- if datatype or language:- escaped = sparql_escaping.escape_literal(obj)- if datatype:- datatype_iri = sparql_escaping.resolve_datatype_iri(datatype)- return f'"{escaped}"^^{datatype_iri}'+ if datatype:+ datatype_iri = sparql_escaping.resolve_datatype_iri(datatype)+ return f'"{escaped}"^^{datatype_iri}'+ if language:if not sparql_escaping.LANG_TAG_RE.match(str(language)):raise ValueError(f"Invalid language tag {language!r}: must match RFC 5646")return f'"{escaped}"@{language}'- return f"<{obj}>"+ return f'"{escaped}"'def _triplets_to_ntriples(self, triplets: List[Triplet]) -> str:"""Convert triplets to N-Triples format."""diff --git a/tests/triplet_store/test_rdf4j_store.py b/tests/triplet_store/test_rdf4j_store.pyindex 425279bd..4ef4f16b 100644--- a/tests/triplet_store/test_rdf4j_store.py+++ b/tests/triplet_store/test_rdf4j_store.py@@ -461,6 +461,30 @@ class TestRDF4JStoreQodoBugfixes(unittest.TestCase):self.assertEqual(str(o.datatype), "http://www.w3.org/2001/XMLSchema#integer")self.assertIsNone(o.language)+ def test_ntriples_serialization_plain_literal_without_metadata(self):+ # Regression test: an object with no datatype/lang metadata and no+ # URI shape (e.g. typical NER/extraction output like "Alice") must+ # be serialized as a plain quoted literal, not wrapped as `<Alice>`+ # (which is not a valid IRI and corrupts the write).+ store = _make_connected_store()+ t = Triplet(+ subject="http://ex.org/s1",+ predicate="http://ex.org/name",+ object="Alice",+ )+ nt = store._triplets_to_ntriples([t])+ self.assertNotIn("<Alice>", nt)++ from rdflib import Graph, Literal+ g = Graph()+ g.parse(data=nt, format="nt")+ self.assertEqual(len(g), 1)+ for s, p, o in g:+ self.assertEqual(str(s), "http://ex.org/s1")+ self.assertEqual(str(p), "http://ex.org/name")+ self.assertIsInstance(o, Literal)+ self.assertEqual(str(o), "Alice")+def test_add_triplets_validates_graph_uri(self):from semantica.utils.exceptions import ValidationErrorstore = _make_connected_store()