Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix: JenaStore remote endpoint uses SPARQLUpdateStore instead of read-only SPARQLStore

Sameer630510e26cb5704c
diff --git a/semantica/triplet_store/jena_store.py b/semantica/triplet_store/jena_store.py
index b994343d..c1cd691e 100644
--- a/semantica/triplet_store/jena_store.py
+++ b/semantica/triplet_store/jena_store.py
@@ -37,7 +37,7 @@ from . import sparql_escaping
# Optional Jena imports
try:
from rdflib import RDF, Graph, Literal, Namespace, URIRef
- from rdflib.plugins.stores.sparqlstore import SPARQLStore
+ from rdflib.plugins.stores.sparqlstore import SPARQLStore, SPARQLUpdateStore
HAS_JENA_RDFLIB = True
except (ImportError, OSError):
@@ -69,7 +69,7 @@ class JenaStore:
if not self.progress_tracker.enabled:
self.progress_tracker.enabled = True
- self.endpoint = config.get("endpoint")
+ self.endpoint = endpoint or config.get("endpoint")
self.dataset = config.get("dataset", "default")
self.enable_inference = config.get("enable_inference", False)
@@ -81,15 +81,38 @@ class JenaStore:
return bool(sparql_escaping.CONSTRUCT_QUERY_RE.search(query))
def _initialize_graph(self) -> None:
- """Initialize RDF graph."""
+ """Initialize RDF graph.
+
+ 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:
+
+ query_endpoint = <endpoint>/query
+ update_endpoint = <endpoint>/update
+
+ These match the default service names shipped with every Apache Jena
+ Fuseki dataset (configurable per-deployment, but correct for the
+ canonical out-of-the-box setup).
+ """
if HAS_JENA_RDFLIB:
if self.endpoint:
- # Use SPARQL store for remote endpoint
+ # Use SPARQLUpdateStore so that .add() issues SPARQL INSERT DATA
+ # requests against the Fuseki update endpoint. The read-only
+ # SPARQLStore was previously used here, which caused every
+ # add_triplets() call to silently fail with TypeError.
+ base = self.endpoint.rstrip("/")
+ query_endpoint = f"{base}/query"
+ update_endpoint = f"{base}/update"
try:
- store = SPARQLStore(query_endpoint=self.endpoint)
+ store = SPARQLUpdateStore(
+ query_endpoint=query_endpoint,
+ update_endpoint=update_endpoint,
+ autocommit=True,
+ )
self.graph = Graph(store=store)
except Exception as e:
- self.logger.warning(f"Could not initialize SPARQL store: {e}")
+ self.logger.warning(f"Could not initialize SPARQL update store: {e}")
self.graph = Graph()
else:
# Use in-memory graph
@@ -159,8 +182,22 @@ class JenaStore:
self.graph.add((subject, predicate, obj))
added_count += 1
- except Exception as e:
- self.logger.warning(f"Failed to add triplet: {e}")
+ except (ValueError, AttributeError) as e:
+ # Skip individual malformed triplets (bad URI / missing
+ # field) but let store-level errors (e.g. network failure,
+ # read-only store, authentication error) propagate so they
+ # are not silently swallowed as per-triplet warnings.
+ self.logger.warning(f"Skipping malformed triplet: {e}")
+
+ if triplets and added_count == 0:
+ # Every single triplet failed. This almost certainly indicates
+ # a store-level problem (wrong endpoint, auth failure, etc.)
+ # rather than N bad triplets, so we raise instead of returning
+ # a misleading success=True/added=0.
+ raise ProcessingError(
+ f"Failed to add any of the {len(triplets)} triplet(s). "
+ "Check store connectivity and endpoint configuration."
+ )
self.progress_tracker.stop_tracking(
tracking_id,
diff --git a/tests/triplet_store/test_jena_store.py b/tests/triplet_store/test_jena_store.py
index c8021a2e..afe99321 100644
--- a/tests/triplet_store/test_jena_store.py
+++ b/tests/triplet_store/test_jena_store.py
@@ -120,5 +120,172 @@ class TestExecuteConstructTemplateWithJenaBackend(unittest.TestCase):
self.assertEqual(triplet.object, 'true')
self.assertEqual(triplet.metadata.get('datatype'), 'http://www.w3.org/2001/XMLSchema#boolean')
+class TestJenaStoreRemoteEndpointUsesUpdateStore(unittest.TestCase):
+ """
+ Tests for the SPARQLStore → SPARQLUpdateStore fix.
+
+ Bug: _initialize_graph bound a read-only SPARQLStore for remote endpoints,
+ causing every add_triplets() call to silently fail (TypeError swallowed,
+ success=True/added=0 returned).
+
+ Fix: SPARQLUpdateStore is now used, configured with both
+ query_endpoint (<base>/query) and update_endpoint (<base>/update)
+ per standard Apache Jena Fuseki REST API conventions.
+ """
+
+ _BASE = "http://localhost:3030/ds"
+
+ # ------------------------------------------------------------------
+ # Helpers
+ # ------------------------------------------------------------------
+
+ def _make_remote_store(self):
+ """Return a JenaStore wired to a fake remote endpoint."""
+ from rdflib.plugins.stores.sparqlstore import SPARQLUpdateStore
+
+ with patch(
+ "semantica.triplet_store.jena_store.SPARQLUpdateStore",
+ ) as MockUpdateStore:
+ # SPARQLUpdateStore.__init__ would normally try to contact the
+ # server; the mock prevents any network I/O during init.
+ mock_store_instance = MagicMock(spec=SPARQLUpdateStore)
+ MockUpdateStore.return_value = mock_store_instance
+
+ with patch("semantica.triplet_store.jena_store.Graph") as MockGraph:
+ mock_graph_instance = MagicMock(spec=Graph)
+ MockGraph.return_value = mock_graph_instance
+
+ store = JenaStore(endpoint=self._BASE)
+ return store, MockUpdateStore, MockGraph, mock_graph_instance
+
+ # ------------------------------------------------------------------
+ # Test 1 – correct class is instantiated
+ # ------------------------------------------------------------------
+
+ def test_remote_endpoint_instantiates_sparql_update_store_not_sparql_store(self):
+ """
+ _initialize_graph must use SPARQLUpdateStore, never the read-only SPARQLStore.
+ """
+ from rdflib.plugins.stores.sparqlstore import SPARQLUpdateStore
+
+ with patch(
+ "semantica.triplet_store.jena_store.SPARQLUpdateStore"
+ ) as MockUpdateStore, patch(
+ "semantica.triplet_store.jena_store.SPARQLStore"
+ ) as MockReadOnlyStore:
+ MockUpdateStore.return_value = MagicMock()
+ with patch("semantica.triplet_store.jena_store.Graph"):
+ JenaStore(endpoint=self._BASE)
+
+ MockUpdateStore.assert_called_once()
+ MockReadOnlyStore.assert_not_called()
+
+ # ------------------------------------------------------------------
+ # Test 2 – correct Fuseki sub-paths are derived from base URL
+ # ------------------------------------------------------------------
+
+ def test_remote_endpoint_derives_fuseki_query_and_update_sub_paths(self):
+ """
+ Standard Fuseki datasets expose /query and /update under the dataset
+ base URL. The store must pass both to SPARQLUpdateStore.
+ """
+ with patch(
+ "semantica.triplet_store.jena_store.SPARQLUpdateStore"
+ ) as MockUpdateStore, patch("semantica.triplet_store.jena_store.Graph"):
+ MockUpdateStore.return_value = MagicMock()
+
+ JenaStore(endpoint=self._BASE)
+
+ call_kwargs = MockUpdateStore.call_args
+ # Accept both positional and keyword argument forms
+ args, kwargs = call_kwargs
+ passed = {**kwargs}
+ if len(args) >= 1:
+ passed.setdefault("query_endpoint", args[0])
+ if len(args) >= 2:
+ passed.setdefault("update_endpoint", args[1])
+
+ self.assertEqual(
+ passed.get("query_endpoint"),
+ "http://localhost:3030/ds/query",
+ "query_endpoint must be <base>/query",
+ )
+ self.assertEqual(
+ passed.get("update_endpoint"),
+ "http://localhost:3030/ds/update",
+ "update_endpoint must be <base>/update",
+ )
+
+ def test_remote_endpoint_trailing_slash_is_normalised(self):
+ """A trailing slash on the supplied endpoint must not produce double-slashes."""
+ with patch(
+ "semantica.triplet_store.jena_store.SPARQLUpdateStore"
+ ) as MockUpdateStore, patch("semantica.triplet_store.jena_store.Graph"):
+ MockUpdateStore.return_value = MagicMock()
+
+ JenaStore(endpoint="http://localhost:3030/ds/")
+
+ _, kwargs = MockUpdateStore.call_args
+ self.assertNotIn(
+ "//query",
+ kwargs.get("query_endpoint", ""),
+ "Trailing slash must be stripped before appending /query",
+ )
+ self.assertEqual(kwargs.get("query_endpoint"), "http://localhost:3030/ds/query")
+ self.assertEqual(kwargs.get("update_endpoint"), "http://localhost:3030/ds/update")
+
+ # ------------------------------------------------------------------
+ # Test 3 – end-to-end write path: add_triplets fires INSERT DATA POST
+ # ------------------------------------------------------------------
+
+ def test_add_triplets_remote_endpoint_fires_insert_data_via_update_store(self):
+ """
+ End-to-end mock: add_triplets() against a remote-endpoint JenaStore must
+ call graph.add() (which SPARQLUpdateStore maps to INSERT DATA). We verify
+ that graph.add() is actually invoked with the correct (subject, predicate,
+ object) triple and that add_triplets returns success=True/added=1.
+
+ 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.
+ """
+ triplet = Triplet(
+ subject="http://example.org/Alice",
+ predicate="http://example.org/knows",
+ object="http://example.org/Bob",
+ )
+
+ with patch(
+ "semantica.triplet_store.jena_store.SPARQLUpdateStore"
+ ) as MockUpdateStore, patch(
+ "semantica.triplet_store.jena_store.Graph"
+ ) as MockGraph:
+ 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
+
+ store = JenaStore(endpoint=self._BASE)
+ result = store.add_triplets([triplet])
+
+ # add_triplets must report success
+ self.assertTrue(result["success"])
+ 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(
+ (
+ URIRef("http://example.org/Alice"),
+ URIRef("http://example.org/knows"),
+ URIRef("http://example.org/Bob"),
+ )
+ )
+
+
if __name__ == "__main__":
unittest.main()