Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(mcp): persist link_decisions to SEMANTICA_KG_PATH (#1828)

Maxi6e2dbda1459e
diff --git a/semantica_mcp/mcp/tools/decisions.py b/semantica_mcp/mcp/tools/decisions.py
index 28124095..83dc3778 100644
--- a/semantica_mcp/mcp/tools/decisions.py
+++ b/semantica_mcp/mcp/tools/decisions.py
@@ -310,20 +310,67 @@ def handle_link_decisions(args: dict) -> dict:
return {"error": "relationship is required"}
try:
graph = get_graph()
- added = graph.add_causal_relationship(source, target, relationship)
- except ValueError as exc:
- return {"error": str(exc)}
except Exception as exc:
log.exception("link_decisions failed")
return {"error": str(exc)}
+
+ # Hold the graph lock from the add through the save (and any rollback) so a
+ # concurrent caller can't slip an edge in between: a failed save must only
+ # undo the edge this call made, never someone else's.
+ with graph._lock:
+ try:
+ edge_count = len(graph.edges)
+ added = graph.add_causal_relationship(source, target, relationship)
+ new_edges = list(graph.edges)[edge_count:]
+ except ValueError as exc:
+ return {"error": str(exc)}
+ except Exception as exc:
+ log.exception("link_decisions failed")
+ return {"error": str(exc)}
+
+ # Persist like record_decision / add_relationship do, so the link survives a
+ # server restart. A skipped link (added=False) changed nothing to save.
+ persisted = False
+ kg_path = os.environ.get("SEMANTICA_KG_PATH", "").strip()
+ if added and kg_path:
+ if not is_persistence_safe():
+ _drop_edges(graph, new_edges)
+ return {
+ "error": (
+ "Persistence blocked: the configured SEMANTICA_KG_PATH "
+ "could not be loaded at startup. Restart the server with "
+ "a readable graph file to re-enable persistence."
+ )
+ }
+ try:
+ graph.save_to_file(kg_path)
+ persisted = True
+ except Exception as save_exc:
+ _drop_edges(graph, new_edges)
+ log.exception("save_to_file failed after link_decisions; mutation rolled back")
+ return {"error": f"Mutation rolled back: could not persist graph: {save_exc}"}
return {
"source": source,
"target": target,
"relationship": relationship,
"linked": added,
+ "persisted": persisted,
}
+def _drop_edges(graph, edges) -> None:
+ """Undo add_causal_relationship: drop exactly the given edges."""
+ try:
+ with graph._lock:
+ for edge in edges:
+ graph._drop_edge_from_indexes(edge)
+ # _drop_edge_from_indexes leaves _edge_index alone; without this a
+ # retry of the same link would be treated as a duplicate and skipped
+ graph._edge_index.pop(edge.edge_id, None)
+ except Exception:
+ log.exception("could not roll back link_decisions")
+
+
DECISION_TOOLS = [
{
"name": "record_decision",
diff --git a/tests/test_mcp_decisions_link.py b/tests/test_mcp_decisions_link.py
index 7ea07ae3..c05cb6ac 100644
--- a/tests/test_mcp_decisions_link.py
+++ b/tests/test_mcp_decisions_link.py
@@ -65,7 +65,13 @@ class TestHandleLinkDecisions(unittest.TestCase):
mock_graph.add_causal_relationship.assert_called_once_with("dec_a", "dec_b", "CAUSED")
self.assertEqual(
result,
- {"source": "dec_a", "target": "dec_b", "relationship": "CAUSED", "linked": True},
+ {
+ "source": "dec_a",
+ "target": "dec_b",
+ "relationship": "CAUSED",
+ "linked": True,
+ "persisted": False,
+ },
)
@patch("semantica_mcp.mcp.tools.decisions.get_graph")
diff --git a/tests/test_mcp_package_persistence.py b/tests/test_mcp_package_persistence.py
index 6a602a3e..d0f856ee 100644
--- a/tests/test_mcp_package_persistence.py
+++ b/tests/test_mcp_package_persistence.py
@@ -290,5 +290,115 @@ class TestMCPPackageMutationPersistence(unittest.TestCase):
self.assertEqual(result.get("status"), "added")
+class TestLinkDecisionsPersistence(unittest.TestCase):
+ """#1811: link_decisions must persist like record_decision / add_relationship."""
+
+ def _record(self, label):
+ from semantica_mcp.mcp.tools.decisions import handle_record_decision
+
+ result = handle_record_decision({
+ "category": "link_persistence",
+ "scenario": label,
+ "reasoning": "r",
+ "outcome": "o",
+ "confidence": 0.9,
+ })
+ self.assertNotIn("error", result, result)
+ return result["decision_id"]
+
+ def test_link_survives_a_reload(self):
+ from semantica_mcp.mcp.tools.decisions import handle_link_decisions
+
+ with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
+ path = f.name
+ try:
+ with _IsolatedSession():
+ with patch.dict(os.environ, {"SEMANTICA_KG_PATH": path}):
+ a, b = self._record("A"), self._record("B")
+ result = handle_link_decisions(
+ {"source": a, "target": b, "relationship": "CAUSED"}
+ )
+ self.assertNotIn("error", result, result)
+ self.assertTrue(result["linked"])
+ self.assertTrue(result["persisted"])
+
+ g2 = ContextGraph(advanced_analytics=False)
+ g2.load_from_file(path)
+ chain = g2.get_causal_chain(b, direction="upstream")
+ self.assertIn(a, [d.decision_id for d in chain])
+ finally:
+ os.unlink(path)
+
+ def test_failed_save_rolls_the_link_back(self):
+ from semantica_mcp.mcp.tools.decisions import handle_link_decisions
+
+ with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
+ path = f.name
+ try:
+ with _IsolatedSession():
+ with patch.dict(os.environ, {"SEMANTICA_KG_PATH": path}):
+ a, b = self._record("A"), self._record("B")
+ graph = _session.get_graph()
+ edges_before = len(graph.edges)
+ with patch.object(type(graph), "save_to_file", side_effect=OSError("disk full")):
+ result = handle_link_decisions(
+ {"source": a, "target": b, "relationship": "CAUSED"}
+ )
+ self.assertIn("rolled back", result.get("error", ""))
+ self.assertEqual(len(graph.edges), edges_before)
+ # the same link can be made again once saving works
+ retry = handle_link_decisions(
+ {"source": a, "target": b, "relationship": "CAUSED"}
+ )
+ self.assertTrue(retry["linked"], retry)
+ self.assertTrue(retry["persisted"], retry)
+ finally:
+ os.unlink(path)
+
+ def test_failed_save_keeps_another_callers_link(self):
+ from semantica_mcp.mcp.tools.decisions import handle_link_decisions
+
+ with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
+ path = f.name
+ try:
+ with _IsolatedSession():
+ with patch.dict(os.environ, {"SEMANTICA_KG_PATH": path}):
+ a, b = self._record("A"), self._record("B")
+ c, d = self._record("C"), self._record("D")
+ graph = _session.get_graph()
+
+ def other_caller_links_then_save_fails(*_args, **_kwargs):
+ # another link lands after this call's edge, then the save fails
+ graph.add_causal_relationship(c, d, "CAUSED")
+ raise OSError("disk full")
+
+ with patch.object(
+ type(graph), "save_to_file",
+ side_effect=other_caller_links_then_save_fails,
+ ):
+ result = handle_link_decisions(
+ {"source": a, "target": b, "relationship": "CAUSED"}
+ )
+ self.assertIn("rolled back", result.get("error", ""))
+ pairs = {(e.source_id, e.target_id) for e in graph.edges}
+ self.assertNotIn((a, b), pairs)
+ self.assertIn((c, d), pairs)
+ finally:
+ os.unlink(path)
+
+ def test_no_kg_path_links_without_persisting(self):
+ from semantica_mcp.mcp.tools.decisions import handle_link_decisions
+
+ with _IsolatedSession():
+ env = {k: v for k, v in os.environ.items() if k != "SEMANTICA_KG_PATH"}
+ with patch.dict(os.environ, env, clear=True):
+ a, b = self._record("A"), self._record("B")
+ result = handle_link_decisions(
+ {"source": a, "target": b, "relationship": "CAUSED"}
+ )
+ self.assertTrue(result["linked"])
+ self.assertFalse(result["persisted"])
+
+
if __name__ == "__main__":
unittest.main()