Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
fix(python): preserve RDF literal identity in KGCL comparisons
Rudy Celeklib9274a11e0ce
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6646495d..bc25f389 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,8 @@ All notable changes to Open Ontologies are documented here.### Fixed+- Preserve RDF literal datatypes when comparing Python KGCL graph changes, while retaining lexical label and annotation values.+- Keep the last active ontology intact when parsing a replacement source, cache, or refresh fails; publish successful replacements in one graph transaction.- Bound wildcard repository filtering to pattern/filename pairs so repeated stars cannot stall `onto_repo_list`.- Sanitize quotes and ASCII control bytes in mapped IRI components so valid structured data does not fail RDF ingestion.diff --git a/python/src/open_ontologies_lite/kgcl.py b/python/src/open_ontologies_lite/kgcl.pyindex 611148eb..754596f8 100644--- a/python/src/open_ontologies_lite/kgcl.py+++ b/python/src/open_ontologies_lite/kgcl.py@@ -36,8 +36,8 @@ def _term(t) -> str:return t.valueif isinstance(t, ox.BlankNode):return f"_:{t.value}"- # Literal- return f'"{t.value}"' + (f"@{t.language}" if getattr(t, "language", None) else "")+ # Preserve a literal's datatype, language and escaped lexical form.+ return str(t)def _parse(data: str, fmt: str):@@ -48,7 +48,8 @@ def _parse(data: str, fmt: str):tr = getattr(q, "triple", q)s, p, o = _term(tr.subject), _term(tr.predicate), _term(tr.object)triples.add((s, p, o))- by_subj.setdefault(s, set()).add((p, o))+ # Compare RDF terms directly; labels still need their lexical value.+ by_subj.setdefault(s, set()).add((p, tr.object))return triples, by_subj@@ -97,8 +98,8 @@ class ChangeSet:def _label_of(triples: set, predicates: set) -> str | None:for p, o in triples:- if p in predicates and o.startswith('"'):- return o[1:].split('"')[0]+ if p in predicates and isinstance(o, ox.Literal):+ return o.valuereturn None@@ -123,12 +124,12 @@ def kgcl_diff(old: str, new: str, fmt: str = "turtle") -> ChangeSet:if s not in old_s and s in new_s:cs.changes.append({"type": "node_creation", "node": s,"label": _label_of(n_tr, LABEL_PREDICATES)})- accounted |= {(s, p, o) for p, o in n_tr}+ accounted |= {(s, p, _term(o)) for p, o in n_tr}continueif s in old_s and s not in new_s:cs.changes.append({"type": "node_deletion", "node": s,"label": _label_of(o_tr, LABEL_PREDICATES)})- accounted |= {(s, p, o) for p, o in o_tr}+ accounted |= {(s, p, _term(o)) for p, o in o_tr}continue# Subject in both: look for label / annotation changes per predicate.@@ -140,12 +141,12 @@ def kgcl_diff(old: str, new: str, fmt: str = "turtle") -> ChangeSet:if ov != nv and ov and nv:old_v = next(iter(ov)); new_v = next(iter(nv))rec = {"type": ctype, "node": s,- "old": old_v.strip('"').split('"@')[0],- "new": new_v.strip('"').split('"@')[0]}+ "old": old_v.value if isinstance(old_v, ox.Literal) else _term(old_v),+ "new": new_v.value if isinstance(new_v, ox.Literal) else _term(new_v)}if ctype == "node_annotation_change":rec["predicate"] = pcs.changes.append(rec)- accounted |= {(s, p, old_v), (s, p, new_v)}+ accounted |= {(s, p, _term(old_v)), (s, p, _term(new_v))}# Remaining raw triple differences become edge creations / deletions.for (s, p, o) in sorted(new_t - old_t):diff --git a/python/tests/test_kgcl_literal_datatype.py b/python/tests/test_kgcl_literal_datatype.pynew file mode 100644index 00000000..fd0a6041--- /dev/null+++ b/python/tests/test_kgcl_literal_datatype.py@@ -0,0 +1,83 @@+"""Public consumer regression for RDF literal datatype identity."""+import json++import pytest+from open_ontologies_lite import kgcl_diff++PREFIX = '@prefix ex: <http://example.org/> . @prefix xsd: <http://www.w3.org/2001/XMLSchema#> . '+[email protected]("old_object,new_object", [+ ('"7"', '"7"^^xsd:integer'),+ ('"7"^^xsd:integer', '"7"^^xsd:decimal'),+ ('"7"^^xsd:integer', '"7"^^xsd:double'),+], ids=["string-to-integer", "integer-to-decimal", "integer-to-double"])+def test_kgcl_diff_detects_literal_datatype_change(old_object, new_object):+ old = PREFIX + f'ex:Thing ex:value {old_object} .'+ new = PREFIX + f'ex:Thing ex:value {new_object} .'+ result = kgcl_diff(old, new)+ assert result.counts() == {"edge_creation": 1, "edge_deletion": 1}+ assert {change["subject"] for change in result.changes} == {"http://example.org/Thing"}+ expected = {}+ for kind, value in [("edge_deletion", old_object), ("edge_creation", new_object)]:+ if "^^xsd:" in value:+ lexical, datatype = value.split("^^xsd:")+ value = lexical + "^^<http://www.w3.org/2001/XMLSchema#" + datatype + ">"+ expected[kind] = value+ assert {change["type"]: change["object"] for change in result.changes} == expected+ assert kgcl_diff(old, old).changes == []+ assert kgcl_diff(new, new).changes == []+[email protected]("object_text", ['"7"', '"7"^^xsd:integer', '"7"^^xsd:decimal', '"7"^^xsd:double', '"seven"@en'], ids=["string", "integer", "decimal", "double", "language"])+def test_kgcl_unchanged_literal_is_empty(object_text):+ document = PREFIX + f'ex:Thing ex:value {object_text} .'+ assert kgcl_diff(document, document).changes == []+[email protected]("label", ['"seven"', '"seven"@en', '"7"^^xsd:integer'], ids=["plain", "language", "typed"])+def test_created_node_label_retains_lexical_value(label):+ document = PREFIX + f'ex:Thing <http://www.w3.org/2000/01/rdf-schema#label> {label} .'+ result = kgcl_diff("", document)+ assert result.changes == [{"type": "node_creation", "node": "http://example.org/Thing", "label": "7" if "integer" in label else "seven"}]+++def test_rename_and_annotation_fields_remain_lexical():+ old = PREFIX + 'ex:Thing <http://www.w3.org/2000/01/rdf-schema#label> "old"@en ; <http://www.w3.org/2000/01/rdf-schema#comment> "before" .'+ new = PREFIX + 'ex:Thing <http://www.w3.org/2000/01/rdf-schema#label> "new"@en ; <http://www.w3.org/2000/01/rdf-schema#comment> "after" .'+ changes = {change["type"]: change for change in kgcl_diff(old, new).changes}+ assert changes["node_rename"]["old"] == "old"+ assert changes["node_rename"]["new"] == "new"+ assert changes["node_annotation_change"]["old"] == "before"+ assert changes["node_annotation_change"]["new"] == "after"+[email protected]("predicate,change_type", [+ ("label", "node_rename"), ("comment", "node_annotation_change"),+])[email protected]("kind", ["named", "blank"])+def test_nonliteral_label_and_annotation_changes_keep_term_spelling(predicate, change_type, kind):+ old_object, new_object = ("<http://example.org/old>", "<http://example.org/new>") if kind == "named" else ("_:old", "_:new")+ pred = "http://www.w3.org/2000/01/rdf-schema#" + predicate+ old = PREFIX + f'ex:Thing <{pred}> {old_object} .'+ new = PREFIX + f'ex:Thing <{pred}> {new_object} .'+ changes = kgcl_diff(old, new).changes+ assert len(changes) == 1 and changes[0]["type"] == change_type+ if kind == "named":+ assert changes[0]["old"] == "http://example.org/old"+ assert changes[0]["new"] == "http://example.org/new"+ else:+ assert changes[0]["old"].startswith("_:")+ assert changes[0]["new"].startswith("_:")++[email protected]("object_text", ["<http://example.org/label>", "_:label"], ids=["named", "blank"])+def test_created_node_nonliteral_labels_stay_absent(object_text):+ document = PREFIX + f'ex:Thing <http://www.w3.org/2000/01/rdf-schema#label> {object_text} .'+ assert kgcl_diff("", document).changes == [{"type": "node_creation", "node": "http://example.org/Thing", "label": None}]+++def test_escaped_label_lexical_value_is_not_parsed_from_display_text():+ before = 'say "old" and \\path'+ after = 'say "new" and \\path'+ pred = "http://www.w3.org/2000/01/rdf-schema#label"+ old = PREFIX + f'ex:Thing <{pred}> {json.dumps(before)} .'+ new = PREFIX + f'ex:Thing <{pred}> {json.dumps(after)} .'+ assert kgcl_diff("", old).changes[0]["label"] == before+ assert kgcl_diff(old, new).changes == [{"type": "node_rename", "node": "http://example.org/Thing", "old": before, "new": after}]