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
perf(explorer): bound the ontology graph fetch and hydrate external nodes concurrently (#1441)
Wei Taoc25b88c07e2c
diff --git a/semantica/explorer/routes/ontology.py b/semantica/explorer/routes/ontology.pyindex 7fa547af..66fb6efb 100644--- a/semantica/explorer/routes/ontology.py+++ b/semantica/explorer/routes/ontology.py@@ -35,6 +35,10 @@ router = APIRouter(prefix="/api/ontology", tags=["ontology"])_MAX_FETCH_BYTES = 20 * 1024 * 1024 # 20 MB_MAX_ANALYSIS_NODES = 5_000 # cap for health/suggest/shacl node scans to avoid OOM_MAX_ENTITIES_PER_SIDE = 500 # per-ontology cap for the O(n²) pairwise suggestion loop+_GRAPH_TOO_LARGE_DETAIL = (+ "Ontology editor graph exceeds the maximum size "+ f"({_MAX_ANALYSIS_NODES} nodes or edges)."+)class GraphTruncationError(Exception):@@ -72,6 +76,20 @@ _ONTOLOGY_TYPES = frozenset({}) | _SCHEME_TYPES_SEARCHABLE_TYPES = _CLASS_TYPES | _PROPERTY_TYPES | _INDIVIDUAL_TYPES | _CONCEPT_TYPES | _SCHEME_TYPES+_SCHEMA_NODE_TYPES = _CLASS_TYPES | _PROPERTY_TYPES | _CONCEPT_TYPES | _ONTOLOGY_TYPES+_STRUCTURE_EDGE_TYPES = frozenset({+ "rdf:type",+ "rdfs:subClassOf",+ "rdfs:domain",+ "rdfs:range",+ "owl:disjointWith",+ "owl:equivalentClass",+ "owl:equivalentProperty",+ "owl:inverseOf",+ "skos:broader",+ "skos:narrower",+ "skos:related",+})_URI_PREFIX_MAP = {"http://www.w3.org/2002/07/owl#": "owl:",@@ -1821,6 +1839,64 @@ async def search_entities(return results+def _known_ontology_uris(+ session: GraphSession, registry: Dict[str, OntologyEntry]+) -> set[str]:+ known = set(registry)+ for node_type in _ONTOLOGY_TYPES:+ for node in session.iter_nodes(node_type=node_type):+ node_id = str(node.get("id", ""))+ if node_id:+ known.add(node_id)+ return known+++def _collect_core_nodes(+ session: GraphSession, uri: str, known_ontology_uris: set[str]+) -> Dict[str, Dict[str, Any]]:+ """Stream schema nodes, keeping only the ones this ontology owns.++ Filtering as each node arrives makes _MAX_ANALYSIS_NODES bound the work and+ not merely the response: foreign nodes are discarded instead of materialized,+ and the scan stops once the owned ones pass the cap. The ownership filter has+ to stay ahead of that check — thousands of *other* ontologies' nodes must+ never make this one too large to open. Requesting pages instead would bound+ nothing: paginate_nodes normalizes the whole matching set on every call.+ """+ core_nodes_by_id: Dict[str, Dict[str, Any]] = {}+ for node_type in _SCHEMA_NODE_TYPES:+ for node in session.iter_nodes(node_type=node_type):+ node_id = str(node.get("id", ""))+ if not node_id or not _node_belongs_to_ontology(+ node, uri, known_ontology_uris+ ):+ continue+ core_nodes_by_id[node_id] = node+ if len(core_nodes_by_id) > _MAX_ANALYSIS_NODES:+ raise GraphTruncationError(_GRAPH_TOO_LARGE_DETAIL)+ return core_nodes_by_id+++def _select_structure_edges(+ session: GraphSession, core_node_ids: set[str]+) -> List[Dict[str, Any]]:+ """Stream structural edges, keeping only those leaving a core node.++ The requested ontology may reference outward (e.g. rdfs:range to an external+ vocabulary), but an unrelated ontology's property pointing at a core class+ must not leak inward.+ """+ selected_edges: List[Dict[str, Any]] = []+ for edge_type in _STRUCTURE_EDGE_TYPES:+ for edge in session.iter_edges(edge_type=edge_type):+ if str(edge.get("source", "")) not in core_node_ids:+ continue+ selected_edges.append(edge)+ if len(selected_edges) > _MAX_ANALYSIS_NODES:+ raise GraphTruncationError(_GRAPH_TOO_LARGE_DETAIL)+ return selected_edges++@router.get("/graph", response_model=OntologyGraphResponse)async def get_ontology_graph(request: Request,@@ -1828,88 +1904,39 @@ async def get_ontology_graph(session: GraphSession = Depends(get_session),):"""Return the editable schema subgraph for one registered ontology."""- registry = _get_registry(request)- ontology_nodes: List[Dict[str, Any]] = []- for node_type in _ONTOLOGY_TYPES:- nodes, _ = await asyncio.to_thread(- session.get_nodes, node_type=node_type, skip=0, limit=2**63 - 1- )- ontology_nodes.extend(nodes)- known_ontology_uris = set(registry) | {- str(node.get("id", "")) for node in ontology_nodes if node.get("id")- }+ known_ontology_uris = await asyncio.to_thread(+ _known_ontology_uris, session, _get_registry(request)+ )if uri not in known_ontology_uris:raise HTTPException(status_code=404, detail="Ontology not found in registry.")- schema_types = _CLASS_TYPES | _PROPERTY_TYPES | _CONCEPT_TYPES | _ONTOLOGY_TYPES- candidates_by_id: Dict[str, Dict[str, Any]] = {}- for node_type in schema_types:- nodes, _ = await asyncio.to_thread(- session.get_nodes, node_type=node_type, skip=0, limit=2**63 - 1- )- candidates_by_id.update(- (str(node.get("id", "")), node) for node in nodes if node.get("id")- )-- core_node_ids = {- str(node.get("id", ""))- for node in candidates_by_id.values()- if _node_belongs_to_ontology(node, uri, known_ontology_uris)- }- if not core_node_ids:- raise HTTPException(status_code=404, detail="Ontology graph not found.")-- structure_edge_types = {- "rdf:type",- "rdfs:subClassOf",- "rdfs:domain",- "rdfs:range",- "owl:disjointWith",- "owl:equivalentClass",- "owl:equivalentProperty",- "owl:inverseOf",- "skos:broader",- "skos:narrower",- "skos:related",- }- selected_edges: List[Dict[str, Any]] = []- for edge_type in structure_edge_types:- edges, _ = await asyncio.to_thread(- session.get_edges,- edge_type=edge_type,- skip=0,- limit=2**63 - 1,+ try:+ core_nodes_by_id = await asyncio.to_thread(+ _collect_core_nodes, session, uri, known_ontology_uris)- # Keep only edges whose source is a core node: the requested ontology- # may reference outward (e.g. rdfs:range to an external vocabulary),- # but an unrelated ontology's property pointing at a core class must- # not leak inward.- selected_edges.extend(- edge for edge in edges- if str(edge.get("source", "")) in core_node_ids- )- if (- len(core_node_ids) > _MAX_ANALYSIS_NODES- or len(selected_edges) > _MAX_ANALYSIS_NODES- ):- raise HTTPException(- status_code=413,- detail=(- "Ontology editor graph exceeds the maximum size "- f"({_MAX_ANALYSIS_NODES} nodes or edges)."- ),+ if not core_nodes_by_id:+ raise HTTPException(status_code=404, detail="Ontology graph not found.")+ core_node_ids = set(core_nodes_by_id)+ selected_edges = await asyncio.to_thread(+ _select_structure_edges, session, core_node_ids)+ except GraphTruncationError as exc:+ raise HTTPException(status_code=413, detail=str(exc)) from exc- selected_node_ids = set(core_node_ids)- for edge in selected_edges:- selected_node_ids.add(str(edge.get("source", "")))- selected_node_ids.add(str(edge.get("target", "")))+ # Invariant: the helpers raise the moment their accumulation passes+ # _MAX_ANALYSIS_NODES, so core_nodes_by_id and selected_edges are both+ # within the cap here; a post-filter re-check would be unreachable.+ external_node_ids = {+ node_id+ for edge in selected_edges+ for node_id in (str(edge.get("source", "")), str(edge.get("target", "")))+ } - core_node_ids+ external_nodes = await asyncio.gather(+ *(asyncio.to_thread(session.get_node, node_id) for node_id in external_node_ids)+ )- selected_nodes = [candidates_by_id[node_id] for node_id in core_node_ids]- for node_id in selected_node_ids - core_node_ids:- external = await asyncio.to_thread(session.get_node, node_id)- if external is not None:- selected_nodes.append(external)+ selected_nodes = list(core_nodes_by_id.values())+ selected_nodes.extend(node for node in external_nodes if node is not None)selected_nodes.sort(key=lambda node: str(node.get("id", "")))selected_edges.sort(key=lambda edge: (diff --git a/semantica/explorer/session.py b/semantica/explorer/session.pyindex abdc1711..1ed937fb 100644--- a/semantica/explorer/session.py+++ b/semantica/explorer/session.py@@ -9,7 +9,7 @@ import threadingimport timeimport uuidfrom datetime import UTC, datetime-from typing import Any, Dict, Iterable, List, Optional+from typing import Any, Dict, Iterable, Iterator, List, Optionalfrom ..context.context_graph import ContextGraph, _resolve_edge_identityfrom .search_index import GraphSearchIndex@@ -375,6 +375,52 @@ class GraphSession:)return page, total+ def iter_nodes(self, node_type: Optional[str] = None) -> Iterator[Dict[str, Any]]:+ """Yield matching nodes one at a time, in the same order as ``paginate_nodes``.++ ``paginate_nodes`` normalizes and holds the entire matching set before it+ slices out a page, so a caller that filters the result down itself cannot+ bound its cost by asking for smaller pages — it would re-pay that full+ cost per page. Streaming lets such a caller retain only what it selects+ and stop scanning as soon as it has enough.++ Only the id list is snapshotted under the lock; nodes are read one at a+ time, so a concurrent mutation can be observed mid-iteration and ids that+ disappear are skipped. ``paginate_nodes`` is the atomic alternative.+ """+ with self._lock:+ source_ids = (+ self.graph.node_type_index.get(node_type, set())+ if node_type+ else self.graph.nodes.keys()+ )+ node_ids = sorted(+ (node_id for node_id in source_ids if node_id is not None),+ key=lambda value: str(value),+ )+ for node_id in node_ids:+ with self._lock:+ raw = self.graph.find_node(node_id)+ if raw is None:+ continue+ yield self.normalize_node(raw)++ def iter_edges(self, edge_type: Optional[str] = None) -> Iterator[Dict[str, Any]]:+ """Yield matching edges one at a time, in raw graph order.++ Same rationale as ``iter_nodes``. Edge normalization derives an identity+ hash per edge, which ``paginate_edges`` pays for every matching edge (and+ then sorts) before paging; a filtering caller only needs it for the edges+ it keeps. Callers that need a stable order sort the subset they select.+ """+ with self._lock:+ raw_edges = self.graph.find_edges(edge_type=edge_type)+ for edge in raw_edges:+ normalized = self.normalize_edge(edge)+ if not normalized["source"] or not normalized["target"]:+ continue+ yield normalized+def get_raw_counts(self) -> tuple[int, int]:"""O(1) node/edge counts from the raw collections, with no per-itemnormalization.diff --git a/tests/explorer/test_ontology_subissue3.py b/tests/explorer/test_ontology_subissue3.pyindex 23192b96..6294c944 100644--- a/tests/explorer/test_ontology_subissue3.py+++ b/tests/explorer/test_ontology_subissue3.py@@ -13,6 +13,7 @@ pytest.importorskip("fastapi")from semantica.explorer.app import create_app # noqa: E402from semantica.explorer.routes.ontology import ( # noqa: E402+ _MAX_ANALYSIS_NODES,OntologyEntry,_convert_ontology_to_graph,_node_belongs_to_ontology,@@ -310,6 +311,66 @@ def test_ontology_graph_ignores_unrelated_data_when_enforcing_size_limit(client)}+def test_ontology_graph_rejects_oversized_core_and_stops_scanning(client, monkeypatch):+ graph = client.app.state.session.graph+ for index in range(5_001):+ graph.add_node(+ f"http://example.org/onto-a#Bulk{index:05d}",+ node_type="owl:Class",+ content="Bulk",+ scheme_uri="http://example.org/onto-a",+ )+ for index in range(3_000):+ graph.add_node(+ f"urn:unrelated:{index}",+ node_type="owl:Class",+ content="Unrelated",+ scheme_uri="http://example.org/onto-b",+ )++ streamed = 0+ original_iter_nodes = GraphSession.iter_nodes++ def counting_iter_nodes(self, node_type=None):+ nonlocal streamed+ for node in original_iter_nodes(self, node_type=node_type):+ streamed += 1+ yield node++ monkeypatch.setattr(GraphSession, "iter_nodes", counting_iter_nodes)++ response = client.get(+ "/api/ontology/graph",+ params={"uri": "http://example.org/onto-a"},+ )++ assert response.status_code == 413+ assert str(_MAX_ANALYSIS_NODES) in response.json()["detail"]+ # The graph holds 8,001 owl:Class nodes and onto-a's own sort first, so a+ # scan that abandons at the cap sees far fewer than the whole type.+ assert streamed < 6_000+++def test_ontology_graph_hydrates_external_edge_targets_in_sorted_order(client):+ graph = client.app.state.session.graph+ external = "http://external.example/Thing"+ also_external = "http://external.example/Aardvark"+ graph.add_node(external, node_type="owl:Class", content="External Thing")+ graph.add_node(also_external, node_type="owl:Class", content="External Aardvark")+ graph.add_edge("http://example.org/onto-a#name", external, edge_type="rdfs:range")+ graph.add_edge("http://example.org/onto-a#name", also_external, edge_type="rdfs:range")++ response = client.get(+ "/api/ontology/graph",+ params={"uri": "http://example.org/onto-a"},+ )++ assert response.status_code == 200+ node_ids = [node["id"] for node in response.json()["nodes"]]+ assert {external, also_external} <= set(node_ids)+ assert node_ids == sorted(node_ids)++def test_shacl_generate_and_shapes(client):response = client.post("/api/ontology/shacl/generate",