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
[BUG] SHACL to_shacl emits a doubled xsd: prefix for already-qualified ranges (#1792)
Kevincc13b6172887
diff --git a/semantica/ontology/ontology_generator.py b/semantica/ontology/ontology_generator.pyindex 709a73dd..d4229d1b 100644--- a/semantica/ontology/ontology_generator.py+++ b/semantica/ontology/ontology_generator.py@@ -828,6 +828,12 @@ class SHACLGenerator:"uri": "xsd:anyURI", "anyuri": "xsd:anyURI",}+ #: An IRI begins with a scheme: ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) ":".+ #: Matching the scheme grammar (rather than looking for ``://``) also catches+ #: absolute IRIs whose scheme is not followed by slashes, such as ``urn:``+ #: and ``doi:``, and covers qualified names like ``xsd:string``.+ _IRI_SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.\-]*:")+def __init__(self,base_uri: str = "https://semantica.dev/shapes/",@@ -1237,6 +1243,25 @@ class SHACLGenerator:return f"<{resolved}>"return resolved+ def _turtle_datatype(self, graph: SHACLGraph, datatype: str) -> str:+ """+ Turtle-facing datatype: angle brackets for IRIs, bare qname only if declared.++ ``_resolve_xsd`` may hand back a declared prefix name (``xsd:string``) or+ an absolute IRI, since #1788 leaves anything already qualified alone.+ Interpolating the latter produced ``sh:datatype http://...#string ;``,+ which RDFLib rejects as BadSyntax, and ``urn:`` / ``doi:`` came out as+ undeclared prefixed names for the same reason. Turtle only allows a+ prefix name when ``@prefix`` declared it, so anything else is bracketed.+ """+ value = datatype.strip()+ prefix, separator, _ = value.partition(":")+ if separator and prefix in graph.prefixes:+ return value+ if self._IRI_SCHEME_RE.match(value):+ return f"<{value}>"+ return value+def _serialize_turtle(self, graph: SHACLGraph) -> str:lines = [self._prefix_decls(graph), ""]lines.append(f"<{graph.shapes_uri}> a owl:Ontology .")@@ -1264,7 +1289,7 @@ class SHACLGenerator:parts = [" sh:property ["]parts.append(f' sh:path {self._uri(graph, ps.path, "property")} ;')if ps.datatype:- parts.append(f" sh:datatype {ps.datatype} ;")+ parts.append(f" sh:datatype {self._turtle_datatype(graph, ps.datatype)} ;")if ps.class_:parts.append(f' sh:class {self._uri(graph, ps.class_, "class")} ;')if ps.min_count is not None:@@ -1394,6 +1419,14 @@ class SHACLGenerator:# ── Helper ────────────────────────────────────────────────────────────────def _resolve_xsd(self, range_str: str) -> str:- """Map ontology range strings to xsd:-prefixed datatypes."""- key = range_str.lower().strip()- return self._XSD_ALIASES.get(key, f"xsd:{range_str}")+ """Map ontology range strings to xsd:-prefixed datatypes.++ A range that is already an IRI is returned unchanged, so the prefix is+ never doubled (#1788). That covers both qualified names (``xsd:string``)+ and absolute IRIs, including schemes that carry no slashes such as+ ``urn:example:datatype``. Only a bare name such as ``string`` is mapped+ through the alias table.+ """+ if self._IRI_SCHEME_RE.match(range_str.strip()):+ return range_str+ return self._XSD_ALIASES.get(range_str.lower().strip(), f"xsd:{range_str}")diff --git a/tests/ontology/test_shacl_xsd_datatype_prefix.py b/tests/ontology/test_shacl_xsd_datatype_prefix.pynew file mode 100644index 00000000..f21d84e1--- /dev/null+++ b/tests/ontology/test_shacl_xsd_datatype_prefix.py@@ -0,0 +1,105 @@+"""Regression tests for #1788: _resolve_xsd must not double the xsd: prefix.++A range that already carries the prefix (``xsd:string``) or that is a full IRI+used to come back as ``xsd:xsd:string`` / ``xsd:http://...#string``, which is+not a resolvable IRI, so the generated ``sh:datatype`` constraint could never+match. Every range must resolve to a single, valid datatype IRI.+"""++import pytest++from semantica.ontology import SHACLGenerator+++def generator():+ return SHACLGenerator()+++def test_already_xsd_qualified_range_is_left_alone(generator):+ assert generator._resolve_xsd("xsd:string") == "xsd:string"+ assert generator._resolve_xsd("xsd:integer") == "xsd:integer"+++def test_bare_names_still_map_to_xsd(generator):+ assert generator._resolve_xsd("string") == "xsd:string"+ assert generator._resolve_xsd("int") == "xsd:integer"+ assert generator._resolve_xsd("datetime") == "xsd:dateTime"+++def test_absolute_iri_range_is_left_alone(generator):+ iri = "http://www.w3.org/2001/XMLSchema#string"+ assert generator._resolve_xsd(iri) == iri+++def test_scheme_without_slashes_is_left_alone(generator):+ # A URN or DOI is an absolute IRI too, even without "//".+ assert generator._resolve_xsd("urn:example:datatype") == "urn:example:datatype"+ assert generator._resolve_xsd("doi:10.1000/182") == "doi:10.1000/182"+++def test_property_shape_carries_a_single_prefix(generator):+ shape = generator._build_property_shape(+ {"type": "datatype", "range": "xsd:string", "name": "title"}+ )+ assert shape.datatype == "xsd:string"++ bare = generator._build_property_shape(+ {"type": "datatype", "range": "string", "name": "title"}+ )+ assert bare.datatype == "xsd:string"+++# A resolved datatype reaches the serializers as either a declared prefix name+# or an absolute IRI. Turtle is the only format that pastes it through+# unmodified, so it was the only one that emitted the absolute form unbracketed.+rdflib = pytest.importorskip("rdflib")++from rdflib import Graph, URIRef # noqa: E402++SH_DATATYPE = URIRef("http://www.w3.org/ns/shacl#datatype")++# range → the datatype IRI the serialized shapes have to carry+DATATYPE_CASES = [+ ("xsd:string", "http://www.w3.org/2001/XMLSchema#string"),+ ("string", "http://www.w3.org/2001/XMLSchema#string"),+ (+ "http://www.w3.org/2001/XMLSchema#string",+ "http://www.w3.org/2001/XMLSchema#string",+ ),+ ("urn:example:datatype", "urn:example:datatype"),+ ("doi:10.1000/182", "doi:10.1000/182"),+]++# rdflib's plugin name differs from the generator's format name for N-Triples+RDFLIB_FORMAT = {"turtle": "turtle", "json-ld": "json-ld", "n-triples": "nt"}+++def _ontology_with_datatype(range_):+ return {+ "namespace": {"base_uri": "http://example.org/core/"},+ "classes": [{"name": "Person", "label": "Person"}],+ "properties": [+ {"name": "title", "type": "datatype", "range": range_, "domain": "Person"}+ ],+ }++[email protected]("range_,expected", DATATYPE_CASES)+def test_turtle_serialization_round_trips_datatype(generator, range_, expected):+ shapes = generator.generate(_ontology_with_datatype(range_))+ parsed = Graph()+ parsed.parse(data=generator.serialize(shapes, "turtle"), format="turtle")++ assert {str(dt) for dt in parsed.objects(None, SH_DATATYPE)} == {expected}++[email protected]("range_,expected", DATATYPE_CASES)[email protected]("fmt", sorted(RDFLIB_FORMAT))+def test_every_serialization_format_parses(generator, range_, expected, fmt):+ shapes = generator.generate(_ontology_with_datatype(range_))+ parsed = Graph()+ parsed.parse(data=generator.serialize(shapes, fmt), format=RDFLIB_FORMAT[fmt])++ assert {str(dt) for dt in parsed.objects(None, SH_DATATYPE)} == {expected}+