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): validate Markdown graph persistence
Saurabh Meenadec05b907d1d
diff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.pyindex 4adefc77..9d4e73cf 100644--- a/semantica/context/context_graph.py+++ b/semantica/context/context_graph.py@@ -1291,6 +1291,24 @@ class ContextGraph:str(edge["type"]),))+ seen_edge_ids: Set[str] = set()+ duplicate_edge_ids: Set[str] = set()+ for edge in edges:+ edge_id = edge["id"]+ if not isinstance(edge_id, str) or not edge_id.strip():+ raise ValueError(+ "Cannot export ContextGraph: every edge must have a string ID."+ )+ if edge_id in seen_edge_ids:+ duplicate_edge_ids.add(edge_id)+ seen_edge_ids.add(edge_id)+ if duplicate_edge_ids:+ duplicates = ", ".join(+ repr(edge_id) for edge_id in sorted(duplicate_edge_ids)+ )+ raise ValueError(+ f"Cannot export ContextGraph: duplicate edge ID(s): {duplicates}."+ )links = sorted(links_by_id.values(), key=lambda link: str(link.get("link_id", "")))@@ -1783,13 +1801,22 @@ class ContextGraph:) -> Optional[str]:if value is None:return None- if isinstance(value, (date, datetime)):+ if isinstance(value, datetime):+ return _normalize_temporal_input(value)+ if isinstance(value, date):return value.isoformat()if isinstance(value, str) and value.strip():+ try:+ _normalize_temporal_input(value)+ except ValueError as exc:+ raise ValueError(+ f"Invalid Markdown frontmatter in {source}: "+ f"'{field_name}' must be a valid ISO-8601 string."+ ) from excreturn valueraise ValueError(f"Invalid Markdown frontmatter in {source}: "- f"'{field_name}' must be an ISO-8601 string."+ f"'{field_name}' must be a valid ISO-8601 string.")diff --git a/tests/context/test_context_graph_markdown.py b/tests/context/test_context_graph_markdown.pyindex a5e33210..b2cd0c24 100644--- a/tests/context/test_context_graph_markdown.py+++ b/tests/context/test_context_graph_markdown.py@@ -224,6 +224,21 @@ def test_markdown_empty_graph_round_trip(tmp_path):assert restored.edges == []+def test_markdown_export_rejects_duplicate_edge_ids_before_writing(tmp_path):+ graph = ContextGraph(advanced_analytics=False)+ graph.add_node("source", "Note", "Source")+ graph.add_node("target", "Note", "Target")+ graph.add_edge("source", "target", "REFERENCES")+ graph.add_edge("source", "target", "REFERENCES")+ export_path = tmp_path / "graph"++ assert graph.edges[0].edge_id == graph.edges[1].edge_id+ with pytest.raises(ValueError, match=r"duplicate edge ID.*[0-9a-f-]+"):+ graph.save_to_file(export_path, format="markdown")++ assert not export_path.exists()++@pytest.mark.parametrize("corruption, expected_error",[@@ -285,6 +300,38 @@ def test_invalid_markdown_does_not_mutate_existing_graph(assert _normalized_state(target) == before+ ("location", "field_name"),+ [("node", "valid_from"), ("edge", "valid_until")],+)+def test_invalid_markdown_temporal_value_does_not_mutate_existing_graph(+ tmp_path, location, field_name+):+ source, _, _ = _sample_graph()+ export_path = tmp_path / location+ source.save_to_file(export_path, format="markdown")++ if location == "node":+ document_path = _node_file(export_path, "policy/\u6771\u4eac")+ else:+ document_path = export_path / "graph.md"+ frontmatter, body = _read_markdown(document_path)+ if location == "node":+ frontmatter[field_name] = "not-a-date"+ else:+ frontmatter["edges"][0][field_name] = "not-a-date"+ _write_markdown(document_path, frontmatter, body)++ target = ContextGraph(advanced_analytics=False)+ target.add_node("sentinel", "Existing", "Do not replace")+ before = _normalized_state(target)++ with pytest.raises(ValueError, match=rf"'{field_name}'.*valid ISO-8601"):+ target.load_from_file(export_path, format="markdown")++ assert _normalized_state(target) == before++def test_duplicate_yaml_keys_are_rejected(tmp_path):graph = ContextGraph(advanced_analytics=False)graph.add_node("node-1", "Note", "Body")