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
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# The open-world hole, live\n",
"\n",
"`SHACL` is the default RDF validator, and it is **open-world**: it validates the terms a shape targets and stays silent about everything else. So when a language model emits a *plausible-but-nonexistent* ontology term, SHACL reports `conforms = true` and the fabricated data flows on, looking exactly like clean data. A **closed-world vocabulary gate** catches it.\n",
"\n",
"**Press `Runtime -> Run all`** (or the play button on each cell). It installs two packages, then runs both validators on three preloaded hallucinated examples so you can see the contrast. The last cell is yours to edit.\n",
"\n",
"Full benchmark and reproducible code: https://github.com/fabio-rovai/open-ontologies/tree/main/case-studies/onto-correctness-bench\n"
]
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": [
"!pip -q install rdflib pyshacl requests\n"
]
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": [
"import json, requests\n",
"import rdflib\n",
"from rdflib import Graph, RDF, URIRef, Literal\n",
"from rdflib.namespace import SH\n",
"from pyshacl import validate\n",
"\n",
"RAW = \"https://raw.githubusercontent.com/fabio-rovai/open-ontologies/main/case-studies/onto-correctness-bench/space/vocab\"\n",
"VOCAB = {}\n",
"for key, label in [(\"schemaorg\",\"schema.org\"), (\"ies4\",\"IES4\"), (\"obo\",\"OBO (PATO+RO)\")]:\n",
" d = requests.get(f\"{RAW}/{key}.json\", timeout=60).json()\n",
" VOCAB[label] = {\"policed\": d[\"policed\"], \"declared\": set(d[\"declared\"])}\n",
"print(\"loaded vocabularies:\", \", \".join(f\"{k} ({len(v['declared'])} terms)\" for k,v in VOCAB.items()))\n",
"\n",
"def in_policed(iri, policed):\n",
" return any(str(iri).startswith(p) for p in policed)\n",
"\n",
"def closed_world_flags(g, policed, declared):\n",
" flagged = set()\n",
" for s,p,o in g:\n",
" if in_policed(p, policed) and str(p) not in declared: flagged.add(str(p))\n",
" if p == RDF.type and isinstance(o, URIRef) and in_policed(o, policed) and str(o) not in declared: flagged.add(str(o))\n",
" return sorted(flagged)\n",
"\n",
"def build_shapes(g, policed, declared):\n",
" shapes = Graph(); n = 0\n",
" for subj in set(g.subjects(RDF.type, None)):\n",
" for cls in g.objects(subj, RDF.type):\n",
" if not (isinstance(cls, URIRef) and in_policed(cls, policed) and str(cls) in declared): continue\n",
" shape = URIRef(f\"https://example.org/shape/{n}\"); n += 1\n",
" shapes.add((shape, RDF.type, SH.NodeShape)); shapes.add((shape, SH.targetClass, cls))\n",
" for p in set(g.predicates(subj, None)):\n",
" if in_policed(p, policed) and str(p) in declared:\n",
" b = URIRef(f\"https://example.org/shape/{n}/p\"); n += 1\n",
" shapes.add((shape, SH.property, b)); shapes.add((b, SH.path, p)); shapes.add((b, SH.minCount, Literal(1)))\n",
" return shapes\n",
"\n",
"def check(turtle, vocab_label):\n",
" v = VOCAB[vocab_label]\n",
" g = Graph().parse(data=turtle, format=\"turtle\")\n",
" shapes = build_shapes(g, v[\"policed\"], v[\"declared\"])\n",
" conforms, _, _ = validate(g, shacl_graph=shapes, inference=\"none\", abort_on_first=False)\n",
" flags = closed_world_flags(g, v[\"policed\"], v[\"declared\"])\n",
" print(f\"VOCABULARY: {vocab_label}\")\n",
" print(f\" SHACL (open-world): conforms = {str(conforms).lower()} <- {'admits the fabricated term(s)' if conforms else 'violation found'}\")\n",
" if flags:\n",
" print(f\" Closed-world gate: REJECTED, {len(flags)} undeclared term(s):\")\n",
" for f in flags: print(f\" - {f}\")\n",
" else:\n",
" print(\" Closed-world gate: PASSED, every term is declared\")\n",
" print()\n"
]
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": [
"SCHEMA_ORG = \"\"\"@prefix schema: <https://schema.org/> .\n",
"@prefix ex: <https://example.org/> .\n",
"# schema:MerchandiseOffer (class) and schema:priceBracket (predicate) do NOT exist.\n",
"ex:offer1 a schema:Offer , schema:MerchandiseOffer ;\n",
" schema:priceCurrency \"GBP\" ; schema:price \"49.00\" ; schema:priceBracket \"mid\" .\"\"\"\n",
"\n",
"IES4 = \"\"\"@prefix ies: <http://ies.data.gov.uk/ontology/ies4#> .\n",
"@prefix ex: <https://example.org/> .\n",
"# ies:hasParticipant does not exist; the real term is ies:isParticipantIn.\n",
"ex:event1 a ies:Event ; ies:isParticipationOf ex:person1 ; ies:hasParticipant ex:person1 .\"\"\"\n",
"\n",
"OBO = \"\"\"@prefix obo: <http://purl.obolibrary.org/obo/> .\n",
"@prefix ex: <https://example.org/> .\n",
"# obo:PATO_9999999 is a well-formed but undeclared PATO id.\n",
"ex:x1 a obo:PATO_0000462 ; obo:RO_0000052 ex:thing1 ; a obo:PATO_9999999 .\"\"\"\n",
"\n",
"check(SCHEMA_ORG, \"schema.org\")\n",
"check(IES4, \"IES4\")\n",
"check(OBO, \"OBO (PATO+RO)\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Your turn\n",
"\n",
"Edit the Turtle below and re-run this cell. Use `schema.org`, `IES4`, or `OBO (PATO+RO)` as the vocabulary.\n"
]
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": [
"MY_RDF = \"\"\"@prefix schema: <https://schema.org/> .\n",
"@prefix ex: <https://example.org/> .\n",
"ex:thing a schema:Product ;\n",
" schema:name \"Widget\" ;\n",
" schema:colour \"blue\" .\"\"\" # schema uses schema:color, not schema:colour -> watch the gate catch it\n",
"\n",
"check(MY_RDF, \"schema.org\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"Measured across three real vocabularies, open-world SHACL passed **300/300** graphs carrying a fabricated term; the closed-world gate caught **300/300** with **0** false positives. Read the write-up: https://gov.tesseract.academy/research/ontology-correctness-benchmark\n",
"\n",
"Built by Tesseract Academy.\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
},
"colab": {
"provenance": []
}
},
"nbformat": 4,
"nbformat_minor": 5
}