Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: migrate JenaStore from Graph to Dataset(default_union=False) for named-graph support

Sameer6305a9559a6d7a0e
diff --git a/semantica/triplet_store/jena_store.py b/semantica/triplet_store/jena_store.py
index c1cd691e..44e6cf37 100644
--- a/semantica/triplet_store/jena_store.py
+++ b/semantica/triplet_store/jena_store.py
@@ -36,7 +36,7 @@ from . import sparql_escaping
# Optional Jena imports
try:
- from rdflib import RDF, Graph, Literal, Namespace, URIRef
+ from rdflib import RDF, Dataset, Graph, Literal, Namespace, URIRef
from rdflib.plugins.stores.sparqlstore import SPARQLStore, SPARQLUpdateStore
HAS_JENA_RDFLIB = True
@@ -73,7 +73,7 @@ class JenaStore:
self.dataset = config.get("dataset", "default")
self.enable_inference = config.get("enable_inference", False)
- self.graph: Optional[Graph] = None
+ self.graph: Optional[Dataset] = None
self._initialize_graph()
def _is_construct_query(self, query: str) -> bool:
@@ -81,12 +81,19 @@ class JenaStore:
return bool(sparql_escaping.CONSTRUCT_QUERY_RE.search(query))
def _initialize_graph(self) -> None:
- """Initialize RDF graph.
+ """Initialize the backing store as a ``Dataset`` with ``default_union=False``.
+
+ ``Dataset`` is used instead of ``Graph`` to support named graphs.
+ ``default_union=False`` is set explicitly so that SPARQL queries and
+ ``get_triplets()`` calls that do not specify a named graph see **only**
+ the default graph, not a union across all named graphs. This matches
+ the maintainer-confirmed architecture for this migration.
For remote Fuseki endpoints, ``SPARQLUpdateStore`` is used so that
both queries and SPARQL Update (INSERT DATA / DELETE DATA) operations
- work correctly. The standard Fuseki sub-paths are derived from the
- base dataset URL:
+ work correctly. ``SPARQLUpdateStore.graph_aware = True``, satisfying
+ ``Dataset``'s hard requirement that the backing store be graph-aware.
+ The standard Fuseki sub-paths are derived from the base dataset URL:
query_endpoint = <endpoint>/query
update_endpoint = <endpoint>/update
@@ -110,13 +117,16 @@ class JenaStore:
update_endpoint=update_endpoint,
autocommit=True,
)
- self.graph = Graph(store=store)
+ # Dataset requires graph_aware=True on the store;
+ # SPARQLUpdateStore satisfies this.
+ self.graph = Dataset(store=store, default_union=False)
except Exception as e:
self.logger.warning(f"Could not initialize SPARQL update store: {e}")
- self.graph = Graph()
+ self.graph = Dataset(default_union=False)
else:
- # Use in-memory graph
- self.graph = Graph()
+ # In-memory Dataset; default_union=False keeps queries scoped
+ # to the default graph unless a named graph is specified.
+ self.graph = Dataset(default_union=False)
else:
self.logger.warning(
"rdflib not available. Jena store will use basic operations."
@@ -131,7 +141,12 @@ class JenaStore:
**options: Model options
Returns:
- Model information
+ Model information dict with keys:
+ - ``model_id``: dataset name
+ - ``endpoint``: remote endpoint URL if configured, else None
+ - ``triplet_count``: total triples across **all** graphs (default
+ graph + any named graphs). As of the Dataset migration this
+ counts the full dataset, not just the default graph.
"""
if self.graph is None:
self._initialize_graph()
@@ -148,7 +163,14 @@ class JenaStore:
Args:
triplets: List of triplets
- **options: Additional options
+ **options: Additional options. Recognised keys:
+
+ ``graph`` (str | None):
+ Named-graph URI. When supplied, triples are written to
+ that named graph inside the Dataset (4-tuple add). When
+ omitted or ``None``, triples are written to the **default
+ graph** (3-tuple add) — preserving the pre-migration
+ single-Graph semantics exactly.
Returns:
Operation status
@@ -170,6 +192,16 @@ class JenaStore:
self.progress_tracker.update_tracking(
tracking_id, message="Adding triplets to graph..."
)
+
+ # Resolve named-graph context once before the per-triplet loop.
+ # Dataset.graph(uri) returns an existing Graph for that URI or
+ # creates a new empty one — safe to call even if the graph already
+ # exists.
+ graph_uri = options.get("graph")
+ context: Optional[Graph] = None
+ if graph_uri is not None:
+ context = self.graph.graph(URIRef(str(graph_uri)))
+
for triplet in triplets:
try:
subject = URIRef(triplet.subject)
@@ -180,7 +212,15 @@ class JenaStore:
else Literal(triplet.object)
)
- self.graph.add((subject, predicate, obj))
+ if context is not None:
+ # 4-tuple: routes triple to the named graph context.
+ # SPARQLUpdateStore translates this to:
+ # INSERT DATA { GRAPH <uri> { s p o . } }
+ self.graph.add((subject, predicate, obj, context))
+ else:
+ # 3-tuple: Dataset.add() routes to the default graph.
+ # Semantically identical to the pre-migration Graph.add().
+ self.graph.add((subject, predicate, obj))
added_count += 1
except (ValueError, AttributeError) as e:
# Skip individual malformed triplets (bad URI / missing
@@ -259,7 +299,15 @@ class JenaStore:
return []
def delete_triplet(self, triplet: Triplet, **options) -> Dict[str, Any]:
- """Delete triplet."""
+ """Delete triplet from the default graph.
+
+ Note:
+ Named-graph parity (a ``graph=`` option mirroring ``add_triplets``)
+ is a known gap deferred to a future follow-up, per the maintainer's
+ scoping of this migration to ``add_triplets`` only. This method
+ always removes from the default graph regardless of any ``graph=``
+ value in ``**options``.
+ """
if self.graph is None:
raise ProcessingError("Graph not initialized")
@@ -397,11 +445,33 @@ class JenaStore:
Returns:
Serialized RDF string
+
+ Note:
+ Single-graph serializers (``"turtle"``, ``"xml"``, ``"n3"``)
+ serialize **only the default graph**. Triples stored in named
+ graphs are silently omitted. Use ``format="trig"`` or
+ ``format="nquads"`` to capture all named graphs. A WARNING is
+ logged whenever named-graph content would be dropped by the
+ chosen format.
"""
if self.graph is None:
return ""
try:
+ # Warn when named-graph triples exist and would be silently dropped
+ # by a single-graph serializer. len(Dataset) counts all graphs;
+ # len(Dataset.default_graph) counts only the default graph.
+ # Any positive difference means named-graph content is present.
+ default_count = len(self.graph.default_graph)
+ total_count = len(self.graph)
+ if total_count > default_count:
+ self.logger.warning(
+ "serialize(format=%r) serializes only the default graph. "
+ "%d named-graph triple(s) will be omitted. "
+ "Use format='trig' or 'nquads' to include all graphs.",
+ format,
+ total_count - default_count,
+ )
return self.graph.serialize(format=format)
except Exception as e:
self.logger.error(f"Serialization failed: {e}")
diff --git a/tests/triplet_store/test_jena_store.py b/tests/triplet_store/test_jena_store.py
index afe99321..61e3c319 100644
--- a/tests/triplet_store/test_jena_store.py
+++ b/tests/triplet_store/test_jena_store.py
@@ -248,7 +248,12 @@ class TestJenaStoreRemoteEndpointUsesUpdateStore(unittest.TestCase):
This is distinct from the class-instantiation tests above: it confirms
the write path works all the way through add_triplets(), not just that
the right class gets constructed.
+
+ After the Dataset migration the remote path creates Dataset(store=...),
+ so we patch Dataset rather than Graph to intercept the construction.
"""
+ from rdflib import Dataset, URIRef
+
triplet = Triplet(
subject="http://example.org/Alice",
predicate="http://example.org/knows",
@@ -258,15 +263,17 @@ class TestJenaStoreRemoteEndpointUsesUpdateStore(unittest.TestCase):
with patch(
"semantica.triplet_store.jena_store.SPARQLUpdateStore"
) as MockUpdateStore, patch(
- "semantica.triplet_store.jena_store.Graph"
- ) as MockGraph:
+ "semantica.triplet_store.jena_store.Dataset"
+ ) as MockDataset:
mock_store_instance = MagicMock()
MockUpdateStore.return_value = mock_store_instance
- mock_graph_instance = MagicMock(spec=Graph)
- # graph.add() must not raise – simulate a successful INSERT DATA
- mock_graph_instance.add.return_value = None
- MockGraph.return_value = mock_graph_instance
+ mock_dataset_instance = MagicMock(spec=Dataset)
+ # graph.add() must not raise — simulate a successful INSERT DATA
+ mock_dataset_instance.add.return_value = None
+ # graph.graph() is called to resolve named-graph context when graph=
+ # is supplied. It is NOT called in this test (no graph= option).
+ MockDataset.return_value = mock_dataset_instance
store = JenaStore(endpoint=self._BASE)
result = store.add_triplets([triplet])
@@ -276,9 +283,9 @@ class TestJenaStoreRemoteEndpointUsesUpdateStore(unittest.TestCase):
self.assertEqual(result["added"], 1)
self.assertEqual(result["total"], 1)
- # graph.add() must have been called exactly once with the right triple
- from rdflib import URIRef
- mock_graph_instance.add.assert_called_once_with(
+ # graph.add() must have been called exactly once with the 3-tuple
+ # (no graph= option → default graph path → 3-tuple, no context arg)
+ mock_dataset_instance.add.assert_called_once_with(
(
URIRef("http://example.org/Alice"),
URIRef("http://example.org/knows"),
@@ -287,5 +294,222 @@ class TestJenaStoreRemoteEndpointUsesUpdateStore(unittest.TestCase):
)
+class TestJenaStoreDatasetMigration(unittest.TestCase):
+ """
+ Tests confirming the Graph → Dataset(default_union=False) migration.
+
+ These tests specifically exercise _initialize_graph's real, unmodified
+ path (no store.graph injection) to confirm the migration is in effect —
+ unlike the existing test classes, which inject a plain Graph() directly
+ and therefore don't exercise the initialization path at all.
+ """
+
+ # ------------------------------------------------------------------
+ # Test 1 — unmodified _initialize_graph produces Dataset, not Graph
+ # ------------------------------------------------------------------
+
+ def test_initialize_graph_produces_dataset_not_graph(self):
+ """
+ The in-memory path of _initialize_graph must produce a Dataset instance,
+ not a plain Graph. This is the direct regression guard for the migration:
+ if someone reverts the Dataset construction back to Graph() this test fails.
+ """
+ from rdflib import Dataset
+
+ store = JenaStore() # no endpoint → in-memory path
+
+ self.assertIsInstance(
+ store.graph,
+ Dataset,
+ "_initialize_graph must produce a Dataset, not a Graph",
+ )
+
+ def test_initialize_graph_dataset_has_default_union_false(self):
+ """
+ default_union must be explicitly False so that queries without a named
+ graph scope see only the default graph, not a union across all graphs.
+ """
+ from rdflib import Dataset
+
+ store = JenaStore()
+
+ self.assertIsInstance(store.graph, Dataset)
+ self.assertFalse(
+ store.graph.default_union,
+ "Dataset.default_union must be False (named-graph isolation)",
+ )
+
+ # ------------------------------------------------------------------
+ # Test 2 — add_triplets with graph= writes to named graph, not default
+ # ------------------------------------------------------------------
+
+ def test_add_triplets_with_graph_option_writes_to_named_graph(self):
+ """
+ add_triplets(triplets, graph="http://example.org/g") must write triples
+ to the specified named graph, not to the default graph.
+ """
+ from rdflib import Dataset, URIRef
+
+ store = JenaStore()
+ self.assertIsInstance(store.graph, Dataset)
+
+ named_graph_uri = "http://example.org/named-graph"
+ triplet = Triplet(
+ subject="http://example.org/Alice",
+ predicate="http://example.org/knows",
+ object="http://example.org/Bob",
+ )
+
+ result = store.add_triplets([triplet], graph=named_graph_uri)
+
+ self.assertTrue(result["success"])
+ self.assertEqual(result["added"], 1)
+
+ # Confirm the named graph now contains the triple
+ named_ctx = store.graph.graph(URIRef(named_graph_uri))
+ self.assertEqual(len(named_ctx), 1, "Named graph must hold the added triple")
+
+ # Confirm the default graph does NOT contain it
+ self.assertEqual(
+ len(store.graph.default_graph),
+ 0,
+ "Default graph must be empty when graph= option is used",
+ )
+
+ def test_add_triplets_without_graph_option_writes_to_default_graph(self):
+ """
+ When graph= is omitted (the common path), triples must go to the default
+ graph — preserving pre-migration semantics exactly.
+ """
+ from rdflib import Dataset, URIRef
+
+ store = JenaStore()
+
+ triplet = Triplet(
+ subject="http://example.org/Alice",
+ predicate="http://example.org/knows",
+ object="http://example.org/Bob",
+ )
+
+ result = store.add_triplets([triplet]) # no graph= option
+
+ self.assertTrue(result["success"])
+ self.assertEqual(result["added"], 1)
+
+ # Triple is in the default graph
+ self.assertEqual(
+ len(store.graph.default_graph),
+ 1,
+ "Triple without graph= must go to the default graph",
+ )
+
+ def test_add_triplets_named_graph_isolated_from_default_query(self):
+ """
+ A triple added to a named graph must NOT appear in a plain SELECT query
+ (which, with default_union=False, sees only the default graph).
+ This confirms the isolation guarantee end-to-end.
+ """
+ from rdflib import URIRef
+
+ store = JenaStore()
+
+ # Add to named graph
+ store.add_triplets(
+ [Triplet(
+ subject="http://example.org/Named",
+ predicate="http://example.org/type",
+ object="http://example.org/Thing",
+ )],
+ graph="http://example.org/isolated",
+ )
+
+ # Also add to default graph so we can confirm query returns that one
+ store.add_triplets([
+ Triplet(
+ subject="http://example.org/Default",
+ predicate="http://example.org/type",
+ object="http://example.org/Other",
+ )
+ ])
+
+ # Plain SPARQL query (no FROM / GRAPH clause) should see only default
+ result = store.execute_sparql("SELECT ?s WHERE { ?s ?p ?o }")
+ subjects = [b["s"]["value"] for b in result["bindings"]]
+
+ self.assertIn("http://example.org/Default", subjects)
+ self.assertNotIn(
+ "http://example.org/Named",
+ subjects,
+ "Named-graph triple must not appear in a default-graph-scoped query",
+ )
+
+ # ------------------------------------------------------------------
+ # Test 3 — serialize() logs a warning when named-graph content is present
+ # ------------------------------------------------------------------
+
+ def test_serialize_logs_warning_when_named_graph_content_present(self):
+ """
+ serialize(format='turtle') serializes only the default graph. When
+ named-graph triples are also present, a WARNING must be logged so the
+ data loss is not silent.
+ """
+ from unittest.mock import patch
+
+ store = JenaStore()
+
+ # Put one triple in each location
+ store.add_triplets([
+ Triplet(
+ subject="http://example.org/S",
+ predicate="http://example.org/P",
+ object="default_val",
+ )
+ ])
+ store.add_triplets(
+ [Triplet(
+ subject="http://example.org/S2",
+ predicate="http://example.org/P",
+ object="named_val",
+ )],
+ graph="http://example.org/ng",
+ )
+
+ with patch.object(store.logger, "warning") as mock_warn:
+ output = store.serialize(format="turtle")
+
+ # serialize must have returned something (the default graph)
+ self.assertIsInstance(output, str)
+ self.assertIn("default_val", output)
+ self.assertNotIn("named_val", output)
+
+ # Warning must have been logged
+ mock_warn.assert_called_once()
+ warn_msg = mock_warn.call_args[0][0]
+ self.assertIn("named-graph", warn_msg.lower().replace("-", "-"))
+ self.assertIn("trig", warn_msg.lower())
+
+ def test_serialize_no_warning_when_only_default_graph_used(self):
+ """
+ serialize() must NOT log a warning when no named-graph content exists —
+ this avoids noise for the common case where named graphs are not used.
+ """
+ from unittest.mock import patch
+
+ store = JenaStore()
+ store.add_triplets([
+ Triplet(
+ subject="http://example.org/S",
+ predicate="http://example.org/P",
+ object="default_only",
+ )
+ ])
+
+ with patch.object(store.logger, "warning") as mock_warn:
+ output = store.serialize(format="turtle")
+
+ self.assertIn("default_only", output)
+ mock_warn.assert_not_called()
+
+
if __name__ == "__main__":
unittest.main()