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): normalize method and algorithm casing in detect_communities with fallback warning (#1925) (#1930)
Akshat Raj41f2d254522d
diff --git a/semantica/kg/community_detector.py b/semantica/kg/community_detector.pyindex 7d7fa153..a6bed516 100644--- a/semantica/kg/community_detector.py+++ b/semantica/kg/community_detector.py@@ -478,9 +478,11 @@ class CommunityDetector:graph: Input graph for community detectionalgorithm: Community detection algorithm to use. Supported valuesare "louvain", "leiden", "overlapping" and- "label_propagation".- method: Alias for ``algorithm``. A value that is not supported is- ignored, which leaves ``algorithm`` in effect.+ "label_propagation". Names are case-insensitive and+ tolerate "-", "_" and spaces as separators.+ method: Alias for ``algorithm``, matched the same way. A value+ that is not recognized logs a warning and falls back+ to the ``algorithm`` argument.**options: Additional detection options (passed to algorithm-specific method)Returns:@@ -498,6 +500,9 @@ class CommunityDetector:"label_propagation": self.detect_communities_label_propagation,}+ # Canonical lookup for casing/separators (e.g. 'labelpropagation')+ canonical_map = {k.replace("_", ""): k for k in handlers}+# The names are looked up in a dict, so a non-string would either be# ignored or fail as "unhashable type"; name the real problem instead.if method is not None and not isinstance(method, str):@@ -511,14 +516,37 @@ class CommunityDetector:# 'method' is an alias for 'algorithm'if method is not None:- algorithm = method if method in handlers else algorithm+ clean_m = method.strip().lower().replace("-", "_").replace(" ", "")+ if clean_m in handlers:+ algorithm = clean_m+ elif clean_m.replace("_", "") in canonical_map:+ algorithm = canonical_map[clean_m.replace("_", "")]+ else:+ self.logger.warning(+ f"Unrecognized community detection method '{method}'. "+ f"Falling back to active algorithm '{algorithm}'."+ )- self.logger.info(f"Detecting communities using {algorithm} algorithm")+ # Normalize algorithm parameter for casing/separator tolerance+ clean_algo = (+ algorithm.strip().lower().replace("-", "_").replace(" ", "")+ if isinstance(algorithm, str)+ else algorithm+ )+ if clean_algo in handlers:+ handler = handlers[clean_algo]+ elif (+ isinstance(clean_algo, str) and clean_algo.replace("_", "") in canonical_map+ ):+ handler = handlers[canonical_map[clean_algo.replace("_", "")]]+ else:+ handler = handlers.get(algorithm)- handler = handlers.get(algorithm)if handler is None:raise ValueError(f"Unsupported algorithm: {algorithm}")+ self.logger.info(f"Detecting communities using {algorithm} algorithm")+return handler(graph, **options)def _build_adjacency(self, graph) -> Dict[str, List[str]]:diff --git a/tests/kg/test_community_detector_dispatch.py b/tests/kg/test_community_detector_dispatch.pyindex b0551cb3..dc0db10d 100644--- a/tests/kg/test_community_detector_dispatch.py+++ b/tests/kg/test_community_detector_dispatch.py@@ -485,3 +485,73 @@ def test_chunked_adjacency_keeps_a_neighbour_from_another_chunk():assert sorted(chunked[0]) == [1]assert sorted(chunked[1]) == [0, 2]+++def test_detect_communities_method_casing_and_separator_variations(monkeypatch):+ """Casing, dashes and condensed names route without falling back."""+ called_methods = []++ def mock_lp(self, graph, **kwargs):+ called_methods.append("label_propagation")+ return {"communities": []}++ monkeypatch.setattr(+ CommunityDetector, "detect_communities_label_propagation", mock_lp+ )++ detector = CommunityDetector()+ graph = nx.path_graph(4)++ # Test all variations mentioned in issue #1925+ variations = [+ "Label_Propagation",+ "label-propagation",+ "labelpropagation",+ "LABEL_PROPAGATION",+ ]+ for variant in variations:+ called_methods.clear()+ detector.detect_communities(graph, method=variant)+ assert called_methods == [+ "label_propagation"+ ], f"Failed for method variant: {variant}"+++def test_detect_communities_unrecognized_method_logs_warning_and_falls_back(caplog):+ """An unrecognized method logs one warning and still runs Louvain."""+ with caplog.at_level(logging.WARNING, logger="semantica.community_detector"):+ result = CommunityDetector().detect_communities(+ _graph_dict(), method="unknown_typo_method"+ )++ assert result["algorithm"] == "louvain"+ assert result["communities"]++ warnings = [+ record+ for record in caplog.records+ if "Unrecognized community detection method 'unknown_typo_method'. "+ "Falling back to active algorithm 'louvain'." in record.getMessage()+ ]+ assert len(warnings) == 1+ assert warnings[0].name == "semantica.community_detector"+ assert warnings[0].levelno == logging.WARNING+++def test_detect_communities_algorithm_casing_parity(monkeypatch):+ """Verify that algorithm parameter handles casing variations consistently."""+ called_methods = []++ def mock_lp(self, graph, **kwargs):+ called_methods.append("label_propagation")+ return {"communities": []}++ monkeypatch.setattr(+ CommunityDetector, "detect_communities_label_propagation", mock_lp+ )++ detector = CommunityDetector()+ graph = nx.path_graph(4)++ detector.detect_communities(graph, algorithm="Label_Propagation")+ assert called_methods == ["label_propagation"]