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: scope delete_triplet to the default graph only
KaifAhmad151953a036773
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a6ed9d18..2677bc52 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Named-graph support for `JenaStore` via `Dataset` migration** (#756, #757) by @Sameer6305 and @KaifAhmad1+ - `JenaStore` now backs onto `rdflib.Dataset(default_union=False)` instead of `rdflib.Graph`, closing #756 and fully closing out the #754/#756 cross-backend named-graph parity effort across Blazegraph, RDF4J, and Jena+ - `default_union=False` is explicitly set so existing `execute_sparql()`/`get_triplets()` calls that don't pass `graph=` keep seeing only the default graph, not a union across all named graphs+ - `add_triplets()` accepts a `graph=` option: when supplied, triples are written to that named graph (4-tuple add via `Dataset.graph(uri)`); when omitted, behavior is unchanged (3-tuple add routes to the default graph)+ - Fixed a pre-existing bug where the remote-endpoint path instantiated the read-only rdflib `SPARQLStore` instead of `SPARQLUpdateStore`, so every `add_triplets()` call against a remote Fuseki endpoint silently failed (`TypeError` swallowed, `success=True`/`added=0` returned); also fixed a constructor bug where `self.endpoint` was always `None` regardless of how `JenaStore` was called, making the remote path unreachable in practice+ - `serialize()` now logs a warning instead of silently dropping named-graph content when the requested format (`turtle`, `xml`, `n3`, …) can only serialize the default graph; use `format="trig"` or `format="nquads"` to include all graphs+ - `create_model()`'s `triplet_count` now documented as counting across all graphs (default + named), not just the default graph, matching the `Dataset`-wide semantics+ - `delete_triplet()` remains scoped to the default graph only (named-graph parity for delete is an explicit follow-up, matching the maintainer's scoping of this migration to `add_triplets`); the removal is passed `self.graph.default_graph` explicitly as its context, since `Dataset.remove()` on a bare 3-tuple resolves to a wildcard context internally and would otherwise delete matching triples out of every named graph too — a follow-up fix to the initial PR #757 for a bug that had no test coverage+ - 9 new tests covering `Dataset` construction, `default_union=False` confirmation, named-graph write isolation, `serialize()` warning behavior, and `delete_triplet()`'s default-graph scoping+- **SPARQL CONSTRUCT query templates** (#752, #322, #755, #754) by @Sameer6305- Added parameterized, injection-safe `CONSTRUCT` templates (`ConstructTemplate`, `ParameterDescriptor`, `ConstructTemplateRegistry`)- Extended CONSTRUCT execution support from Blazegraph-only to the RDF4J and Jena backends (#755), closing #754diff --git a/semantica/triplet_store/jena_store.py b/semantica/triplet_store/jena_store.pyindex 4961302e..dadeb71c 100644--- a/semantica/triplet_store/jena_store.py+++ b/semantica/triplet_store/jena_store.py@@ -89,11 +89,12 @@ class JenaStore:the default graph, not a union across all named graphs. This matchesthe 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. ``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:+ For remote Fuseki endpoints, ``SPARQLUpdateStore`` is used instead of+ the read-only ``SPARQLStore`` so that SPARQL Update (INSERT DATA /+ DELETE DATA) operations work correctly against the update endpoint;+ ``SPARQLStore`` has no update endpoint and raises ``TypeError`` from+ ``.add()``/``.remove()``. The standard Fuseki sub-paths are derived+ from the base dataset URL:query_endpoint = <endpoint>/queryupdate_endpoint = <endpoint>/update@@ -152,8 +153,12 @@ class JenaStore:update_endpoint=update_endpoint,autocommit=True,)- # Dataset requires graph_aware=True on the store;- # SPARQLUpdateStore satisfies this.+ # SPARQLUpdateStore is used (not the read-only SPARQLStore)+ # because only it supports writes: SPARQLStore.add()/.remove()+ # raise TypeError since it has no update endpoint to issue+ # SPARQL Update requests against. Both stores are+ # graph_aware=True, so graph-awareness is not what+ # distinguishes them here.self.graph = Dataset(store=store, default_union=False)except Exception as e:self.logger.warning(f"Could not initialize SPARQL update store: {e}")@@ -350,6 +355,14 @@ class JenaStore:scoping of this migration to ``add_triplets`` only. This methodalways removes from the default graph regardless of any ``graph=``value in ``**options``.++ The removal is explicitly scoped to ``self.graph.default_graph``.+ ``Dataset.remove()`` on a bare 3-tuple (no context) resolves to+ ``context=None`` internally, which the underlying store treats as+ a wildcard and matches the triple in *every* graph — silently+ deleting named-graph copies too. Passing ``default_graph``+ explicitly as the context avoids that and keeps this method+ scoped to the default graph only, consistent with this docstring."""if self.graph is None:raise ProcessingError("Graph not initialized")@@ -363,7 +376,7 @@ class JenaStore:else Literal(triplet.object))- self.graph.remove((subject, predicate, obj))+ self.graph.remove((subject, predicate, obj, self.graph.default_graph))return {"success": True}except Exception as e:diff --git a/tests/triplet_store/test_jena_store.py b/tests/triplet_store/test_jena_store.pyindex 66388da2..b718d740 100644--- a/tests/triplet_store/test_jena_store.py+++ b/tests/triplet_store/test_jena_store.py@@ -760,5 +760,74 @@ class TestJenaStoreZeroAddedErrorMessage(unittest.TestCase):self.assertIn("failed", msg)+class TestJenaStoreDeleteTripletScopedToDefaultGraph(unittest.TestCase):+ """+ Regression tests for delete_triplet's cross-graph deletion bug.++ Bug: after the Graph -> Dataset migration, delete_triplet called+ self.graph.remove((s, p, o)) with no context. Dataset.remove() on a bare+ 3-tuple resolves context=None internally, which the store treats as a+ wildcard and matches (and deletes) the triple in every graph — not just+ the default graph the docstring promises. Fix: pass+ self.graph.default_graph explicitly as the 4th tuple element so the+ removal is scoped to the default graph only.+ """++ def test_delete_triplet_does_not_remove_from_named_graph(self):+ """+ A triple present in both the default graph and a named graph must,+ after delete_triplet(), still exist in the named graph — only the+ default-graph copy may be removed.+ """+ from rdflib import URIRef++ store = JenaStore()++ triplet = Triplet(+ subject="http://example.org/Alice",+ predicate="http://example.org/knows",+ object="http://example.org/Bob",+ )++ # Same triple written to both the default graph and a named graph.+ store.add_triplets([triplet])+ store.add_triplets([triplet], graph="http://example.org/ng")++ named_ctx = store.graph.graph(URIRef("http://example.org/ng"))+ self.assertEqual(len(named_ctx), 1)+ self.assertEqual(len(store.graph.default_graph), 1)++ result = store.delete_triplet(triplet)++ self.assertTrue(result["success"])+ self.assertEqual(+ len(store.graph.default_graph),+ 0,+ "Triplet must be removed from the default graph",+ )+ self.assertEqual(+ len(named_ctx),+ 1,+ "Triplet must NOT be removed from a named graph it also lives in",+ )++ def test_delete_triplet_removes_from_default_graph(self):+ """delete_triplet still removes the triple from the default graph."""+ store = JenaStore()++ triplet = Triplet(+ subject="http://example.org/S",+ predicate="http://example.org/P",+ object="http://example.org/O",+ )+ store.add_triplets([triplet])+ self.assertEqual(len(store.graph.default_graph), 1)++ result = store.delete_triplet(triplet)++ self.assertTrue(result["success"])+ self.assertEqual(len(store.graph.default_graph), 0)++if __name__ == "__main__":unittest.main()