Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(explorer): classify multi-hop audit lineage as upstream and enforce provenance storage configuration (#792)

Sameer6305d30aea79a70f
diff --git a/semantica/explorer/app.py b/semantica/explorer/app.py
index 7189fade..c214021a 100644
--- a/semantica/explorer/app.py
+++ b/semantica/explorer/app.py
@@ -3,7 +3,6 @@ Semantica Explorer FastAPI application factory.
"""
import asyncio
-import logging
import os
from contextlib import asynccontextmanager
from pathlib import Path
@@ -19,8 +18,6 @@ from ..context.context_graph import ContextGraph
from .session import GraphSession
from .ws import ConnectionManager
-logger = logging.getLogger(__name__)
-
def _read_int_env(name: str, default: int) -> int:
raw_value = os.environ.get(name)
@@ -96,19 +93,7 @@ def create_app(
else:
active_session = session
if prov_path is not None:
- if active_session._provenance_storage_path is None:
- if getattr(active_session, "_provenance_manager", None) is not None:
- logger.warning(
- "provenance_storage_path=%s was supplied to create_app(), but "
- "the given session's provenance_manager was already constructed "
- "(likely accessed before create_app() ran) and will keep using "
- "its original storage. Pass provenance_storage_path when "
- "constructing the GraphSession instead, or access "
- "session.provenance_manager only after create_app().",
- prov_path,
- )
- else:
- active_session._provenance_storage_path = prov_path
+ active_session.set_provenance_storage_path(prov_path)
@asynccontextmanager
async def lifespan(app: FastAPI):
diff --git a/semantica/explorer/routes/provenance.py b/semantica/explorer/routes/provenance.py
index a3f72337..9145ba64 100644
--- a/semantica/explorer/routes/provenance.py
+++ b/semantica/explorer/routes/provenance.py
@@ -89,13 +89,11 @@ def _transform_audit_lineage(lineage: Dict[str, Any], node_id: str) -> Dict[str,
# ancestor chains via parent_entity_id and used_entities. It does not perform
# reverse lookups for downstream descendants. Consequently, 'direction = "downstream"'
# is unreachable in practice for this audit path until reverse lookup is supported
- # by ProvenanceManager.
- if eid == node_id:
- direction = "upstream"
- elif src == node_id:
+ # by ProvenanceManager. All ancestor derivation edges are upstream lineage.
+ if src == node_id:
direction = "downstream"
else:
- direction = "lateral"
+ direction = "upstream"
edges.append({
"id": f"{src}-{eid}",
diff --git a/semantica/explorer/session.py b/semantica/explorer/session.py
index 1ea6c082..8692f59e 100644
--- a/semantica/explorer/session.py
+++ b/semantica/explorer/session.py
@@ -194,6 +194,28 @@ class GraphSession:
)
return self._provenance_manager
+ def set_provenance_storage_path(self, storage_path: Optional[str]) -> None:
+ """Set or reconfigure the provenance storage path for this session.
+
+ Raises a ValueError if a conflicting storage path is already configured or
+ if the provenance manager has already been constructed with a different path.
+ """
+ with self._lock:
+ if self._provenance_storage_path == storage_path:
+ return
+ if self._provenance_manager is not None:
+ raise ValueError(
+ f"Cannot change provenance_storage_path to '{storage_path}': "
+ f"provenance_manager is already initialized with "
+ f"'{self._provenance_storage_path}'."
+ )
+ if self._provenance_storage_path is not None and storage_path is not None:
+ raise ValueError(
+ f"Conflicting provenance_storage_path: session is already configured "
+ f"with '{self._provenance_storage_path}', cannot overwrite with '{storage_path}'."
+ )
+ self._provenance_storage_path = storage_path
+
def normalize_node(self, node: Dict[str, Any]) -> Dict[str, Any]:
meta: Dict[str, Any] = {}
meta.update(node.get("metadata", {}) or {})
diff --git a/tests/explorer/test_provenance_manager_wiring.py b/tests/explorer/test_provenance_manager_wiring.py
index dec8c1b8..6a07d26d 100644
--- a/tests/explorer/test_provenance_manager_wiring.py
+++ b/tests/explorer/test_provenance_manager_wiring.py
@@ -54,6 +54,7 @@ def test_provenance_manager_wiring_audit_path(client, session):
edge_pairs = {(e["source"], e["target"]) for e in data["edges"]}
assert ("grandparent", "parent") in edge_pairs
assert ("parent", "child") in edge_pairs
+ assert all(e["direction"] == "upstream" for e in data["edges"])
# Confirm /api/provenance/report also uses audit path
rep_response = client.get("/api/provenance/report", params={"node_id": "child"})
@@ -62,6 +63,16 @@ def test_provenance_manager_wiring_audit_path(client, session):
assert report_data.get("source") == "audit"
assert report_data["lineage"].get("source") == "audit"
+ # Confirm markdown export classifies multi-hop ancestor edges under Upstream, not Lateral
+ md_response = client.get(
+ "/api/provenance/report", params={"node_id": "child", "format": "markdown"}
+ )
+ assert md_response.status_code == 200
+ md_text = md_response.text
+ assert "## Upstream" in md_text
+ assert "grandparent" in md_text and "parent" in md_text
+ assert "## Lateral" not in md_text
+
def test_provenance_manager_wiring_fallback_no_records(client, session):
"""Test that a node with no audit records falls back cleanly to source='graph_traversal'."""
@@ -122,3 +133,29 @@ def test_provenance_storage_isolation_between_sessions(tmp_path):
pm1.track_entity(entity_id="node_in_1", source="doc_A", entity_type="entity")
assert pm1.storage.retrieve("node_in_1") is not None
assert pm2.storage.retrieve("node_in_1") is None
+
+
+def test_create_app_rejects_conflicting_provenance_storage_path(tmp_path):
+ """Test that create_app raises ValueError when given a session with a conflicting preconfigured path."""
+ path1 = str(tmp_path / "orig.db")
+ path2 = str(tmp_path / "conflict.db")
+ sess = GraphSession(ContextGraph(advanced_analytics=False), provenance_storage_path=path1)
+ with pytest.raises(ValueError, match="Conflicting provenance_storage_path"):
+ create_app(session=sess, provenance_storage_path=path2)
+
+
+def test_create_app_rejects_path_when_manager_already_initialized(tmp_path):
+ """Test that create_app raises ValueError when given a session whose manager was already constructed."""
+ sess = GraphSession(ContextGraph(advanced_analytics=False))
+ _ = sess.provenance_manager # construct and cache
+ with pytest.raises(ValueError, match="provenance_manager is already initialized"):
+ create_app(session=sess, provenance_storage_path=str(tmp_path / "late.db"))
+
+
+def test_create_app_allows_matching_provenance_storage_path(tmp_path):
+ """Test that create_app succeeds when the supplied path matches the session's existing path."""
+ path1 = str(tmp_path / "same.db")
+ sess = GraphSession(ContextGraph(advanced_analytics=False), provenance_storage_path=path1)
+ app = create_app(session=sess, provenance_storage_path=path1)
+ with TestClient(app):
+ assert app.state.session._provenance_storage_path == path1