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(context): restore duplicate guard in add_causal_relationship (#1921)
Raashish Aggarwal320761de5d04
diff --git a/.github/full-suite-known-failures.txt b/.github/full-suite-known-failures.txtindex 7ee9975b..ba0fb8c1 100644--- a/.github/full-suite-known-failures.txt+++ b/.github/full-suite-known-failures.txt@@ -128,13 +128,11 @@ tests/test_arrow_exporter.py::TestArrowExporter::test_progress_trackingtests/vector_store/test_backward_compatibility.py::TestVectorStoreBackwardCompatibility::test_progress_tracking_unchanged# --- Assertion drift in the test or its expectation ----------------------------tests/context/test_decision_causal_edge_regression.py::test_add_causal_relationship_returns_false_for_duplicatetests/export/test_distance_exporter.py::test_hop_distance_no_warning_when_kg_unavailabletests/ingest/test_repo_ingestor_security.py::TestIsReservedNAT64Regression::test_nat64_local_prefix_not_blockedtests/integrations/agno/test_context_store.py::TestAgnoContextStoreUpsertNERAttributes::test_upsert_indexes_entity_label_as_typetests/integrations/agno/test_context_store.py::TestAgnoContextStoreUpsertNERAttributes::test_upsert_indexes_entity_text_not_reprtests/semantic_extract/test_cache_backends.py::test_zero_ttl_expires_immediately_on_both_backends-tests/test_mcp_decisions_link.py::TestLinkDecisionsEndToEnd::test_duplicate_link_returns_falsetests/vector_store/test_hybrid_similarity.py::TestHybridSimilarityCalculator::test_pearson_similarity_calculationtests/vector_store/test_vector_store.py::test_backend_mirroring_and_savediff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.pyindex f81fedb8..ec8bbc73 100644--- a/semantica/context/context_graph.py+++ b/semantica/context/context_graph.py@@ -3145,8 +3145,12 @@ class ContextGraph:self.logger.warning(f"Audit trail callback failed for node {node.node_id}: {e}")return True- def _add_internal_edge(self, edge: ContextEdge) -> bool:- """Internal method to add an edge."""+ def _add_internal_edge(self, edge: ContextEdge, unique_type: bool = False) -> bool:+ """Internal method to add an edge.++ With ``unique_type=True`` the edge is skipped when the source already has+ an edge of the same type to the same target.+ """if edge.source_id is None or edge.target_id is None:self.logger.warning("Skipping internal edge with invalid endpoints: %r", edge)return False@@ -3155,6 +3159,11 @@ class ContextGraph:# exact edge is already stored; re-adding it is a no-op (issue #922).if edge.edge_id in self._edge_index:return False+ if unique_type and any(+ e.target_id == edge.target_id and e.edge_type == edge.edge_type+ for e in self._adjacency.get(edge.source_id, [])+ ):+ return False# Ensure nodes existif edge.source_id not in self.nodes:@@ -3903,9 +3912,14 @@ class ContextGraph:relationship_type: Type of relationship (CAUSED, INFLUENCED, PRECEDENT_FOR)Returns:- True when the edge was added; False when it was skipped because a- decision ID is unknown or a node is not a decision (logged as a- warning so callers no longer mistake the skip for success).+ True when a new causal edge was inserted.+ False when the operation was skipped without inserting an edge:+ - source or target decision ID is not present in the graph;+ - source or target node exists but is not a decision node;+ - an equivalent causal relationship (same source, target, and+ normalized relationship type) already exists.+ Skipped operations are logged at WARNING level. Invalid+ relationship types raise ValueError instead of returning False."""# Normalize so callers may use either vocabulary's spelling# ("causes" from CausalChainAnalyzer, or "CAUSED" from this module's@@ -3945,7 +3959,16 @@ class ContextGraph:weight=1.0,metadata={"recorded_at": datetime.utcnow().isoformat()},)- self._add_internal_edge(edge)+ # edge_id includes recorded_at, so the same causal link recorded twice+ # gets a new id; compare (target, type) instead.+ if not self._add_internal_edge(edge, unique_type=True):+ self.logger.warning(+ "Causal relationship %s -[%s]-> %s already exists; skipping",+ source_decision_id,+ relationship_type,+ target_decision_id,+ )+ return Falsereturn Truedef get_causal_chain(diff --git a/tests/context/test_decision_causal_edge_regression.py b/tests/context/test_decision_causal_edge_regression.pyindex 8370407e..9e83beb7 100644--- a/tests/context/test_decision_causal_edge_regression.py+++ b/tests/context/test_decision_causal_edge_regression.py@@ -571,8 +571,23 @@ def test_add_causal_relationship_non_decision_node_emits_warning(caplog):assert any(src in r.message for r in caplog.records)-def test_add_causal_relationship_returns_false_for_duplicate():+def test_add_causal_relationship_returns_false_for_duplicate(monkeypatch):"""Duplicate insertion of the same causal edge must return False (issue #1653 Part 2)."""+ import itertools+ from datetime import datetime, timedelta++ import semantica.context.context_graph as context_graph_module++ # Give each call its own recorded_at, as happens whenever the two calls don't+ # land in the same microsecond (#1873).+ ticks = itertools.count()++ class _Clock(datetime):+ @classmethod+ def utcnow(cls):+ return datetime(2026, 1, 1) + timedelta(microseconds=next(ticks))++ monkeypatch.setattr(context_graph_module, "datetime", _Clock)graph, src, tgt = _two_decision_graph()first = graph.add_causal_relationship(src, tgt, "CAUSED")second = graph.add_causal_relationship(src, tgt, "CAUSED")@@ -581,3 +596,27 @@ def test_add_causal_relationship_returns_false_for_duplicate():# Exactly one edge stored, not two.causal_edges = [e for e in graph.edges if e.source_id == src and e.target_id == tgt]assert len(causal_edges) == 1+++def test_add_causal_relationship_runs_callback_without_graph_lock():+ """The audit callback must not run while the graph lock is held."""+ import threading++ graph, src, tgt = _two_decision_graph()+ lock_free = []++ def try_lock():+ acquired = graph._lock.acquire(timeout=1)+ if acquired:+ graph._lock.release()+ lock_free.append(acquired)++ def callback(op, edge_id, payload):+ # Another thread can only take the lock if this thread is not holding it.+ t = threading.Thread(target=try_lock)+ t.start()+ t.join()++ graph.mutation_callback = callback+ assert graph.add_causal_relationship(src, tgt, "CAUSED") is True+ assert lock_free == [True]