Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(export): close Turtle IRI normalization gaps

mikemikimike1f868b97793e
diff --git a/semantica/export/rdf_exporter.py b/semantica/export/rdf_exporter.py
index 5b2b1585..276ed799 100644
--- a/semantica/export/rdf_exporter.py
+++ b/semantica/export/rdf_exporter.py
@@ -105,7 +105,11 @@ def normalize_confidence(value: Any) -> Optional[str]:
# "1e100000000" is eleven characters that expand to a hundred million, and
# the export path continues past validation errors, so a single malformed
# field could exhaust memory. Nothing near this magnitude is a confidence.
- if not -MAX_CONFIDENCE_EXPONENT <= decimal_value.adjusted() <= MAX_CONFIDENCE_EXPONENT:
+ if (
+ not -MAX_CONFIDENCE_EXPONENT
+ <= decimal_value.adjusted()
+ <= MAX_CONFIDENCE_EXPONENT
+ ):
return None
# `str(Decimal("0.00001"))` gives "0.00001", but a float that has already
@@ -411,13 +415,12 @@ class RDFSerializer:
prefix, separator, local_name = value.partition(":")
namespace = (namespaces or self.namespace_manager.namespaces).get(prefix)
if namespace and separator:
- return quote(namespace + local_name, safe=":/?#[]@!$&'()*+,;=%")
- remainder = value[len(prefix) + 1 :]
- if len(prefix) >= 2 and (
- remainder.startswith(("//", "/"))
- or any(token in remainder for token in (":", "/", "@"))
- ):
- return quote(value, safe=":/?#[]@!$&'()*+,;=%")
+ return quote(namespace + local_name, safe=":/?#[]@!$&'()*+,;=")
+ # A scheme with at least two characters is an absolute IRI,
+ # including opaque forms such as mailto:foo and isbn:0451450523.
+ # Keep one-character schemes as the existing Windows drive-path case.
+ if len(prefix) >= 2:
+ return quote(value, safe=":/?#[]@!$&'()*+,;=")
return self._SEMANTICA_NS + quote(value, safe="")
# Design decision — TemporalBound.OPEN in RDF:
@@ -522,7 +525,9 @@ class RDFSerializer:
)
if include_temporal:
- owl_lines = self._owl_time_triples_for_rel(rel, idx, time_axis)
+ owl_lines = self._owl_time_triples_for_rel(
+ rel, idx, time_axis, merged_namespaces
+ )
if owl_lines:
# The interval hangs off the relationship's own IRI, and a
# relationship written as a single triple has no such node
@@ -532,7 +537,7 @@ class RDFSerializer:
# export, and every term is declared in the vocabulary.
lines.extend(
self._reified_relationship_triples(
- rel, idx, source_id, target_id, rel_type
+ rel, idx, source_id, target_id, rel_type, merged_namespaces
)
)
lines.extend(owl_lines)
@@ -546,6 +551,7 @@ class RDFSerializer:
source_id: str,
target_id: str,
rel_type: str,
+ namespaces: Optional[Dict[str, str]] = None,
) -> List[str]:
"""
Emit the reified relationship node that OWL-Time triples hang off.
@@ -554,7 +560,11 @@ class RDFSerializer:
to, using the same sem:Relationship shape the JSON-LD export already
writes, so the two serializations describe relationships the same way.
"""
- rel_id = rel.get("id") or mint_relationship_iri(idx, source_id or "", target_id or "")
+ rel_id = self._as_turtle_iri(
+ rel.get("id")
+ or mint_relationship_iri(idx, source_id or "", target_id or ""),
+ namespaces,
+ )
# The full predicate, not its local name. Truncating to the fragment
# made https://a.example/ns#employs and https://b.example/ns#employs the
@@ -568,17 +578,25 @@ class RDFSerializer:
.replace("\r", "\\r")
)
- predicates = [f"a semantica:Relationship"]
+ predicates = ["a semantica:Relationship"]
if source_id:
- predicates.append(f"semantica:source <{source_id}>")
+ predicates.append(
+ f"semantica:source <{self._as_turtle_iri(source_id, namespaces)}>"
+ )
if target_id:
- predicates.append(f"semantica:target <{target_id}>")
+ predicates.append(
+ f"semantica:target <{self._as_turtle_iri(target_id, namespaces)}>"
+ )
predicates.append(f'semantica:type "{escaped}"')
return ["", f"<{rel_id}> " + " ;\n ".join(predicates) + " ."]
def _owl_time_triples_for_rel(
- self, rel: Dict[str, Any], idx: int, time_axis: str
+ self,
+ rel: Dict[str, Any],
+ idx: int,
+ time_axis: str,
+ namespaces: Optional[Dict[str, str]] = None,
) -> List[str]:
"""
Emit OWL-Time Turtle triples for a relationship that carries temporal metadata.
@@ -593,7 +611,7 @@ class RDFSerializer:
def _is_open(v: Any) -> bool:
if v is None:
return False
- if hasattr(v, "value"): # TemporalBound enum
+ if hasattr(v, "value"): # TemporalBound enum
return v.value == _OPEN_SENTINEL
return str(v).strip().upper() == _OPEN_SENTINEL
@@ -610,7 +628,10 @@ class RDFSerializer:
# deterministic IRI.
source_id = rel.get("source_id") or rel.get("source") or ""
target_id = rel.get("target_id") or rel.get("target") or ""
- rel_base_id = rel.get("id") or mint_relationship_iri(idx, source_id, target_id)
+ rel_base_id = self._as_turtle_iri(
+ rel.get("id") or mint_relationship_iri(idx, source_id, target_id),
+ namespaces,
+ )
lines = [""] # blank separator
for axis_name, from_val, until_val in axes:
@@ -625,9 +646,7 @@ class RDFSerializer:
lines.append(f" time:hasBeginning <{begin_id}> ;")
if _is_open(until_val):
- lines.append(
- ' semantica:openEndedInterval "true"^^xsd:boolean .'
- )
+ lines.append(' semantica:openEndedInterval "true"^^xsd:boolean .')
elif until_val is not None:
end_id = f"{rel_base_id}__{axis_name}_end"
lines.append(f" time:hasEnd <{end_id}> .")
@@ -636,7 +655,9 @@ class RDFSerializer:
f' time:inXSDDateTimeStamp "{until_val}"^^xsd:dateTimeStamp .'
)
else:
- lines[-1] = lines[-1].rstrip(" ;") + " ." # close interval without hasEnd
+ lines[-1] = (
+ lines[-1].rstrip(" ;") + " ."
+ ) # close interval without hasEnd
lines.append(f"<{begin_id}> a time:Instant ;")
lines.append(
diff --git a/tests/export/test_rdf_exporter_turtle_iris.py b/tests/export/test_rdf_exporter_turtle_iris.py
index 6faa3d72..9d6e4ab1 100644
--- a/tests/export/test_rdf_exporter_turtle_iris.py
+++ b/tests/export/test_rdf_exporter_turtle_iris.py
@@ -10,27 +10,41 @@ def test_turtle_normalizes_graph_builder_default_identifiers():
"""Default GraphBuilder labels with spaces become stable absolute IRIs."""
source = {
"entities": [
- {"id": "Acme Corp", "name": "Acme Corp", "type": "ORG"},
+ {
+ "id": "Kochi, Kerala",
+ "name": "Kochi, Kerala",
+ "type": "LOCATION",
+ },
{"id": "Jane Doe", "name": "Jane Doe", "type": "PERSON"},
],
"relationships": [
- {"source": "Jane Doe", "target": "Acme Corp", "type": "works_for"},
+ {
+ "source": "Jane Doe",
+ "target": "Kochi, Kerala",
+ "type": "located_in",
+ },
],
}
graph_data = GraphBuilder(resolve_conflicts=False).build(sources=[source])
turtle = RDFExporter().export_to_rdf(graph_data, format="turtle")
parsed = Graph().parse(data=turtle, format="turtle")
+ assert "<Jane Doe>" not in turtle
+ assert "<Kochi, Kerala>" not in turtle
- acme = URIRef("https://semantica.dev/ns#Acme%20Corp")
+ kochi = URIRef("https://semantica.dev/ns#Kochi%2C%20Kerala")
jane = URIRef("https://semantica.dev/ns#Jane%20Doe")
- assert (acme, RDF.type, URIRef("https://semantica.dev/ns#ORG")) in parsed
+ assert (
+ kochi,
+ RDF.type,
+ URIRef("https://semantica.dev/ns#LOCATION"),
+ ) in parsed
jane_type = URIRef("https://semantica.dev/ns#PERSON")
assert (jane, RDF.type, jane_type) in parsed
assert (
jane,
- URIRef("https://semantica.dev/ns#works_for"),
- acme,
+ URIRef("https://semantica.dev/ns#located_in"),
+ kochi,
) in parsed
@@ -58,12 +72,69 @@ def test_turtle_preserves_absolute_iris():
) in parsed
-def test_turtle_expands_context_prefixes_and_normalizes_malformed_iris():
- """Prefixes expand and malformed URI-like values are minted."""
+def test_turtle_preserves_opaque_absolute_iris_and_encodes_bad_percent_escapes():
+ """Opaque schemes remain absolute and malformed percent escapes are encoded."""
+ turtle = RDFExporter().export_to_rdf(
+ {
+ "entities": [
+ {"id": "mailto:foo", "type": "isbn:0451450523"},
+ {"id": "http://example.org/bad%zz", "type": "PERSON"},
+ ],
+ "relationships": [],
+ },
+ format="turtle",
+ )
+ parsed = Graph().parse(data=turtle, format="turtle")
+
+ assert (
+ URIRef("mailto:foo"),
+ RDF.type,
+ URIRef("isbn:0451450523"),
+ ) in parsed
+ assert URIRef("http://example.org/bad%25zz") in parsed.all_nodes()
+
+
+def test_turtle_normalizes_temporal_relationship_endpoints():
+ """Temporal relationship metadata uses the same normalized resource IRIs."""
+ turtle = RDFExporter().export_to_rdf(
+ {
+ "entities": [
+ {"id": "Jane Doe", "type": "PERSON"},
+ {"id": "Kochi, Kerala", "type": "LOCATION"},
+ ],
+ "relationships": [
+ {
+ "source": "Jane Doe",
+ "target": "Kochi, Kerala",
+ "type": "located_in",
+ "valid_from": "2024-01-01T00:00:00+00:00",
+ "valid_until": "2024-02-01T00:00:00+00:00",
+ }
+ ],
+ },
+ format="turtle",
+ include_temporal=True,
+ )
+ parsed = Graph().parse(data=turtle, format="turtle")
+
+ assert (
+ None,
+ URIRef("https://semantica.dev/ns#source"),
+ URIRef("https://semantica.dev/ns#Jane%20Doe"),
+ ) in parsed
+ assert (
+ None,
+ URIRef("https://semantica.dev/ns#target"),
+ URIRef("https://semantica.dev/ns#Kochi%2C%20Kerala"),
+ ) in parsed
+
+
+def test_turtle_expands_context_prefixes_and_mints_relative_values():
+ """Context prefixes expand while bare values use the fallback namespace."""
turtle = RDFExporter().export_to_rdf(
{
"@context": {"ex": "https://example.org/"},
- "entities": [{"id": "http://[invalid", "type": "ex:Person"}],
+ "entities": [{"id": "ORG", "type": "ex:Person"}],
"relationships": [],
},
format="turtle",
@@ -71,7 +142,7 @@ def test_turtle_expands_context_prefixes_and_normalizes_malformed_iris():
parsed = Graph().parse(data=turtle, format="turtle")
assert (
- URIRef("https://semantica.dev/ns#http%3A%2F%2F%5Binvalid"),
+ URIRef("https://semantica.dev/ns#ORG"),
RDF.type,
URIRef("https://example.org/Person"),
) in parsed