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(export): log DistanceExporter metric computation failures instead of swallowing them (#879)
Amir Fathib0080c3602dc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b23ed156..1107d74b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -56,6 +56,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **Fixed along the way**: `MilvusStore`'s metadata expression builder rendered `NaN`/`Infinity` filter values as bare unquoted tokens, producing an invalid Milvus expression whose server-side rejection was then swallowed by a broad `except`, indistinguishable from "no matches"; these values are now rejected up front with a clear `ValidationError`- New/expanded test coverage in `tests/vector_store/test_backend_metadata_filtering.py` (all 7 backends, including the Pinecone dimension/zero-vector, PgVector boolean-list, FAISS `limit=0`, and Milvus `NaN` regressions) and `tests/vector_store/test_sqlite_vec_store.py` (new `TestSQLiteVecStoreFilterByMetadata`, run against the real `sqlite-vec` extension, including the array-vs-scalar intersection case)+- **`DistanceExporter` silently swallowed metric computation failures, exporting `None` values indistinguishable from a legitimate "no path" result** (#879, closes #874) by @AmirF194+ - `_betweenness`, `_hop_distance`, `_weighted_distance`, and `_semantic_similarity` each caught `Exception` and returned their sentinel (`None`/`{}`) with no logging; a failed computation and a real "no path exists" looked identical in exported CSV/JSONL/DataFrame data. All four now log a `warning` with `exc_info=True` before returning the sentinel; exported row shape and values are unchanged+ - **Fixed along the way**: the module logger was built with `get_logger(__name__)`, which double-prefixed it to `semantica.semantica.export.distance_exporter` — a name `setup_logging()` never configures — so this module's logging (including a pre-existing `logger.debug` call) was silent regardless. Now uses `get_logger("export.distance_exporter")`, matching every other exporter in the module+ - New regression coverage in `tests/export/test_distance_exporter.py`: warnings fire on exception for all four helpers, exported sentinel values/shape stay unchanged, and the legitimate "no KG backend" `None` path still logs nothing+ - Full `tests/export/` suite: 71 passed+### Security- **HTTP response header injection via `node_id`, unbounded-memory DoS in link prediction, and unsanitized imported node IDs in the Explorer** (#912) by @Sunil56224972diff --git a/semantica/export/distance_exporter.py b/semantica/export/distance_exporter.pyindex be78637d..060f041a 100644--- a/semantica/export/distance_exporter.py+++ b/semantica/export/distance_exporter.py@@ -21,7 +21,7 @@ from typing import Any, Dict, List, Optionalfrom ..utils.helpers import classify_path_distancefrom ..utils.logging import get_logger-logger = get_logger(__name__)+logger = get_logger("export.distance_exporter")_KG_AVAILABLE = Falsetry:@@ -72,6 +72,7 @@ class DistanceExporter:result = self._centrality.calculate_betweenness_centrality(graph_dict)return result.get("betweenness", {}) if isinstance(result, dict) else {}except Exception:+ logger.warning("Betweenness centrality computation failed; omitting from export", exc_info=True)return {}def _hop_distance(self, graph_dict: Dict[str, Any], src: str, tgt: str) -> Optional[int]:@@ -82,6 +83,7 @@ class DistanceExporter:path = result.get("path", []) if isinstance(result, dict) else (result or [])return len(path) - 1 if path else Noneexcept Exception:+ logger.warning("Hop distance computation failed for %s -> %s; returning None sentinel", src, tgt, exc_info=True)return Nonedef _weighted_distance(self, graph_dict: Dict[str, Any], src: str, tgt: str) -> Optional[float]:@@ -93,6 +95,7 @@ class DistanceExporter:return float(result.get("total_weight", len(result.get("path", [])) - 1))return Noneexcept Exception:+ logger.warning("Weighted distance computation failed for %s -> %s; returning None sentinel", src, tgt, exc_info=True)return Nonedef _semantic_similarity(self, graph_dict: Dict[str, Any], src: str, tgt: str) -> Optional[float]:@@ -102,6 +105,7 @@ class DistanceExporter:sim = self._similarity.cosine_similarity(graph_dict, src, tgt)return float(sim) if isinstance(sim, (int, float)) else Noneexcept Exception:+ logger.warning("Semantic similarity computation failed for %s -> %s; returning None sentinel", src, tgt, exc_info=True)return Nonedef compute_pairs(diff --git a/tests/export/test_distance_exporter.py b/tests/export/test_distance_exporter.pynew file mode 100644index 00000000..e9d20b67--- /dev/null+++ b/tests/export/test_distance_exporter.py@@ -0,0 +1,107 @@+"""Tests for DistanceExporter's silent-exception handling (issue #874).++Each of the four private metric helpers (_betweenness, _hop_distance,+_weighted_distance, _semantic_similarity) wraps its computation in a bare+except Exception and returns None/{} with no signal, so a raised exception is+indistinguishable in the exported data from a legitimate "no path" result.+"""++import logging++import pytest++from semantica.export.distance_exporter import DistanceExporter+++class _Node:+ def __init__(self, node_id):+ self.node_id = node_id+ self.node_type = "t"+ self.content = ""+ self.properties = {}+++class _Graph:+ def __init__(self):+ self.nodes = {"a": _Node("a"), "b": _Node("b")}+ self.edges = []+++class _RaisingPathFinder:+ def bfs_shortest_path(self, graph_dict, src, tgt):+ raise RuntimeError("bfs boom")++ def dijkstra_shortest_path(self, graph_dict, src, tgt):+ raise RuntimeError("dijkstra boom")+++class _RaisingSimilarity:+ def cosine_similarity(self, graph_dict, src, tgt):+ raise RuntimeError("cosine boom")+++class _RaisingCentrality:+ def calculate_betweenness_centrality(self, graph_dict):+ raise RuntimeError("betweenness boom")+++def exporter():+ exp = DistanceExporter(_Graph())+ exp._path_finder = _RaisingPathFinder()+ exp._similarity = _RaisingSimilarity()+ exp._centrality = _RaisingCentrality()+ return exp+++def test_hop_distance_logs_warning_on_exception(exporter, caplog):+ with caplog.at_level(logging.WARNING, logger="semantica.export.distance_exporter"):+ result = exporter._hop_distance({}, "a", "b")+ assert result is None+ assert any("Hop distance" in rec.message for rec in caplog.records)+++def test_weighted_distance_logs_warning_on_exception(exporter, caplog):+ with caplog.at_level(logging.WARNING, logger="semantica.export.distance_exporter"):+ result = exporter._weighted_distance({}, "a", "b")+ assert result is None+ assert any("Weighted distance" in rec.message for rec in caplog.records)+++def test_semantic_similarity_logs_warning_on_exception(exporter, caplog):+ with caplog.at_level(logging.WARNING, logger="semantica.export.distance_exporter"):+ result = exporter._semantic_similarity({}, "a", "b")+ assert result is None+ assert any("Semantic similarity" in rec.message for rec in caplog.records)+++def test_betweenness_logs_warning_on_exception(exporter, caplog):+ with caplog.at_level(logging.WARNING, logger="semantica.export.distance_exporter"):+ result = exporter._betweenness({})+ assert result == {}+ assert any("Betweenness" in rec.message for rec in caplog.records)+++def test_compute_pairs_still_produces_none_sentinels_when_metrics_raise(exporter, caplog):+ """The exported row shape is unchanged: a raised exception still yields+ None/"distant", it is just no longer silent."""+ with caplog.at_level(logging.WARNING, logger="semantica.export.distance_exporter"):+ rows = exporter.compute_pairs()+ assert len(rows) == 2+ for row in rows:+ assert row["hop_count"] is None+ assert row["weighted_distance"] is None+ assert row["semantic_similarity"] is None+ assert row["distance_band"] == "distant"+ assert len(caplog.records) >= 4+++def test_hop_distance_no_warning_when_kg_unavailable(caplog):+ """A legitimate 'no KG backend' None (the pre-existing early-return path)+ must not be confused with an exception; nothing to log there."""+ exp = DistanceExporter(_Graph())+ exp._path_finder = None+ with caplog.at_level(logging.WARNING, logger="semantica.export.distance_exporter"):+ result = exp._hop_distance({}, "a", "b")+ assert result is None+ assert len(caplog.records) == 0