Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

refactor(provenance): centralize duplicated store-and-swallow logic into _save_entry() (#784) (#815)

Sameer Kadame197977172a4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 221f314c..977b4178 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **`ProvenanceManager` duplicated the same checksum/persist/exception-swallow block across 4 tracking methods** (#784, #815) by @Sameer6305 and @KaifAhmad1
+ - Consolidated the repeated `entry.checksum = compute_checksum(entry)` / `try: self.storage.store(entry) except Exception: pass` block used by `track_entity`, `track_relationship`, `track_chunk`, and `track_property_source` into a single `ProvenanceManager._save_entry()` helper, preserving the existing graceful-failure behavior and the batch `_conn`/re-raise semantics from #807
+ - Added 4 regression tests (`tests/provenance/test_manager.py`) covering storage-failure swallowing for each of the four tracking methods, none of which had coverage for this path before
+ - **Follow-up review fix**: the initial refactor of `track_entity`'s exception fallback (the branch that runs when a failure happens *before* the entry is built, e.g. a retrieve error inside the atomic transaction) routed through `_save_entry()`, which made a new `self.storage.store(entry)` call outside the already-failed transaction — a real behavioral change from the original code (which only computed a checksum on that path) that could have reintroduced the exact race #807's `BEGIN IMMEDIATE` transaction serialization was meant to prevent. Reverted that branch to only compute the checksum, and added `test_track_entity_pre_build_failure_fallback_skips_store` asserting `storage.store` is never called on that path
+
- **`SQLiteStorage` and `ProvenanceManager` connection churn, non-atomic writes, and batch tracking overhead** (#807) by @Sameer6305
- Scoped a single SQLite connection to the full duration of each public storage method call (`track_entity()`, `store()`, `retrieve_all()`, `clear()`) instead of opening independent connections per internal SQL statement, reducing connection churn by ~67% while closing the handle before the public method returns to preserve Windows filesystem unlink safety
- Implemented the `SQLiteStorage.transaction()` context manager with Write-Ahead Logging (`PRAGMA journal_mode=WAL`), `busy_timeout=5000`, `synchronous=NORMAL`, and immediate write transactions (`BEGIN IMMEDIATE`), ensuring concurrent read-modify-write sequences (including history version ID generation) are serialized without lock contention or data loss
diff --git a/semantica/provenance/manager.py b/semantica/provenance/manager.py
index 3ac3036d..b4e6f046 100644
--- a/semantica/provenance/manager.py
+++ b/semantica/provenance/manager.py
@@ -136,6 +136,30 @@ class ProvenanceManager:
self.storage = SQLiteStorage(storage_path)
else:
self.storage = InMemoryStorage()
+
+ def _save_entry(
+ self,
+ entry: ProvenanceEntry,
+ _conn: Optional[Any] = None,
+ _raise_on_error: bool = False,
+ ) -> ProvenanceEntry:
+ """Compute checksum, store entry persistently, and gracefully ignore storage errors."""
+ entry.checksum = compute_checksum(entry)
+
+ try:
+ if _conn is not None:
+ self.storage._store_with_conn(_conn, entry)
+ else:
+ self.storage.store(entry)
+ except Exception:
+ # Propagate when called from a batch's shared transaction so the
+ # caller's per-item try/except can skip counting this item instead
+ # of reporting an unpersisted entry as tracked (#807).
+ if _raise_on_error:
+ raise
+ pass # Graceful failure - don't break main functionality
+
+ return entry
@contextmanager
def _get_or_create_transaction(self, _conn=None):
@@ -242,9 +266,7 @@ class ProvenanceManager:
if archived_history_id and explicit_parent_supplied:
entry.used_entities.append(archived_history_id)
- entry.checksum = compute_checksum(entry)
-
- self.storage._store_with_conn(conn, entry)
+ self._save_entry(entry, _conn=conn, _raise_on_error=(_conn is not None))
except Exception:
# When called from a batch's shared transaction (_conn is not None),
# propagate so the caller's per-item try/except can skip counting
@@ -308,14 +330,7 @@ class ProvenanceManager:
last_updated=datetime.utcnow().isoformat()
)
- entry.checksum = compute_checksum(entry)
-
- try:
- self.storage.store(entry)
- except Exception:
- pass
-
- return entry
+ return self._save_entry(entry)
# === Chunk Tracking (from split.ProvenanceTracker) ===
@@ -367,21 +382,7 @@ class ProvenanceManager:
timestamp=datetime.utcnow().isoformat()
)
- entry.checksum = compute_checksum(entry)
-
- try:
- if _conn is not None:
- self.storage._store_with_conn(_conn, entry)
- else:
- self.storage.store(entry)
- except Exception:
- # Propagate when called from a batch's shared transaction so the
- # caller's per-item try/except can skip counting this item instead
- # of reporting an unpersisted entry as tracked (#807).
- if _conn is not None:
- raise
-
- return entry
+ return self._save_entry(entry, _conn=_conn, _raise_on_error=(_conn is not None))
# === Source Tracking (from conflicts.SourceTracker) ===
@@ -437,14 +438,7 @@ class ProvenanceManager:
timestamp=datetime.utcnow().isoformat()
)
- entry.checksum = compute_checksum(entry)
-
- try:
- self.storage.store(entry)
- except Exception:
- pass
-
- return entry
+ return self._save_entry(entry)
# === Batch Operations ===
diff --git a/tests/provenance/test_manager.py b/tests/provenance/test_manager.py
index 157e8300..a4e999e5 100644
--- a/tests/provenance/test_manager.py
+++ b/tests/provenance/test_manager.py
@@ -6,6 +6,7 @@ chunk tracking, source tracking, and lineage tracing.
"""
import pytest
+from unittest.mock import patch
from semantica.provenance import ProvenanceManager, SourceReference
@@ -598,3 +599,67 @@ class TestProvenanceManager:
assert check_broken["errors"] >= 1
assert "e_broken_child -> non_existent_parent" in check_broken["missing_references"]
+ def test_track_entity_storage_error_swallowed(self):
+ """Test that track_entity swallows storage.store() exceptions and still returns a ProvenanceEntry."""
+ prov_mgr = ProvenanceManager()
+ with patch.object(prov_mgr.storage, "store", side_effect=RuntimeError("storage error")):
+ entry = prov_mgr.track_entity("e_test", source="doc_1")
+ assert entry is not None
+ assert entry.entity_id == "e_test"
+ assert entry.checksum is not None
+
+ def test_track_relationship_storage_error_swallowed(self):
+ """Test that track_relationship swallows storage.store() exceptions and still returns a ProvenanceEntry."""
+ prov_mgr = ProvenanceManager()
+ with patch.object(prov_mgr.storage, "store", side_effect=RuntimeError("storage error")):
+ entry = prov_mgr.track_relationship("r_test", source="doc_1")
+ assert entry is not None
+ assert entry.entity_id == "r_test"
+ assert entry.checksum is not None
+
+ def test_track_chunk_storage_error_swallowed(self):
+ """Test that track_chunk swallows storage.store() exceptions and still returns a ProvenanceEntry."""
+ prov_mgr = ProvenanceManager()
+ 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,
+ )
+ assert entry is not None
+ assert entry.entity_id == "c_test"
+ assert entry.checksum is not None
+
+ def test_track_property_source_storage_error_swallowed(self):
+ """Test that track_property_source swallows storage.store() exceptions and still returns a ProvenanceEntry."""
+ prov_mgr = ProvenanceManager()
+ 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,
+ )
+ assert entry is not None
+ assert entry.entity_id == "e_test_prop_test"
+ assert entry.checksum is not None
+
+ 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), the fallback entry only
+ gets a checksum and is not persisted via a second, out-of-transaction
+ storage.store() call (#784)."""
+ prov_mgr = ProvenanceManager()
+ with patch.object(
+ prov_mgr.storage, "_retrieve_with_conn", side_effect=RuntimeError("retrieve error")
+ ), patch.object(prov_mgr.storage, "store") as mock_store:
+ entry = prov_mgr.track_entity("e_test", source="doc_1")
+ assert entry is not None
+ assert entry.entity_id == "e_test"
+ assert entry.checksum is not None
+ mock_store.assert_not_called()
+
+