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(ontology): address review follow-ups on live SHACL validation (#804)
KaifAhmad128fe304f7677
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1a7464b7..bce24536 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **`POST /shacl/validate` and the `/health` SHACL dimension never ran live SHACL validation** (#772, #804) by @Sameer6305 and @KaifAhmad1+ - `/shacl/validate` had no data graph to validate submitted shapes against — only a Turtle syntax check. Added `_data_graph_turtle_for_uri()`, which serializes the loaded ontology's nodes/edges into an RDF/Turtle instance graph (CURIE resolution across owl/rdfs/skos/dct/dc, arbitrary node-property projection, typed individuals) and wires both `/shacl/validate` and the `/health` SHACL dimension to `OntologyEngine.validate_graph()` via pySHACL, returning real `conforms`/violations instead of a hardcoded `status="unavailable"` stub+ - Fixed a cross-ontology namespace leak in `_node_belongs_to_ontology`: its prefix fallback (`_extract_namespace()`) split only on the last `/`, so sibling ontologies sharing a domain (e.g. `.../onto-a` and `.../onto-b`) could match entities across ontologies that shouldn't be related; fixed by comparing against the full URI stem via the new `_ontology_namespace()` helper+ - Added resource guardrails to `/shacl/validate` to close a DoS risk flagged in review: a submitted-Turtle byte cap (`SEMANTICA_MAX_SHACL_TURTLE_BYTES`, default 256 KB), a parsed-triple cap (`SEMANTICA_MAX_SHACL_TRIPLES`, default 1,000), a validation timeout (`SEMANTICA_MAX_SHACL_TIMEOUT`, default 15s), and a global concurrency semaphore (`SEMANTICA_MAX_SHACL_CONCURRENCY`, default 4)+ - Fixed `HealthDimension.status` being set to `"error"` on a real (non-`ImportError`) validation exception, which isn't a valid value on that model — Pydantic construction raised and turned the whole `/health` endpoint into a 422 on any real bug; now reports `status="critical"` (already a valid value) with a regression test forcing this exact path+ - Follow-up review fixes: reverted an unrelated regression that had crept into this PR — `POST /api/ontology/create` had gone back to silently swallowing `OntologyEngine.from_data`/`from_text` failures into a near-empty "minimal" ontology instead of raising `HTTPException(500)`, undoing the earlier #770/#787 fix for the same endpoint (and breaking `TestOntologyCreateFailures`, which wasn't run before this PR's initial merge request); `sh:Warning`/`sh:Info`-severity pySHACL results were silently dropped from the `/shacl/validate` response — a shape using non-`Violation` severities could report `conforms=False` with an empty `violations` list and no explanation, so warnings/infos are now folded into the response's `violations` array; and `/health` was independently re-fetching and re-truncation-checking the same ontology's nodes/edges once for the generated SHACL shapes and once for the data graph — both now share a single fetch via `_fetch_analysis_graph()`+ - New regression tests: `TestOntologyCreateFailures` (pre-existing, now passing again), `test_shacl_validate_surfaces_warning_severity_results`, `test_health_dedupes_node_edge_fetch`, plus the existing 26-test `tests/explorer/test_ontology_subissue3.py` suite (28/28 passing) and the pre-existing `tests/ontology/` suite (83/83 passing)+- **`react-hooks/set-state-in-effect` cascading renders across 12 Explorer workspace files** (#769, #796) by @Sameer6305 and @KaifAhmad1- Replaced synchronous `setState` calls inside `useEffect` bodies with React's recommended "adjust state during render" pattern (`if (x !== prevX) { setPrevX(x); ...setState... }`) across `OntologyWorkspace`, `ManageWorkspace`, `LineageWorkspace`, and `GraphWorkspace`, and inlined async data-fetching effects with `ignore` flags to prevent race conditions and stale writes after unmount- Fixed a regression the inlining itself introduced: `AlignmentsTab.tsx`, `KGOverviewTab.tsx`, `OntologyManager.tsx`, and `VersionsTab.tsx` each duplicated their existing fetch callback (`reload` / `fetchOverview` / `fetchRegistry` / `loadVersions`+`loadProposals`) into a second, inline copy for the mount effect, and the copy silently dropped the `setError`/`flashMsg` calls the original had — re-introducing, on the very first page load, the exact error-swallowing behavior that #767/#790 had already fixed for these same files. The inline copies now mirror the original's error handling (including `207` partial-success messages) exactlydiff --git a/semantica/explorer/routes/ontology.py b/semantica/explorer/routes/ontology.pyindex d069852c..31c21afa 100644--- a/semantica/explorer/routes/ontology.py+++ b/semantica/explorer/routes/ontology.py@@ -1472,8 +1472,8 @@ async def create_ontology(logger.info(f"Generated ontology from sample data with {len(nodes)} nodes, {len(edges)} edges")except Exception as exc:- logger.exception("Failed to generate ontology from sample data; falling back to minimal ontology.")- logger.warning(f"OntologyEngine.from_data error: {exc}")+ logger.exception("Failed to generate ontology from sample data; aborting ontology creation.")+ raise HTTPException(status_code=500, detail=f"Ontology generation failed: {exc}") from excelif body.mode == "text" and body.schema_text:try:@@ -1542,8 +1542,8 @@ async def create_ontology(logger.info(f"Generated ontology from text with {len(nodes)} nodes, {len(edges)} edges")except Exception as exc:- logger.exception("Failed to generate ontology from schema text; falling back to minimal ontology.")- logger.warning(f"OntologyEngine.from_text error: {exc}")+ logger.exception("Failed to generate ontology from schema text; aborting ontology creation.")+ raise HTTPException(status_code=500, detail=f"Ontology generation failed: {exc}") from excnodes_added = await asyncio.to_thread(session.add_nodes, nodes)edges_added = await asyncio.to_thread(session.add_edges, edges)@@ -2166,8 +2166,13 @@ async def ontology_health(documentation_score = ((with_comment / total) * 80.0) + (20.0 if entry.version or entry.source_url else 0.0)try:- shacl_turtle, _ = await _generated_shacl_for_uri(request, session, uri)- data_graph_turtle = await _data_graph_turtle_for_uri(request, session, uri)+ health_nodes, health_edges = await _fetch_analysis_graph(session, uri, "shacl-health")+ shacl_turtle, _ = await _generated_shacl_for_uri(+ request, session, uri, nodes=health_nodes, edges=health_edges+ )+ data_graph_turtle = await _data_graph_turtle_for_uri(+ request, session, uri, nodes=health_nodes, edges=health_edges+ )from ...ontology import OntologyEngineengine = OntologyEngine()report = await asyncio.to_thread(@@ -2177,12 +2182,23 @@ async def ontology_health(data_graph_format="turtle",shacl_format="turtle",)- shacl_score = 100.0 if report.conforms else max(0.0, 100.0 - (report.violation_count * 20.0))- shacl_status = "ok" if report.conforms else "warning"+ warning_count = len(report.warnings)+ if not report.conforms:+ shacl_score = max(0.0, 100.0 - (report.violation_count * 20.0))+ elif warning_count:+ shacl_score = max(0.0, 100.0 - (warning_count * 5.0))+ else:+ shacl_score = 100.0+ shacl_status = "ok" if report.conforms and not warning_count else "warning"+ detail_parts = []+ if not report.conforms:+ detail_parts.append(f"{report.violation_count} SHACL violation(s)")+ if warning_count:+ detail_parts.append(f"{warning_count} SHACL warning(s)")shacl_detail = ("Graph conforms to all generated SHACL constraints."- if report.conforms- else f"Graph has {report.violation_count} SHACL violation(s)."+ if not detail_parts+ else f"Graph has {', '.join(detail_parts)}.")shacl_dimension = HealthDimension(key="shacl",@@ -2260,28 +2276,46 @@ async def ontology_health()-async def _generated_shacl_for_uri(- request: Request,+async def _fetch_analysis_graph(session: GraphSession,uri: str,- quality_tier: str = "strict",-) -> tuple[str, List[ShaclShapeSummary]]:- registry = {entry.uri: entry for entry in await _registry_entries(request, session)}- entry = registry.get(uri)- if entry is None:- raise HTTPException(status_code=404, detail="Ontology not found in registry.")+ log_tag: str,+) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:+ """Fetch nodes/edges for SHACL analysis, raising GraphTruncationError if oversized.+ Shared by `_generated_shacl_for_uri` and `_data_graph_turtle_for_uri` so callers that+ need both (e.g. `/health`) can fetch once and pass the results to both via `nodes=`/`edges=`.+ """nodes, total_nodes = await asyncio.to_thread(session.get_nodes, skip=0, limit=_MAX_ANALYSIS_NODES)edges, total_edges = await asyncio.to_thread(session.get_edges, skip=0, limit=_MAX_ANALYSIS_NODES)if total_nodes > _MAX_ANALYSIS_NODES or total_edges > _MAX_ANALYSIS_NODES:logger.warning(- "shacl-generate: graph for %s is too large to analyse (nodes=%d, edges=%d, limit=%d); skipping.",- uri, total_nodes, total_edges, _MAX_ANALYSIS_NODES,+ "%s: graph for %s is too large to analyse (nodes=%d, edges=%d, limit=%d); skipping.",+ log_tag, uri, total_nodes, total_edges, _MAX_ANALYSIS_NODES,)raise GraphTruncationError(f"Graph size (nodes={total_nodes}, edges={total_edges}) exceeds maximum analysis limit ({_MAX_ANALYSIS_NODES}). ""SHACL validation is skipped because the graph is too large to validate fully under current limits.")+ return nodes, edges+++async def _generated_shacl_for_uri(+ request: Request,+ session: GraphSession,+ uri: str,+ quality_tier: str = "strict",+ *,+ nodes: Optional[List[Dict[str, Any]]] = None,+ edges: Optional[List[Dict[str, Any]]] = None,+) -> tuple[str, List[ShaclShapeSummary]]:+ registry = {entry.uri: entry for entry in await _registry_entries(request, session)}+ entry = registry.get(uri)+ if entry is None:+ raise HTTPException(status_code=404, detail="Ontology not found in registry.")++ if nodes is None or edges is None:+ nodes, edges = await _fetch_analysis_graph(session, uri, "shacl-generate")entities = _ontology_entities(nodes, uri)ontology_dict = _ontology_dict_from_nodes(uri, entry.name, entities, edges)@@ -2306,6 +2340,9 @@ async def _data_graph_turtle_for_uri(request: Request,session: GraphSession,uri: str,+ *,+ nodes: Optional[List[Dict[str, Any]]] = None,+ edges: Optional[List[Dict[str, Any]]] = None,) -> str:try:import rdflib@@ -2316,17 +2353,8 @@ async def _data_graph_turtle_for_uri(if uri not in registry:raise HTTPException(status_code=404, detail="Ontology not found in registry.")- nodes, total_nodes = await asyncio.to_thread(session.get_nodes, skip=0, limit=_MAX_ANALYSIS_NODES)- edges, total_edges = await asyncio.to_thread(session.get_edges, skip=0, limit=_MAX_ANALYSIS_NODES)- if total_nodes > _MAX_ANALYSIS_NODES or total_edges > _MAX_ANALYSIS_NODES:- logger.warning(- "shacl-data-graph: graph for %s is too large to analyse (nodes=%d, edges=%d, limit=%d); skipping.",- uri, total_nodes, total_edges, _MAX_ANALYSIS_NODES,- )- raise GraphTruncationError(- f"Graph size (nodes={total_nodes}, edges={total_edges}) exceeds maximum analysis limit ({_MAX_ANALYSIS_NODES}). "- "SHACL validation is skipped because the graph is too large to validate fully under current limits."- )+ if nodes is None or edges is None:+ nodes, edges = await _fetch_analysis_graph(session, uri, "shacl-data-graph")entities = _data_graph_entities(nodes, uri)g = rdflib.Graph()@@ -2653,12 +2681,19 @@ async def validate_shacl(focus_node=str(v.focus_node) if v.focus_node is not None else None,source_shape=str(v.shape) if v.shape is not None else None,)- for v in report.violations+ for v in [*report.violations, *report.warnings, *report.infos]]+ _result_counts = []+ if report.violations:+ _result_counts.append(f"{len(report.violations)} violation(s)")+ if report.warnings:+ _result_counts.append(f"{len(report.warnings)} warning(s)")+ if report.infos:+ _result_counts.append(f"{len(report.infos)} info result(s)")summary_msg = (- "Graph conforms to SHACL shapes."- if report.conforms- else f"SHACL validation found {len(violations)} violation(s)."+ f"SHACL validation found {', '.join(_result_counts)}."+ if _result_counts+ else "Graph conforms to SHACL shapes.")return ShaclValidationResponse(uri=body.uri,diff --git a/tests/explorer/test_ontology_subissue3.py b/tests/explorer/test_ontology_subissue3.pyindex bc0d240d..2d6f7d9d 100644--- a/tests/explorer/test_ontology_subissue3.py+++ b/tests/explorer/test_ontology_subissue3.py@@ -228,6 +228,73 @@ onto:PersonNameShape a sh:NodeShape ;assert "person-no-name" in str(violation["focus_node"]) or "person-no-name" in str(violation["node"])+def test_shacl_validate_surfaces_warning_severity_results(client):+ graph = client.app.state.session.graph+ onto_uri = "http://example.org/onto-a"+ person_a = "http://example.org/onto-a#Person"+ person_inst = "http://example.org/onto-a#person-no-email"+ graph.add_node(+ person_inst,+ node_type="owl:NamedIndividual",+ content="Person Without Email",+ scheme_uri=onto_uri,+ **{+ "rdf:type": person_a,+ "rdfs:label": "Person Without Email",+ },+ )++ shacl_turtle = """+@prefix sh: <http://www.w3.org/ns/shacl#> .+@prefix onto: <http://example.org/onto-a#> .++onto:PersonEmailShape a sh:NodeShape ;+ sh:targetClass onto:Person ;+ sh:property [+ sh:path onto:email ;+ sh:minCount 1 ;+ sh:severity sh:Warning ;+ sh:message "Person should have an email." ;+ ] .+"""++ response = client.post(+ "/api/ontology/shacl/validate",+ json={+ "uri": onto_uri,+ "shacl_turtle": shacl_turtle,+ },+ )+ assert response.status_code == 200+ payload = response.json()+ assert payload["status"] == "success"+ # pySHACL flips conforms=False for any result regardless of severity, but+ # previously the response body gave no explanation for that: violations+ # was always populated from report.violations only, so a report that was+ # "non-conforming" purely due to a Warning-severity result rendered as+ # conforms=False with an empty violations list. Warnings/infos are now+ # folded into the violations array so the response is self-explanatory.+ assert payload["conforms"] is False+ assert len(payload["violations"]) >= 1+ warning = payload["violations"][0]+ assert warning["severity"] == "Warning"+ assert "warning" in payload["message"].lower()+++def test_health_dedupes_node_edge_fetch(client):+ import semantica.explorer.routes.ontology as ont_mod++ with patch.object(+ ont_mod, "_fetch_analysis_graph", wraps=ont_mod._fetch_analysis_graph+ ) as fetch_spy:+ response = client.get("/api/ontology/health?uri=http%3A%2F%2Fexample.org%2Fonto-a")+ assert response.status_code == 200+ # /health needs both the generated SHACL shapes and the data graph for the+ # same uri; both used to independently re-fetch nodes/edges from the+ # session. They now share a single fetch.+ assert fetch_spy.call_count == 1++def test_health_returns_404_for_unknown_ontology(client):response = client.get("/api/ontology/health?uri=http%3A%2F%2Fnot-loaded.example%2Fonto")assert response.status_code == 404