Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix: replace mutable default arguments with None + in-body defaults (#1068)

yzxcj797b177fa7556dc
diff --git a/semantica/kg/graph_analyzer.py b/semantica/kg/graph_analyzer.py
index dd26cb5f..7f32e5b8 100644
--- a/semantica/kg/graph_analyzer.py
+++ b/semantica/kg/graph_analyzer.py
@@ -253,7 +253,7 @@ class GraphAnalyzer:
graph,
start_time=None,
end_time=None,
- metrics=["node_count", "edge_count", "density", "communities"],
+ metrics=None,
interval=None,
**options,
):
@@ -271,6 +271,8 @@ class GraphAnalyzer:
Returns:
Evolution analysis results with time series data
"""
+ if metrics is None:
+ metrics = ["node_count", "edge_count", "density", "communities"]
self.logger.info("Analyzing temporal evolution")
from .temporal_query import TemporalGraphQuery
diff --git a/semantica/split/kg_chunkers.py b/semantica/split/kg_chunkers.py
index e1909aec..426ff5ea 100644
--- a/semantica/split/kg_chunkers.py
+++ b/semantica/split/kg_chunkers.py
@@ -375,7 +375,7 @@ class HierarchicalChunker:
def __init__(
self,
- levels: List[str] = ["section", "paragraph", "sentence"],
+ levels: Optional[List[str]] = None,
chunk_sizes: Optional[List[int]] = None,
**kwargs,
):
@@ -387,6 +387,8 @@ class HierarchicalChunker:
chunk_sizes: Chunk sizes for each level
**kwargs: Additional options
"""
+ if levels is None:
+ levels = ["section", "paragraph", "sentence"]
self.levels = levels
self.chunk_sizes = chunk_sizes or [2000, 1000, 500]
self.options = kwargs
diff --git a/semantica/split/methods.py b/semantica/split/methods.py
index 61b67ee0..3ba339b7 100644
--- a/semantica/split/methods.py
+++ b/semantica/split/methods.py
@@ -1402,7 +1402,7 @@ def split_embedding_semantic(
def split_hierarchical(
text: str,
- levels: List[str] = ["section", "paragraph", "sentence"],
+ levels: Optional[List[str]] = None,
chunk_sizes: Optional[List[int]] = None,
**kwargs,
) -> List[Chunk]:
@@ -1420,6 +1420,8 @@ def split_hierarchical(
"""
if chunk_sizes is None:
chunk_sizes = [2000, 1000, 500]
+ if levels is None:
+ levels = ["section", "paragraph", "sentence"]
# Start with largest level
if "section" in levels:
diff --git a/tests/kg/test_kg.py b/tests/kg/test_kg.py
index 4d02b1e4..48cb12d1 100644
--- a/tests/kg/test_kg.py
+++ b/tests/kg/test_kg.py
@@ -242,6 +242,107 @@ class TestGraphAnalyzer(unittest.TestCase):
self.mock_connectivity.analyze_connectivity.assert_called_once()
mock_metrics.assert_called_once()
+class TestAnalyzeTemporalEvolutionMutableDefault(unittest.TestCase):
+ """Regression tests for fix: replace mutable default argument in
+ GraphAnalyzer.analyze_temporal_evolution (metrics=[...] -> None).
+
+ TemporalGraphQuery is imported lazily inside the method body
+ (``from .temporal_query import TemporalGraphQuery``), so it is patched
+ at its definition site: ``semantica.kg.temporal_query.TemporalGraphQuery``.
+ """
+
+ def setUp(self):
+ self.mock_tracker_patcher = patch("semantica.kg.graph_analyzer.get_progress_tracker")
+ self.mock_get_tracker = self.mock_tracker_patcher.start()
+ self.mock_get_tracker.return_value = MagicMock()
+
+ self.mock_centrality_patcher = patch("semantica.kg.graph_analyzer.CentralityCalculator")
+ self.mock_centrality_patcher.start()
+
+ self.mock_community_patcher = patch("semantica.kg.graph_analyzer.CommunityDetector")
+ self.mock_community_patcher.start()
+
+ self.mock_connectivity_patcher = patch("semantica.kg.graph_analyzer.ConnectivityAnalyzer")
+ self.mock_connectivity_patcher.start()
+
+ # TemporalGraphQuery is imported *inside* the method body, so patch it
+ # at the definition module rather than at the caller module.
+ self.mock_tq_patcher = patch(
+ "semantica.kg.temporal_query.TemporalGraphQuery", autospec=False
+ )
+ mock_tq_cls = self.mock_tq_patcher.start()
+ self.mock_tq = MagicMock()
+ self.mock_tq.analyze_evolution.return_value = {"snapshots": []}
+ mock_tq_cls.return_value = self.mock_tq
+
+ def tearDown(self):
+ patch.stopall()
+
+ def _make_analyzer(self):
+ return GraphAnalyzer()
+
+ def test_default_metrics_value_is_canonical(self):
+ """When metrics=None, the four canonical metric names must be used."""
+ analyzer = self._make_analyzer()
+ graph = {"entities": [], "relationships": []}
+ result = analyzer.analyze_temporal_evolution(graph)
+
+ self.assertEqual(
+ sorted(result["metrics_tracked"]),
+ sorted(["node_count", "edge_count", "density", "communities"]),
+ )
+
+ def test_default_metrics_independent_across_calls(self):
+ """Mutating the returned metrics_tracked list must not affect the next call."""
+ analyzer = self._make_analyzer()
+ graph = {"entities": [], "relationships": []}
+
+ result1 = analyzer.analyze_temporal_evolution(graph)
+ # Mutate the returned list in-place.
+ result1["metrics_tracked"].append("MUTATED")
+
+ result2 = analyzer.analyze_temporal_evolution(graph)
+ self.assertNotIn(
+ "MUTATED",
+ result2["metrics_tracked"],
+ "Mutable default leaked: 'MUTATED' appeared in the second call's metrics list",
+ )
+
+ def test_result_contains_metrics_tracked_key(self):
+ """Return value must include 'metrics_tracked' with the default list."""
+ analyzer = self._make_analyzer()
+ graph = {"entities": [], "relationships": []}
+ result = analyzer.analyze_temporal_evolution(graph)
+
+ self.assertIn("metrics_tracked", result)
+ self.assertEqual(
+ sorted(result["metrics_tracked"]),
+ sorted(["node_count", "edge_count", "density", "communities"]),
+ )
+
+ def test_explicit_metrics_override_is_respected(self):
+ """Explicitly passed metrics must be forwarded and reflected in the return value."""
+ analyzer = self._make_analyzer()
+ graph = {"entities": [], "relationships": []}
+ custom = ["node_count"]
+ result = analyzer.analyze_temporal_evolution(graph, metrics=custom)
+
+ self.assertEqual(result["metrics_tracked"], custom)
+
+ def test_explicit_metrics_mutation_does_not_affect_default(self):
+ """Mutating the list passed as an explicit argument must not corrupt
+ a subsequent default call."""
+ analyzer = self._make_analyzer()
+ graph = {"entities": [], "relationships": []}
+
+ explicit = ["node_count"]
+ analyzer.analyze_temporal_evolution(graph, metrics=explicit)
+ explicit.append("MUTATED")
+
+ result = analyzer.analyze_temporal_evolution(graph)
+ self.assertNotIn("MUTATED", result["metrics_tracked"])
+
+
class TestTemporalGraphQuery(unittest.TestCase):
def setUp(self):
self.mock_tracker_patcher = patch("semantica.utils.progress_tracker.get_progress_tracker")
diff --git a/tests/split/test_chunkers.py b/tests/split/test_chunkers.py
index 0fff307c..4193f0e3 100644
--- a/tests/split/test_chunkers.py
+++ b/tests/split/test_chunkers.py
@@ -638,3 +638,89 @@ Body paragraph under a distinct heading for separation checks.
self.SAMPLE * 3, chunk_size=80, ner_method="pattern"
)
assert len(chunks) >= 1
+
+
+# ---------------------------------------------------------------------------
+# Mutable-default regression tests (fix: replace mutable default arguments)
+# ---------------------------------------------------------------------------
+
+
+class TestMutableDefaultRegression:
+ """Regression tests proving that mutable default arguments do not leak
+ between calls. Each test mutates the list returned / stored by one call
+ and verifies that a subsequent call still receives the *original* default
+ value, not the mutated one.
+ """
+
+ # --- split_hierarchical -------------------------------------------------
+
+ def test_split_hierarchical_default_levels_are_independent_across_calls(self):
+ """Mutating the levels list from one call must not affect the next."""
+ text = "Para one.\n\nPara two.\n\nPara three."
+
+ # First call – capture and mutate the levels list indirectly by
+ # passing explicit levels and then appending to a reference.
+ call1_levels: list = ["paragraph"]
+ chunks1 = split_hierarchical(text, levels=call1_levels, chunk_sizes=[1000])
+ # Mutate the list that was passed in.
+ call1_levels.append("MUTATED")
+
+ # Second call with default levels=None must still use the canonical default.
+ chunks2 = split_hierarchical(text)
+ # The function must succeed and produce chunks (not raise because
+ # "MUTATED" is not a valid level name).
+ assert len(chunks2) >= 1
+
+ def test_split_hierarchical_none_default_creates_fresh_list_each_call(self):
+ """Two calls with levels=None must receive independent list objects."""
+ text = "A sentence.\n\nAnother sentence."
+
+ # Patch the body assignment so we can capture it.
+ captured: list = []
+ original_fn = split_hierarchical.__wrapped__ if hasattr(split_hierarchical, "__wrapped__") else None
+
+ # Use a simpler black-box approach: call twice and verify behaviour.
+ chunks_a = split_hierarchical(text)
+ chunks_b = split_hierarchical(text)
+
+ # Both calls should produce identical results (same default).
+ assert len(chunks_a) == len(chunks_b)
+ assert [c.text for c in chunks_a] == [c.text for c in chunks_b]
+
+ def test_split_hierarchical_default_chunk_sizes_are_independent_across_calls(self):
+ """Mutating chunk_sizes in one call must not affect the next."""
+ text = "Para A.\n\nPara B."
+ mutable_sizes = [5000, 2000, 1000]
+ split_hierarchical(text, chunk_sizes=mutable_sizes)
+ # Mutate after first call.
+ mutable_sizes[0] = 1 # Would produce very different chunking if leaked.
+
+ # Second call with default chunk_sizes=None must still use canonical defaults.
+ chunks = split_hierarchical(text)
+ assert len(chunks) >= 1
+
+ # --- HierarchicalChunker ------------------------------------------------
+
+ def test_hierarchical_chunker_default_levels_independent_across_instances(self):
+ """Mutating levels on one instance must not affect a second instance
+ created with the default."""
+ chunker_a = HierarchicalChunker()
+ # Mutate the instance attribute that was built from the default.
+ chunker_a.levels.append("MUTATED")
+
+ chunker_b = HierarchicalChunker()
+ assert "MUTATED" not in chunker_b.levels, (
+ "Mutation of chunker_a.levels leaked into chunker_b — "
+ "mutable default not fixed properly"
+ )
+
+ def test_hierarchical_chunker_default_levels_value(self):
+ """Default levels must equal the canonical list."""
+ chunker = HierarchicalChunker()
+ assert chunker.levels == ["section", "paragraph", "sentence"]
+
+ def test_hierarchical_chunker_explicit_levels_preserved(self):
+ """Explicitly passed levels must be stored as given."""
+ custom = ["document", "paragraph"]
+ chunker = HierarchicalChunker(levels=custom)
+ assert chunker.levels == custom