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
Address Qodo review: cover derived_from in explicit-parent check, keep archived history entries reachable via used_entities
Sameer6305e81baca5a893
diff --git a/semantica/provenance/manager.py b/semantica/provenance/manager.pyindex 9bfea349..3021242d 100644--- a/semantica/provenance/manager.py+++ b/semantica/provenance/manager.py@@ -25,6 +25,7 @@ License: MIT"""from typing import Optional, List, Dict, Any+from collections.abc import Mappingfrom datetime import datetimefrom .schemas import ProvenanceEntry, SourceReference, PropertySource@@ -115,7 +116,14 @@ class ProvenanceManager:# Check if entity already existsexisting = self.storage.retrieve(entity_id)parent_id = kwargs.get("parent_entity_id")-++ # If caller declared an explicit parent via metadata, honor it+ # (unless parent_entity_id was already passed directly)+ if not parent_id and metadata and isinstance(metadata, Mapping):+ derived_from = metadata.get("derived_from")+ if derived_from and isinstance(derived_from, str):+ parent_id = derived_from+# If source is a known entity, link it as parent (unless parent already set)if not parent_id and source and isinstance(source, str):try:@@ -129,13 +137,14 @@ class ProvenanceManager:pass# Track whether the caller explicitly supplied a parent link (via- # parent_entity_id kwarg or source-as-known-entity-id resolution)- # BEFORE the history-preservation block below. If they did, that- # explicit value should not be silently overwritten by the auto-- # generated history pointer (#742).+ # parent_entity_id kwarg, metadata["derived_from"], or source-as-+ # known-entity-id resolution) BEFORE the history-preservation block+ # below. If they did, that explicit value should not be silently+ # overwritten by the auto-generated history pointer (#742).explicit_parent_supplied = parent_id is not None# If entity exists, preserve history by archiving the old state+ archived_history_id = Noneif existing:# Create a history entry for the previous state# Use timestamp or counter for uniqueness@@ -152,6 +161,7 @@ class ProvenanceManager:# Store the history entrytry:self.storage.store(history_entry)+ archived_history_id = history_id# Link new entry to this history entry — but only when the# caller didn't explicitly supply a new parent on this call.# An explicit parent_entity_id (or derived_from on branches@@ -175,6 +185,14 @@ class ProvenanceManager:last_updated=datetime.utcnow().isoformat(),parent_entity_id=parent_id # Link to history or explicit parent)++ # Make the archived history entry discoverable via trace_lineage()'s+ # BFS over used_entities — this ensures the previous version remains+ # reachable in the lineage chain even when explicit_parent_supplied is+ # True and parent_entity_id points to the caller's explicit parent+ # rather than the history pointer.+ if archived_history_id:+ entry.used_entities.append(archived_history_id)# Compute checksum for integrityentry.checksum = compute_checksum(entry)diff --git a/tests/provenance/test_manager.py b/tests/provenance/test_manager.pyindex a651bbab..f3533cb9 100644--- a/tests/provenance/test_manager.py+++ b/tests/provenance/test_manager.py@@ -179,3 +179,46 @@ class TestProvenanceManager:assert y1.parent_entity_id is Noneassert y2.parent_entity_id is not Noneassert y2.parent_entity_id.startswith("Y:v:")++ def test_retrack_with_derived_from_overrides_history_link(self):+ """#742 — re-tracking with metadata['derived_from'] (no parent_entity_id+ kwarg) should also override the auto-generated history link, not just+ the parent_entity_id kwarg case."""+ prov_mgr = ProvenanceManager()++ prov_mgr.track_entity("parent_A", source="doc_1")+ prov_mgr.track_entity("parent_B", source="doc_1")++ e1 = prov_mgr.track_entity("Z", source="doc_1", metadata={"derived_from": "parent_A"})+ e2 = prov_mgr.track_entity("Z", source="doc_1", metadata={"derived_from": "parent_B"})++ assert e1.parent_entity_id == "parent_A"+ assert e2.parent_entity_id == "parent_B"++ def test_retrack_history_reachable_via_used_entities(self):+ """#742 — when re-tracking with an explicit parent, the archived history+ entry for the previous version must still be reachable in the lineage+ chain via used_entities (prov:used), even though it's no longer the+ direct parent_entity_id."""+ prov_mgr = ProvenanceManager()++ prov_mgr.track_entity("explicit_parent", source="doc_1")+ prov_mgr.track_entity("X", source="doc_1") # first track, no parent++ # Re-track with an explicit parent — should NOT lose the history entry+ e2 = prov_mgr.track_entity("X", source="doc_1", parent_entity_id="explicit_parent")++ assert e2.parent_entity_id == "explicit_parent"+ assert len(e2.used_entities) == 1+ assert e2.used_entities[0].startswith("X:v:")++ # trace_lineage should reach: X, explicit_parent (via parent_entity_id),+ # AND the archived history snapshot (via used_entities)+ lineage = prov_mgr.get_lineage("X")+ entity_ids = {e["entity_id"] for e in lineage["lineage_chain"]}++ assert "X" in entity_ids+ assert "explicit_parent" in entity_ids+ assert e2.used_entities[0] in entity_ids, (+ "Archived history entry should be reachable via used_entities in lineage"+ )