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(kg): consume detect_communities result fields in production callers (#1929)
Kevind47696a26ca2
diff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.pyindex bb6633af..b5381114 100644--- a/semantica/context/context_graph.py+++ b/semantica/context/context_graph.py@@ -4177,11 +4177,13 @@ class ContextGraph:# Community detectionif "community_detector" in self.kg_components:- communities = self.kg_components["community_detector"].detect_communities(kg_graph)+ community_detector = self.kg_components["community_detector"]+ community_result = community_detector.detect_communities(kg_graph)+ communities = community_result["communities"]analysis["community_analysis"] = {"communities": communities,"num_communities": len(communities),- "modularity": self._calculate_modularity(communities)+ "modularity": community_result.get("modularity", 0.0)}# Connectivity analysis@@ -4347,11 +4349,6 @@ class ContextGraph:distribution[edge.edge_type] += 1return dict(distribution)- def _calculate_modularity(self, communities: Dict) -> float:- """Calculate modularity for communities (simplified)."""- # Placeholder for modularity calculation- return 0.5-def _get_node_subgraph(self, node_id: str, max_depth: int = 2) -> Dict[str, Any]:"""Get subgraph around a node."""neighbors = self.get_neighbors(node_id, hops=max_depth)diff --git a/semantica/context/context_retriever.py b/semantica/context/context_retriever.pyindex 67d5c931..43120b35 100644--- a/semantica/context/context_retriever.py+++ b/semantica/context/context_retriever.py@@ -2456,18 +2456,20 @@ Answer:"""# Use community detection for contextually related entitiesif self.community_detector:try:- communities = self.community_detector.detect_communities(self.knowledge_graph)-+ community_result = self.community_detector.detect_communities(+ self.knowledge_graph+ )+ node_assignments = community_result.get("node_assignments", {})+# Find community of current entity- entity_community = None- for comm_id, comm_nodes in communities.items():- if entity_name in comm_nodes:- entity_community = comm_id- break-+ entity_community = node_assignments.get(entity_name)+# Add other entities from same communityif entity_community is not None:- same_community_entities = communities[entity_community]+ same_community_entities = [+ node for node, community_id in node_assignments.items()+ if community_id == entity_community+ ]for comm_entity in same_community_entities:if comm_entity != entity_name and comm_entity not in [e["name"] for e in expanded_entities]:expanded_entities.append({diff --git a/semantica/context/decision_query.py b/semantica/context/decision_query.pyindex 612d035e..e6bb6053 100644--- a/semantica/context/decision_query.py+++ b/semantica/context/decision_query.py@@ -1263,16 +1263,21 @@ class DecisionQuery:# Community detectionif "community_detector" in self.kg_components:subgraph = self._get_decision_subgraph(decision_id, max_depth)- communities = self.kg_components["community_detector"].detect_communities(subgraph)-- for community_id, members in communities.items():- if decision_id in members:- analysis["community_info"] = {- "community_id": community_id,- "community_size": len(members),- "community_members": list(members)[:10]- }- break+ community_detector = self.kg_components["community_detector"]+ community_result = community_detector.detect_communities(subgraph)+ node_assignments = community_result.get("node_assignments", {})++ community_id = node_assignments.get(decision_id)+ if community_id is not None:+ members = [+ node for node, assignment in node_assignments.items()+ if assignment == community_id+ ]+ analysis["community_info"] = {+ "community_id": community_id,+ "community_size": len(members),+ "community_members": members[:10]+ }self.logger.info(f"Completed influence analysis for decision {decision_id}")return analysisdiff --git a/semantica/kg/graph_analyzer.py b/semantica/kg/graph_analyzer.pyindex 7f32e5b8..aeb7a0f6 100644--- a/semantica/kg/graph_analyzer.py+++ b/semantica/kg/graph_analyzer.py@@ -127,14 +127,16 @@ class GraphAnalyzer:Returns:Dictionary containing:- centrality: Centrality measures for all nodes- - communities: Detected community structures+ - communities: Community detector result, a dict of+ ``communities``, ``node_assignments``, ``modularity`` and+ ``algorithm``- connectivity: Connectivity analysis results- metrics: Graph metrics and statisticsExample:>>> analysis = analyzer.analyze_graph(graph)>>> top_nodes = analysis["centrality"]["rankings"][:10]- >>> num_communities = len(analysis["communities"])+ >>> num_communities = len(analysis["communities"]["communities"])"""self.logger.info("Performing comprehensive graph analysis")diff --git a/semantica/vector_store/decision_embedding_pipeline.py b/semantica/vector_store/decision_embedding_pipeline.pyindex f8b32014..df907f70 100644--- a/semantica/vector_store/decision_embedding_pipeline.py+++ b/semantica/vector_store/decision_embedding_pipeline.py@@ -579,17 +579,14 @@ class DecisionEmbeddingPipeline:"""Get community assignments for entities."""try:# Detect communities in the graph- communities = self.community_detector.detect_communities(self.graph_store)-- entity_communities = {}- for entity in entities:- # Find which community the entity belongs to- for community_id, community_nodes in communities.items():- if entity in community_nodes:- entity_communities[entity] = community_id- break-- return entity_communities+ result = self.community_detector.detect_communities(self.graph_store)+ node_assignments = result.get("node_assignments", {})++ return {+ entity: node_assignments[entity]+ for entity in entities+ if entity in node_assignments+ }except Exception:return {}diff --git a/tests/context/test_end_to_end_context_integration.py b/tests/context/test_end_to_end_context_integration.pyindex f24fca4a..b516fad8 100644--- a/tests/context/test_end_to_end_context_integration.py+++ b/tests/context/test_end_to_end_context_integration.py@@ -217,8 +217,13 @@ class TestEndToEndContextIntegration:mock_community_detector = Mock()mock_community_detector.detect_communities.return_value = {- 0: ["entity1", "entity2", "entity3"],- 1: ["entity4", "entity5"]+ "communities": [["entity1", "entity2", "entity3"], ["entity4", "entity5"]],+ "node_assignments": {+ "entity1": 0, "entity2": 0, "entity3": 0,+ "entity4": 1, "entity5": 1,+ },+ "modularity": 0.5,+ "algorithm": "louvain",}mock_centrality_calculator = Mock()diff --git a/tests/test_issue_1822_detect_communities_callers.py b/tests/test_issue_1822_detect_communities_callers.pynew file mode 100644index 00000000..bfe920d1--- /dev/null+++ b/tests/test_issue_1822_detect_communities_callers.py@@ -0,0 +1,162 @@+"""Regression tests for the detect_communities result wrapper in callers (#1822).++`CommunityDetector.detect_communities()` returns a wrapper dict+(``communities``, ``node_assignments``, ``modularity``, ``algorithm``).+Four production callers still consumed that wrapper as a flat+``{community_id: members}`` mapping, so they silently produced wrong community+data: a wrapper key such as ``node_assignments`` could be taken for a community+id, and ``len()`` of the wrapper reported ``4`` for every graph and algorithm.++Every graph used below has two communities, so a constant wrapper-key count+cannot accidentally pass.+"""++import unittest+from unittest import mock++from semantica.context import ContextGraph+from semantica.context.context_retriever import ContextRetriever+from semantica.context.decision_query import DecisionQuery+from semantica.kg import CommunityDetector+from semantica.vector_store.decision_embedding_pipeline import (+ DecisionEmbeddingPipeline,+)+++def _two_community_graph() -> ContextGraph:+ """Two disjoint clusters: (alice, bob, carol) and (dave, erin)."""+ graph = ContextGraph(advanced_analytics=True)+ for name in ("alice", "bob", "carol", "dave", "erin"):+ graph.add_node(name, node_type="Person", content=name)+ graph.add_edge("alice", "bob", edge_type="knows")+ graph.add_edge("bob", "carol", edge_type="knows")+ graph.add_edge("dave", "erin", edge_type="knows")+ return graph+++class TestAnalyzeGraphWithKgCommunityCount(unittest.TestCase):+ """`ContextGraph.analyze_graph_with_kg` must count groups, not wrapper keys."""++ def _analyze(self) -> dict:+ graph = _two_community_graph()+ # Keep the real community detector; stub the other components so only+ # the community path is exercised.+ graph.kg_components["centrality_calculator"] = mock.Mock(+ calculate_all_centrality=mock.Mock(return_value={"centrality_measures": {}})+ )+ graph.kg_components["connectivity_analyzer"] = mock.Mock(+ analyze_connectivity=mock.Mock(return_value={})+ )+ graph.kg_components["node_embedder"] = mock.Mock(+ compute_embeddings=mock.Mock(return_value={})+ )+ return graph.analyze_graph_with_kg()++ def test_num_communities_reports_detected_groups(self):+ analysis = self._analyze()+ self.assertNotIn("error", analysis, analysis)+ community_analysis = analysis["community_analysis"]+ self.assertEqual(community_analysis["num_communities"], 2)+ self.assertEqual(len(community_analysis["communities"]), 2)+ # The wrapper dict has four keys; a key count must never leak through.+ self.assertNotEqual(community_analysis["num_communities"], 4)+++class TestExpandDecisionContextCommunity(unittest.TestCase):+ """`ContextRetriever._expand_decision_context` must read node_assignments."""++ def test_only_same_community_entities_are_added(self):+ graph = _two_community_graph()+ retriever = ContextRetriever(vector_store=mock.Mock(), knowledge_graph=graph)+ retriever.path_finder = None+ retriever.centrality_calculator = None+ retriever.community_detector = CommunityDetector()++ detected = CommunityDetector().detect_communities(graph)+ assignments = detected["node_assignments"]+ self.assertEqual(len(detected["communities"]), 2, assignments)+ alice_community = assignments["alice"]+ same_community = {+ node+ for node, community_id in assignments.items()+ if community_id == alice_community and node != "alice"+ }+ other_communities = {+ node+ for node, community_id in assignments.items()+ if community_id != alice_community+ }+ self.assertTrue(other_communities, assignments)++ expanded = retriever._expand_decision_context([{"name": "alice"}], max_hops=1)+ community_names = {+ entity["name"]+ for entity in expanded+ if entity.get("source") == "community_detector"+ }++ self.assertTrue(+ same_community & community_names,+ (same_community, community_names),+ )+ for leaked in other_communities:+ self.assertNotIn(leaked, community_names)+ # No wrapper key may ever surface as an entity name.+ self.assertNotIn("node_assignments", community_names)+ self.assertNotIn("communities", community_names)+++class TestGetEntityCommunities(unittest.TestCase):+ """`DecisionEmbeddingPipeline._get_entity_communities` must use assignments."""++ def test_assignments_come_from_node_assignments(self):+ graph = _two_community_graph()+ pipeline = DecisionEmbeddingPipeline(+ vector_store=mock.Mock(),+ graph_store=graph,+ use_graph_features=True,+ )+ pipeline.community_detector = CommunityDetector()++ detected = CommunityDetector().detect_communities(graph)+ expected = detected["node_assignments"]+ self.assertEqual(len(detected["communities"]), 2, expected)++ got = pipeline._get_entity_communities(["alice", "carol", "dave"])+ self.assertEqual(got["alice"], expected["alice"])+ self.assertEqual(got["carol"], expected["carol"])+ self.assertEqual(got["dave"], expected["dave"])+ self.assertNotEqual(got["alice"], got["dave"])++ # An entity that is not in the graph is dropped, not mapped to a key.+ self.assertEqual(pipeline._get_entity_communities(["ghost"]), {})+++class TestAnalyzeDecisionInfluenceCommunity(unittest.TestCase):+ """`DecisionQuery.analyze_decision_influence` must derive community data."""++ def _query_with(self, detector) -> DecisionQuery:+ graph_store = mock.Mock()+ graph_store.execute_query.return_value = {"success": True, "records": []}+ query = DecisionQuery(graph_store=graph_store, advanced_analytics=False)+ query.kg_components = {"community_detector": detector}+ return query++ def test_community_info_is_derived_from_node_assignments(self):+ detector = mock.Mock()+ detector.detect_communities.return_value = {+ "communities": [["d1", "d2"], ["d3", "d4", "d5"]],+ "node_assignments": {"d1": 0, "d2": 0, "d3": 1, "d4": 1, "d5": 1},+ "modularity": 0.4,+ "algorithm": "louvain",+ }+ analysis = self._query_with(detector).analyze_decision_influence("d4")++ info = analysis["community_info"]+ self.assertEqual(info["community_id"], 1)+ self.assertEqual(info["community_size"], 3)+ self.assertEqual(set(info["community_members"]), {"d3", "d4", "d5"})+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/vector_store/test_kg_integration.py b/tests/vector_store/test_kg_integration.pyindex 857422c1..898bbd3e 100644--- a/tests/vector_store/test_kg_integration.py+++ b/tests/vector_store/test_kg_integration.py@@ -156,8 +156,16 @@ class TestKGAlgorithmIntegration:# Mock KG algorithmsmock_path_finder.return_value.find_shortest_path.return_value = ["entity1", "entity2", "entity3"]mock_community.return_value.detect_communities.return_value = {- 0: ["customer_123", "related_entity1", "related_entity2"],- 1: ["other_entity"]+ "communities": [+ ["customer_123", "related_entity1", "related_entity2"],+ ["other_entity"],+ ],+ "node_assignments": {+ "customer_123": 0, "related_entity1": 0, "related_entity2": 0,+ "other_entity": 1,+ },+ "modularity": 0.5,+ "algorithm": "louvain",}mock_centrality.return_value.calculate_degree_centrality.return_value = 0.8@@ -280,8 +288,16 @@ class TestKGAlgorithmSpecificFeatures:# Mock community detectorwith patch.object(pipeline.community_detector, 'detect_communities') as mock_community:mock_community.return_value = {- 0: ["entity1", "entity2", "entity3"],- 1: ["entity4", "entity5"]+ "communities": [+ ["entity1", "entity2", "entity3"],+ ["entity4", "entity5"],+ ],+ "node_assignments": {+ "entity1": 0, "entity2": 0, "entity3": 0,+ "entity4": 1, "entity5": 1,+ },+ "modularity": 0.5,+ "algorithm": "louvain",}# Test community detection