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
fixed qodo reviews
Sameer63053db35a6871f5
diff --git a/semantica/provenance/manager.py b/semantica/provenance/manager.pyindex 08015d1b..19a6a5ec 100644--- a/semantica/provenance/manager.py+++ b/semantica/provenance/manager.py@@ -29,6 +29,7 @@ from collections.abc import Mappingfrom datetime import datetimefrom contextlib import contextmanagerimport copy+import inspectimport jsonimport threading@@ -182,8 +183,9 @@ class ProvenanceManager:# Atomic tracking transaction (#807):# We scope one connection to the full duration of track_entity so all- # retrieve and store operations share a single transaction. If any- # step raises, the whole operation rolls back.+ # retrieve and store operations share a single transaction. With BEGIN IMMEDIATE,+ # concurrent calls serialize during retrieval so no intervening versions are lost.+ # If any step raises, the whole operation rolls back.entry = Nonetry:with self._get_or_create_transaction(_conn) as conn:@@ -208,13 +210,15 @@ class ProvenanceManager:archived_history_id = Noneif existing:history_entry = copy.deepcopy(existing)- history_id = f"{entity_id}:v:{existing.last_updated}"-- if self.storage._retrieve_with_conn(conn, history_id):- history_id = f"{history_id}:{datetime.utcnow().microsecond}"-+ base_history_id = f"{entity_id}:v:{existing.last_updated}"+ history_id = base_history_id+ counter = 1+ while self.storage._retrieve_with_conn(conn, history_id):+ history_id = f"{base_history_id}:{counter}"+ counter += 1+history_entry.entity_id = history_id-+self.storage._store_with_conn(conn, history_entry)archived_history_id = history_idif not explicit_parent_supplied:@@ -464,6 +468,7 @@ class ProvenanceManager:for i in range(0, len(entities), batch_size):batch = entities[i : i + batch_size]+ batch_count = 0try:with self.storage.transaction() as conn:for entity in batch:@@ -475,9 +480,12 @@ class ProvenanceManager:try:self.track_entity(entity_id, source, entity_metadata, _conn=conn)- tracked_count += 1+ batch_count += 1except Exception:pass # Continue with other entities in this batch+ # Add batch_count to tracked_count only after the transaction context+ # exits successfully and commits (#807).+ tracked_count += batch_countexcept Exception:pass # Partial failure: if block-level storage transaction fails, continue to next block@@ -507,6 +515,7 @@ class ProvenanceManager:for i in range(0, len(chunks), batch_size):batch = chunks[i : i + batch_size]+ batch_count = 0try:with self.storage.transaction() as conn:for chunk in batch:@@ -525,9 +534,12 @@ class ProvenanceManager:_conn=conn,**{**metadata, **chunk.get("metadata", {})})- tracked_count += 1+ batch_count += 1except Exception:pass+ # Add batch_count to tracked_count only after the transaction context+ # exits successfully and commits (#807).+ tracked_count += batch_countexcept Exception:pass@@ -612,7 +624,18 @@ class ProvenanceManager:Returns:List of ProvenanceEntry objects"""- return self.storage.trace_lineage(entity_id, max_depth=max_depth)+ if max_depth is None:+ return self.storage.trace_lineage(entity_id)+ try:+ sig = inspect.signature(self.storage.trace_lineage)+ supports_max_depth = "max_depth" in sig.parameters or any(+ p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()+ )+ except (ValueError, TypeError):+ supports_max_depth = True+ if supports_max_depth:+ return self.storage.trace_lineage(entity_id, max_depth=max_depth)+ return self.storage.trace_lineage(entity_id)def get_all_sources(self, entity_id: str) -> List[Dict[str, Any]]:"""diff --git a/semantica/provenance/storage.py b/semantica/provenance/storage.pyindex 6bad5682..d64608bb 100644--- a/semantica/provenance/storage.py+++ b/semantica/provenance/storage.py@@ -79,9 +79,14 @@ class ProvenanceStorage(ABC):"""Trace complete lineage for an entity.+ Note:+ Custom storage backends implementing only trace_lineage(self, entity_id)+ remain backward compatible; ProvenanceManager automatically preserves+ one-argument invocations when max_depth is omitted or unsupported.+Args:entity_id: Entity identifier- max_depth: Optional maximum BFS depth+ max_depth: Optional maximum BFS depth (default: None)Returns:List of ProvenanceEntry objects in lineage chain@@ -308,24 +313,37 @@ class SQLiteStorage(ProvenanceStorage):except Exception:pass- conn.execute("PRAGMA busy_timeout=5000")- conn.execute("PRAGMA synchronous=NORMAL")+ try:+ conn.execute("PRAGMA busy_timeout=5000")+ except sqlite3.OperationalError as e:+ self.logger.warning(f"busy_timeout PRAGMA not supported ({e})")++ try:+ conn.execute("PRAGMA synchronous=NORMAL")+ except sqlite3.OperationalError as e:+ self.logger.warning(f"synchronous PRAGMA not supported ({e})")@contextmanagerdef transaction(self):"""Context manager providing an active SQLite connection within a transaction.+ Starts an IMMEDIATE write transaction (BEGIN IMMEDIATE) so read-modify-write+ sequences are serialized across concurrent connections.Commits on normal exit, rolls back on exception, and always closes the connection.Configures PRAGMAs (WAL, busy_timeout=5000, synchronous=NORMAL)."""conn = sqlite3.connect(self.db_path)- self._configure_connection(conn)try:+ self._configure_connection(conn)+ conn.execute("BEGIN IMMEDIATE")yield connconn.commit()except Exception:- conn.rollback()+ try:+ conn.rollback()+ except Exception:+ passraisefinally:conn.close()@@ -333,51 +351,53 @@ class SQLiteStorage(ProvenanceStorage):def _init_db(self) -> None:"""Create tables with W3C PROV-O compliant schema."""conn = sqlite3.connect(self.db_path)- self._configure_connection(conn)- cursor = conn.cursor()-- cursor.execute("""- CREATE TABLE IF NOT EXISTS provenance (- entity_id TEXT PRIMARY KEY,- entity_type TEXT NOT NULL,- activity_id TEXT NOT NULL,- agent_id TEXT DEFAULT 'semantica',- source_document TEXT,- source_location TEXT,- source_quote TEXT,- timestamp TEXT NOT NULL,- first_seen TEXT,- last_updated TEXT,- confidence REAL DEFAULT 1.0,- checksum TEXT,- parent_entity_id TEXT,- used_entities TEXT,- start_index INTEGER,- end_index INTEGER,- credibility REAL,- metadata TEXT,- version TEXT DEFAULT '1.0'- )- """)-- # Create indexes for efficient querying- cursor.execute("""- CREATE INDEX IF NOT EXISTS idx_entity_type- ON provenance(entity_type)- """)-- cursor.execute("""- CREATE INDEX IF NOT EXISTS idx_source_document- ON provenance(source_document)- """)-- cursor.execute("""- CREATE INDEX IF NOT EXISTS idx_parent_entity- ON provenance(parent_entity_id)- """)-- conn.commit()- conn.close()+ try:+ self._configure_connection(conn)+ cursor = conn.cursor()++ cursor.execute("""+ CREATE TABLE IF NOT EXISTS provenance (+ entity_id TEXT PRIMARY KEY,+ entity_type TEXT NOT NULL,+ activity_id TEXT NOT NULL,+ agent_id TEXT DEFAULT 'semantica',+ source_document TEXT,+ source_location TEXT,+ source_quote TEXT,+ timestamp TEXT NOT NULL,+ first_seen TEXT,+ last_updated TEXT,+ confidence REAL DEFAULT 1.0,+ checksum TEXT,+ parent_entity_id TEXT,+ used_entities TEXT,+ start_index INTEGER,+ end_index INTEGER,+ credibility REAL,+ metadata TEXT,+ version TEXT DEFAULT '1.0'+ )+ """)++ # Create indexes for efficient querying+ cursor.execute("""+ CREATE INDEX IF NOT EXISTS idx_entity_type+ ON provenance(entity_type)+ """)++ cursor.execute("""+ CREATE INDEX IF NOT EXISTS idx_source_document+ ON provenance(source_document)+ """)++ cursor.execute("""+ CREATE INDEX IF NOT EXISTS idx_parent_entity+ ON provenance(parent_entity_id)+ """)++ conn.commit()+ finally:+ conn.close()def store(self, entry: ProvenanceEntry) -> None:"""@@ -455,10 +475,9 @@ class SQLiteStorage(ProvenanceStorage):List of ProvenanceEntry objects"""conn = sqlite3.connect(self.db_path)- self._configure_connection(conn)- cursor = conn.cursor()-try:+ self._configure_connection(conn)+ cursor = conn.cursor()if entity_type:cursor.execute("""SELECT * FROM provenance WHERE entity_type = ?@@ -540,10 +559,9 @@ class SQLiteStorage(ProvenanceStorage):Number of entries cleared"""conn = sqlite3.connect(self.db_path)- self._configure_connection(conn)- cursor = conn.cursor()-try:+ self._configure_connection(conn)+ cursor = conn.cursor()cursor.execute("SELECT COUNT(*) FROM provenance")count = cursor.fetchone()[0]diff --git a/tests/provenance/test_sqlite_storage_performance_807.py b/tests/provenance/test_sqlite_storage_performance_807.pyindex c4bb7104..05505eb0 100644--- a/tests/provenance/test_sqlite_storage_performance_807.py+++ b/tests/provenance/test_sqlite_storage_performance_807.py@@ -90,3 +90,116 @@ def test_trace_lineage_batched_bfs_and_max_depth(tmp_path):limited_lineage = mgr.trace_lineage("ent_3", max_depth=1)assert len(limited_lineage) == 1assert limited_lineage[0].entity_id == "ent_3"+++def test_batch_rollback_does_not_count_unpersisted_entries(tmp_path):+ """Test that batch tracking does not increment count when transaction commit fails."""+ from contextlib import contextmanager+ db_path = str(tmp_path / "test_batch_rollback.db")+ mgr = ProvenanceManager(storage_path=db_path)++ entities = [{"id": f"ent_{i}"} for i in range(10)]+ chunks = [{"id": f"chk_{i}", "start_index": 0, "end_index": 10} for i in range(10)]++ @contextmanager+ def failing_tx():+ with mgr.storage.transaction() as conn:+ yield conn+ raise sqlite3.OperationalError("Commit failed")++ with patch.object(mgr.storage, "transaction", side_effect=failing_tx):+ ent_count = mgr.track_entities_batch(entities, source="doc_1")+ chk_count = mgr.track_chunks_batch(chunks, source_document="doc_1")+ assert ent_count == 0+ assert chk_count == 0++ assert len(mgr.storage.retrieve_all()) == 0+++def test_custom_storage_trace_lineage_one_argument_backward_compatibility():+ """Test that custom ProvenanceStorage implementing trace_lineage(entity_id) without max_depth remains compatible."""+ from typing import List, Optional+ from semantica.provenance.storage import ProvenanceStorage+ from semantica.provenance.schemas import ProvenanceEntry++ class LegacyCustomStorage(ProvenanceStorage):+ def __init__(self):+ self.calls = 0++ def store(self, entry: ProvenanceEntry) -> None:+ pass++ def retrieve(self, entity_id: str) -> Optional[ProvenanceEntry]:+ return None++ def retrieve_all(self, entity_type: Optional[str] = None) -> List[ProvenanceEntry]:+ return []++ def trace_lineage(self, entity_id: str) -> List[ProvenanceEntry]:+ self.calls += 1+ return []++ def clear(self) -> int:+ return 0++ storage = LegacyCustomStorage()+ mgr = ProvenanceManager(storage=storage)++ # Calling with max_depth omitted / None must succeed without TypeError+ lineage1 = mgr.trace_lineage("entity_1")+ assert lineage1 == []+ assert storage.calls == 1++ # Calling with max_depth provided must also fall back cleanly to 1-argument call without TypeError+ lineage2 = mgr.trace_lineage("entity_1", max_depth=2)+ assert lineage2 == []+ assert storage.calls == 2+++def test_track_entity_concurrent_read_modify_write(tmp_path):+ """Test that concurrent track_entity calls serialize via BEGIN IMMEDIATE without losing version history."""+ from concurrent.futures import ThreadPoolExecutor+ db_path = str(tmp_path / "test_concurrent.db")++ # Create initial version+ mgr_init = ProvenanceManager(storage_path=db_path)+ mgr_init.track_entity("entity_1", source="doc_init", metadata={"version": 0})++ def update_entity(index):+ # Separate manager/connection per worker+ mgr = ProvenanceManager(storage_path=db_path)+ return mgr.track_entity("entity_1", source=f"doc_{index}", metadata={"version": index})++ num_workers = 8+ with ThreadPoolExecutor(max_workers=num_workers) as executor:+ results = list(executor.map(update_entity, range(1, num_workers + 1)))++ assert len(results) == num_workers++ # Verify that all versions were preserved in history (1 current + num_workers archived versions = num_workers + 1 total entries)+ mgr_check = ProvenanceManager(storage_path=db_path)+ all_entries = mgr_check.storage.retrieve_all()+ assert len(all_entries) == num_workers + 1++ # All archived history IDs should start with "entity_1:v:" except the active entity_1+ history_entries = [e for e in all_entries if e.entity_id != "entity_1"]+ assert len(history_entries) == num_workers+ for he in history_entries:+ assert he.entity_id.startswith("entity_1:v:")+++def test_sqlite_storage_cleanup_guard_on_configure_error(tmp_path):+ """Test that connection handles are closed even when _configure_connection raises an exception."""+ from unittest.mock import patch+ db_path = str(tmp_path / "test_leak_guard.db")+ storage = SQLiteStorage(db_path)++ with patch.object(storage, "_configure_connection", side_effect=RuntimeError("PRAGMA error")):+ with pytest.raises(RuntimeError, match="PRAGMA error"):+ with storage.transaction():+ pass++ # Verify Windows unlink safety: handle must not be leaked after error+ assert os.path.exists(db_path)+ os.unlink(db_path)+ assert not os.path.exists(db_path)