Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

test(provenance): expand storage failure regression coverage (#785)

Sameer6305aae4c946ea1b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 389779fc..3651e4c4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -106,6 +106,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Follow-up fix**: `track_entity()`/`track_chunk()` caught all internal storage exceptions unconditionally, so when called from `track_entities_batch()`/`track_chunks_batch()`'s shared per-block transaction, a single item's storage failure (e.g. non-JSON-serializable metadata) was swallowed inside the call and never surfaced to the batch loop's per-item `except`, inflating `tracked_count` for entries that were never persisted. Both methods now re-raise when invoked with a shared `_conn` (batch context) while still degrading gracefully on standalone calls, so batch counts match what's actually committed
- Added 8 dedicated regression tests in `tests/provenance/test_sqlite_storage_performance_807.py` covering PRAGMA configuration, Windows unlink safety, batch transaction sharing, BFS `max_depth`, rollback count accuracy, custom storage backward compatibility, concurrent read-modify-write serialization, and connection cleanup guards on configuration error
+- **Closed remaining `ProvenanceManager` storage-failure test-coverage gaps identified by a #785 audit** (#785)
+ - An audit of `tests/provenance/` (filed against a claim that zero tests exercised `storage.store()` failures) found #782/#783/#784/#807 had already closed most of the gap, but two residual surfaces had no test: `track_relationship()`, `track_chunk()`, and `track_property_source()`'s storage-failure-swallowing contract (returns `None`, logs, persists nothing) was only verified against `InMemoryStorage`, never `SQLiteStorage`; and `track_chunks_batch()` had no test for per-item `_save_entry` failure logging or for the block-level transaction-failure log message, even though `track_entities_batch()` had both
+ - No production code changed — #782/#783/#784/#807 already implemented the correct behavior; this closes the coverage gap proving it holds on both backends
+ - Added `test_track_relationship_storage_error_swallowed_sqlite`, `test_track_chunk_storage_error_swallowed_sqlite`, `test_track_property_source_storage_error_swallowed_sqlite`, `test_chunks_batch_logs_per_item_failure_memory`, and `test_track_chunks_batch_block_level_transaction_failure_logs` to `tests/provenance/test_manager.py`
+ - Read-path failure coverage (`get_lineage()`/`trace_lineage()`/`get_provenance()`/`clear()` propagating a raised storage exception) remains untested and is a candidate for a follow-up issue, since none of those methods currently wrap the underlying storage call in a try/except
+
- **Explorer's Provenance UI used a naive 2-hop graph traversal instead of the audit-grade `ProvenanceManager` backend** (#792, #809) by @Sameer6305
- `semantica/explorer/routes/provenance.py` never imported or called `ProvenanceManager` (`semantica/provenance/manager.py`); `/api/provenance` and `/api/provenance/report` built their lineage response entirely from a naive 2-hop networkx traversal over the live graph instead of querying the SQLite-backed, checksummed audit log. Both endpoints now query `session.provenance_manager.get_lineage(node_id)` first, and a new `_transform_audit_lineage()` maps the W3C PROV-O entries into the exact `{"nodes": [...], "edges": [...]}` shape `LineageDiagram.tsx` already expects — no frontend changes required
- Falls back to the original 2-hop traversal, never a 500: no audit records for a node, a `ProvenanceManager` storage failure (corrupted DB, permissions), or a failed SHA-256 integrity check on any entry in the lineage chain all degrade cleanly to the naive path. A new `source: "audit" | "graph_traversal"` field on the response discloses which path actually served the data
diff --git a/tests/provenance/test_manager.py b/tests/provenance/test_manager.py
index 77f61b79..4e1fdd91 100644
--- a/tests/provenance/test_manager.py
+++ b/tests/provenance/test_manager.py
@@ -637,6 +637,36 @@ class TestProvenanceManager:
# and the old assertion was encoding the bug this issue was filed to fix.
assert entry is None
+ def test_track_relationship_storage_error_swallowed_sqlite(self, tmp_path):
+ """Test that track_relationship returns None when storage.store() fails
+ on the SQLite backend, mirroring the InMemory contract verified by
+ test_track_relationship_storage_error_swallowed (#783/#785)."""
+ db_path = str(tmp_path / "test_track_relationship_sqlite.db")
+ prov_mgr = ProvenanceManager(storage_path=db_path)
+ with patch.object(prov_mgr.storage, "store", side_effect=RuntimeError("storage error")):
+ entry = prov_mgr.track_relationship("r_test", source="doc_1")
+ # Returning None is correct because nothing was actually persisted,
+ # and the old assertion was encoding the bug this issue was filed to fix.
+ assert entry is None
+
+ def test_track_chunk_storage_error_swallowed_sqlite(self, tmp_path):
+ """Test that track_chunk returns None when storage.store() fails
+ on the SQLite backend, mirroring the InMemory contract verified by
+ test_track_chunk_storage_error_swallowed (#783/#785)."""
+ db_path = str(tmp_path / "test_track_chunk_sqlite.db")
+ prov_mgr = ProvenanceManager(storage_path=db_path)
+ with patch.object(prov_mgr.storage, "store", side_effect=RuntimeError("storage error")):
+ entry = prov_mgr.track_chunk(
+ chunk_id="c_test",
+ source_document="doc_1",
+ source_path="/path/to/doc.pdf",
+ start_index=0,
+ end_index=100,
+ )
+ # Returning None is correct because nothing was actually persisted,
+ # and the old assertion was encoding the bug this issue was filed to fix.
+ assert entry is None
+
def test_track_property_source_storage_error_swallowed(self):
"""Test that track_property_source returns None when storage.store() fails,
since nothing was persisted (#783)."""
@@ -653,6 +683,24 @@ class TestProvenanceManager:
# and the old assertion was encoding the bug this issue was filed to fix.
assert entry is None
+ def test_track_property_source_storage_error_swallowed_sqlite(self, tmp_path):
+ """Test that track_property_source returns None when storage.store() fails
+ on the SQLite backend, mirroring the InMemory contract verified by
+ test_track_property_source_storage_error_swallowed (#783/#785)."""
+ db_path = str(tmp_path / "test_track_property_source_sqlite.db")
+ prov_mgr = ProvenanceManager(storage_path=db_path)
+ source = SourceReference(document="doc_1", page=1, confidence=0.9)
+ with patch.object(prov_mgr.storage, "store", side_effect=RuntimeError("storage error")):
+ entry = prov_mgr.track_property_source(
+ entity_id="e_test",
+ property_name="prop_test",
+ value="val",
+ source=source,
+ )
+ # Returning None is correct because nothing was actually persisted,
+ # and the old assertion was encoding the bug this issue was filed to fix.
+ assert entry is None
+
def test_save_entry_logs_on_every_failure_path(self):
"""Test that _save_entry logs on storage failures for both raising and swallowing paths (#783)."""
prov_mgr = ProvenanceManager()
@@ -690,6 +738,46 @@ class TestProvenanceManager:
assert count == 0
assert mock_log_error.call_count == 2
+ def test_chunks_batch_logs_per_item_failure_memory(self):
+ """Test that track_chunks_batch emits item-level logs via _save_entry when items fail,
+ mirroring test_track_entities_batch_logs_per_item_failure for the chunk path (#783/#785)."""
+ prov_mgr = ProvenanceManager()
+ chunks = [
+ {"id": "chk_fail_1", "start_index": 0, "end_index": 10},
+ {"id": "chk_fail_2", "start_index": 0, "end_index": 10},
+ ]
+ with patch.object(prov_mgr.storage, "_store_with_conn", side_effect=RuntimeError("batch store error")), \
+ patch.object(prov_mgr.logger, "error") as mock_log_error:
+ count = prov_mgr.track_chunks_batch(chunks, source_document="doc_1")
+ assert count == 0
+ assert mock_log_error.call_count == 2
+
+ def test_track_chunks_batch_block_level_transaction_failure_logs(self, tmp_path):
+ """Test that track_chunks_batch logs the block-level failure message when the
+ shared transaction itself fails to commit, mirroring the entities-batch coverage
+ established by test_batch_rollback_does_not_count_unpersisted_entries (#807/#785)."""
+ from contextlib import contextmanager
+ import sqlite3
+
+ db_path = str(tmp_path / "test_chunks_block_level_failure.db")
+ prov_mgr = ProvenanceManager(storage_path=db_path)
+ chunks = [{"id": f"chk_{i}", "start_index": 0, "end_index": 10} for i in range(5)]
+
+ @contextmanager
+ def failing_tx():
+ with prov_mgr.storage.transaction() as conn:
+ yield conn
+ raise sqlite3.OperationalError("Commit failed")
+
+ with patch.object(prov_mgr.storage, "transaction", side_effect=failing_tx), \
+ patch.object(prov_mgr.logger, "error") as mock_log_error:
+ count = prov_mgr.track_chunks_batch(chunks, source_document="doc_1")
+ assert count == 0
+ mock_log_error.assert_called_once()
+ assert "Block-level storage transaction failed in track_chunks_batch" in mock_log_error.call_args[0][0]
+
+ assert len(prov_mgr.storage.retrieve_all()) == 0
+
def test_track_entity_pre_build_failure_fallback_skips_store(self):
"""Test that when track_entity fails before the entry is built (e.g. a
retrieve error inside the atomic transaction) on a brand-new entity,