Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(provenance): fail closed when a BridgeAxiom provenance write fails (#2139)

Kevinf47699618967
diff --git a/CHANGELOG.md b/CHANGELOG.md
index af01b59d..91a8f4cd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,6 +34,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **Breaking: `BridgeAxiom.apply()` returned normally when its provenance record was not written** (fixes #2137) by @pkupt
+ - **Why**: `apply()` swallowed every provenance failure with `except Exception: pass`, and `ProvenanceManager.track_entity()` reports a storage failure by returning `None` (or a copy of the previous entry on an update) instead of raising. Either way the transform came back as if it had been recorded, so a translation could have no audit record, or a stale one showing an earlier value
+ - **What changed**: when a `prov_manager` is passed and the record is not written, `apply()` raises `ProvenanceRecordingError` (new in `semantica.utils`, error code `SEM007`), and `create_translation_chain()` lets it propagate. `apply()` gains `require_provenance=True`; with `False` it returns the transform instead. Every result now carries `provenance_recorded` (`bool`) and `provenance_error` (`str` or `None`). `trace_translation_chain()` no longer drops a failed `get_lineage()`: the layer gets `provenance=None` and a `provenance_error`
+ - **Who is affected**: callers that pass a `prov_manager` whose writes can fail, such as SQLite storage given metadata that is not JSON-serializable, or a duck-typed manager without `track_entity`. Tests that pass `MagicMock(spec=ProvenanceManager)` as the manager now raise, because the mock does not return a provenance entry. Calls without a `prov_manager`, and calls whose write succeeds, behave as before
+ - **Migration**: to keep best-effort behaviour, pass `require_provenance=False` and check `result["provenance_recorded"]`. A chain fails as a whole; steps recorded before the failing one stay in the store. New tests in `tests/provenance/test_bridge_axiom.py`
+ - Every layer in the trace now carries both `provenance` and `provenance_error`, so a consumer walking the trace does not hit a `KeyError` on the layers that name no entity. The raised message carries the exception type instead of its text, because a storage failure quotes SQL and filesystem paths and this string reaches logs and API responses; the original exception stays attached as `__cause__`
+
- **Relationship filtering on a `ContextGraph` rescanned the edge list for every node pair** (fixes #1927)
- `edge_types_between` read every edge of a `ContextGraph` for each (node, neighbour) pair it classified, so `detect_communities_label_propagation` and `calculate_pagerank` with `relationship_types` were O(E^2): about 21 s each on a 6,000-edge graph. `build_edge_type_index` now indexes a `ContextGraph`'s edge list as well, and both callers build the index once per call (1.4 s and 0.09 s on the same graph). The per-pair answers are unchanged. New `tests/kg/test_context_graph_edge_type_index.py`
diff --git a/docs/reference/provenance.md b/docs/reference/provenance.md
index e8f4ae51..a3d9c64c 100644
--- a/docs/reference/provenance.md
+++ b/docs/reference/provenance.md
@@ -392,6 +392,8 @@ chain = create_translation_chain(input_data, [axiom], prov_manager=manager)
print(chain.confidence) # 0.92
```
+When a `prov_manager` is passed and the provenance record cannot be written, `apply()` raises `ProvenanceRecordingError` (from `semantica.utils`) rather than returning an unrecorded result, and `create_translation_chain()` lets it propagate. Pass `require_provenance=False` for best effort: the call then returns normally and the result carries `provenance_recorded` (`bool`) and `provenance_error` (`str` or `None`) so the caller can see whether the record was written.
+
## Integration with GraphBuilder
`GraphBuilderWithProvenance` (from `semantica.kg`) automatically records provenance for every node and edge:
diff --git a/semantica/provenance/bridge_axiom.py b/semantica/provenance/bridge_axiom.py
index e5e96696..62ddb3b4 100644
--- a/semantica/provenance/bridge_axiom.py
+++ b/semantica/provenance/bridge_axiom.py
@@ -63,7 +63,9 @@ from dataclasses import dataclass, field
from typing import Optional, Dict, Any, List
import uuid
+from ..utils.exceptions import ProvenanceRecordingError
from ..utils.helpers import utc_now_iso
+from .manager import ProvenanceManager
@dataclass
@@ -139,6 +141,7 @@ class BridgeAxiom:
input_entity: str,
input_value: float,
prov_manager: Optional[Any] = None,
+ require_provenance: bool = True,
**kwargs
) -> Dict[str, Any]:
"""
@@ -148,10 +151,16 @@ class BridgeAxiom:
input_entity: Input entity identifier
input_value: Input value to transform
prov_manager: ProvenanceManager instance (optional)
+ require_provenance: If True (default), raise
+ ProvenanceRecordingError when a prov_manager is given and the
+ write fails. If False, return the transform with
+ provenance_recorded=False and provenance_error set instead.
**kwargs: Additional parameters
Returns:
- Dictionary with result and provenance information
+ Dictionary with result and provenance information. Always includes
+ provenance_recorded (bool) and provenance_error (str or None);
+ provenance_recorded is False without a prov_manager.
Example:
>>> result = ba.apply(
@@ -169,10 +178,33 @@ class BridgeAxiom:
output_entity = f"{input_entity}_transformed_{self.axiom_id}"
# Track provenance if manager provided
- if prov_manager:
+ provenance_recorded = False
+ provenance_error: Optional[str] = None
+ # "is not None", not truthiness: a manager that defines __len__ (an
+ # empty store) is still a manager, and skipping it would report the
+ # write as never attempted instead of failing closed.
+ if prov_manager is not None:
+ metadata = {
+ "axiom_id": self.axiom_id,
+ "axiom_name": self.name,
+ "rule": self.rule,
+ "coefficient": self.coefficient,
+ "input_entity": input_entity,
+ "input_value": input_value,
+ "output_value": output_value,
+ "input_domain": self.input_domain,
+ "output_domain": self.output_domain,
+ **kwargs,
+ }
+ # Only the exception type is reported, in the raised message and in
+ # provenance_error alike. The text of a storage failure can carry
+ # SQL and filesystem paths, and both strings reach logs and API
+ # responses; the original exception stays attached as __cause__.
+ failure: Optional[str] = None
+ cause: Optional[BaseException] = None
try:
# Track the bridge axiom application
- prov_manager.track_entity(
+ recorded = prov_manager.track_entity(
entity_id=output_entity,
source=self.source_doi,
entity_type="bridge_axiom_result",
@@ -180,22 +212,34 @@ class BridgeAxiom:
source_location=self.source_page,
source_quote=self.source_quote,
confidence=self.confidence,
- metadata={
- "axiom_id": self.axiom_id,
- "axiom_name": self.name,
- "rule": self.rule,
- "coefficient": self.coefficient,
- "input_entity": input_entity,
- "input_value": input_value,
- "output_value": output_value,
- "input_domain": self.input_domain,
- "output_domain": self.output_domain,
- **kwargs
- }
+ metadata=metadata,
)
- except Exception:
- pass # Graceful failure
-
+ except Exception as exc:
+ failure = type(exc).__name__
+ cause = exc
+ else:
+ # ProvenanceManager logs storage failures instead of raising:
+ # it returns None for a new entity, or a copy of the old entry
+ # when an update fails. Either way this application is not on
+ # record, so treat it as a failed write.
+ if isinstance(prov_manager, ProvenanceManager) and (
+ recorded is None or recorded.metadata != metadata
+ ):
+ failure = (
+ "storage did not persist the entry "
+ "(see the ProvenanceManager log)"
+ )
+
+ if failure is None:
+ provenance_recorded = True
+ elif require_provenance:
+ raise ProvenanceRecordingError(
+ f"Could not record provenance for {output_entity!r}: {failure}",
+ entity_id=output_entity,
+ ) from cause
+ else:
+ provenance_error = failure
+
return {
"axiom_id": self.axiom_id,
"axiom_name": self.name,
@@ -208,7 +252,9 @@ class BridgeAxiom:
"source_doi": self.source_doi,
"source_page": self.source_page,
"input_domain": self.input_domain,
- "output_domain": self.output_domain
+ "output_domain": self.output_domain,
+ "provenance_recorded": provenance_recorded,
+ "provenance_error": provenance_error,
}
def to_dict(self) -> Dict[str, Any]:
@@ -419,18 +465,24 @@ def trace_translation_chain(
"layer": layer.get("layer"),
"type": layer.get("type"),
"value": layer.get("value"),
- "source": layer.get("source")
+ "source": layer.get("source"),
+ # Both keys exist on every layer, whether or not it names an
+ # entity: a consumer that walks the trace should read "provenance
+ # unavailable" rather than trip over a KeyError on the layers that
+ # have no entity_id.
+ "provenance": None,
+ "provenance_error": None,
}
-
+
# Get provenance for entities in this layer
entity_id = layer.get("entity_id")
if entity_id:
try:
- lineage = prov_manager.get_lineage(entity_id)
- layer_trace["provenance"] = lineage
- except Exception:
- pass
-
+ layer_trace["provenance"] = prov_manager.get_lineage(entity_id)
+ except Exception as exc:
+ # Type only, for the same reason as in BridgeAxiom.apply().
+ layer_trace["provenance_error"] = type(exc).__name__
+
trace["layers"].append(layer_trace)
return trace
diff --git a/semantica/utils/__init__.py b/semantica/utils/__init__.py
index a6d7aa9e..7ebcafea 100644
--- a/semantica/utils/__init__.py
+++ b/semantica/utils/__init__.py
@@ -61,6 +61,7 @@ from .constants import (
from .exceptions import (
ConfigurationError,
ProcessingError,
+ ProvenanceRecordingError,
QualityError,
SemanticaError,
TemporalValidationError,
@@ -167,6 +168,7 @@ __all__ = [
"ProcessingError",
"ConfigurationError",
"QualityError",
+ "ProvenanceRecordingError",
"handle_exception",
"format_exception",
# Validators
diff --git a/semantica/utils/exceptions.py b/semantica/utils/exceptions.py
index f7f9316e..d3c5d78b 100644
--- a/semantica/utils/exceptions.py
+++ b/semantica/utils/exceptions.py
@@ -304,6 +304,33 @@ class QualityError(SemanticaError):
self.metrics = details.get("metrics", {})
+class ProvenanceRecordingError(SemanticaError):
+ """
+ Exception raised when an operation completes but its provenance record
+ could not be written, so the result has no audit trail behind it.
+ """
+
+ def __init__(
+ self,
+ message: str,
+ provenance_context: Optional[Dict[str, Any]] = None,
+ **details: Any,
+ ):
+ """
+ Initialize provenance recording error.
+
+ Args:
+ message: Provenance recording error message
+ provenance_context: Provenance context dictionary
+ **details: Additional details (e.g. entity_id)
+ """
+ super().__init__(
+ message, context=provenance_context, error_code="SEM007", **details
+ )
+ self.provenance_context = provenance_context or {}
+ self.entity_id = details.get("entity_id")
+
+
def handle_exception(
exception: Exception, context: Optional[Dict[str, Any]] = None, **options: Any
) -> Dict[str, Any]:
diff --git a/tests/provenance/test_bridge_axiom.py b/tests/provenance/test_bridge_axiom.py
index 39618fb7..846abafa 100644
--- a/tests/provenance/test_bridge_axiom.py
+++ b/tests/provenance/test_bridge_axiom.py
@@ -8,6 +8,7 @@ import pytest
from semantica.provenance import ProvenanceManager
from semantica.provenance.bridge_axiom import (
BridgeAxiom,
+ ProvenanceRecordingError,
TranslationChain,
create_translation_chain,
trace_translation_chain
@@ -489,3 +490,199 @@ class TestEdgeCases:
assert data["chain_id"] == "chain_dict"
assert len(data["layers"]) == 1
assert data["confidence"] == 1.0
+
+
+class TestProvenanceFailClosed:
+ """A failed provenance write must not be silent (issue #2137)."""
+
+ def _axiom(self):
+ return BridgeAxiom(
+ axiom_id="BA-FAIL-001",
+ name="fail_closed",
+ rule="Test rule",
+ coefficient=2.0,
+ source_doi="10.1234/test",
+ source_page="Page 1",
+ )
+
+ def test_failure_raises_by_default(self):
+ with pytest.raises(ProvenanceRecordingError, match="BA-FAIL-001"):
+ self._axiom().apply("in", 3, prov_manager=object())
+
+ def test_opt_out_returns_a_flag_instead_of_raising(self):
+ result = self._axiom().apply(
+ "in", 3, prov_manager=object(), require_provenance=False
+ )
+
+ assert result["output_value"] == 6.0
+ assert result["provenance_recorded"] is False
+ assert "AttributeError" in result["provenance_error"]
+
+ def test_successful_write_reports_recorded(self):
+ result = self._axiom().apply("in", 3, prov_manager=ProvenanceManager())
+
+ assert result["output_value"] == 6.0
+ assert result["provenance_recorded"] is True
+ assert result["provenance_error"] is None
+
+ def test_no_manager_is_not_a_failure(self):
+ result = self._axiom().apply("in", 3)
+
+ assert result["output_value"] == 6.0
+ assert result["provenance_recorded"] is False
+ assert result["provenance_error"] is None
+
+ def test_chain_propagates_the_failure(self):
+ with pytest.raises(ProvenanceRecordingError):
+ create_translation_chain(
+ {"entity_id": "e1", "value": 3, "source": "doc"},
+ [self._axiom()],
+ object(),
+ )
+
+ def test_trace_reports_a_lineage_lookup_failure(self):
+ class _BadLineage:
+ def get_lineage(self, entity_id):
+ raise RuntimeError("lineage unavailable")
+
+ chain = TranslationChain(chain_id="chain_trace")
+ chain.add_layer("L1", "input", 1, entity_id="e1")
+
+ trace = trace_translation_chain(chain, _BadLineage())
+
+ layer = trace["layers"][0]
+ assert layer["provenance"] is None
+ assert "RuntimeError" in layer["provenance_error"]
+
+ def _broken_storage(self, manager, monkeypatch):
+ def fail(*args, **kwargs):
+ raise IOError("disk full")
+
+ monkeypatch.setattr(manager.storage, "store", fail)
+ monkeypatch.setattr(manager.storage, "_store_with_conn", fail)
+
+ def test_real_manager_storage_failure_raises(self, monkeypatch):
+ manager = ProvenanceManager()
+ self._broken_storage(manager, monkeypatch)
+
+ with pytest.raises(ProvenanceRecordingError) as excinfo:
+ self._axiom().apply("in", 3, prov_manager=manager)
+
+ assert excinfo.value.entity_id == "in_transformed_BA-FAIL-001"
+ assert excinfo.value.error_code == "SEM007"
+
+ def test_real_manager_storage_failure_is_reported_when_opted_out(
+ self, monkeypatch
+ ):
+ manager = ProvenanceManager()
+ self._broken_storage(manager, monkeypatch)
+
+ result = self._axiom().apply(
+ "in", 3, prov_manager=manager, require_provenance=False
+ )
+
+ assert result["provenance_recorded"] is False
+ assert result["provenance_error"] is not None
+
+ def test_failed_update_is_not_reported_as_recorded(self, monkeypatch):
+ # A failed update hands back a copy of the old entry; the new value
+ # must not be reported as recorded on the strength of that copy.
+ manager = ProvenanceManager()
+ axiom = self._axiom()
+ axiom.apply("in", 3, prov_manager=manager)
+ self._broken_storage(manager, monkeypatch)
+
+ result = axiom.apply("in", 5, prov_manager=manager, require_provenance=False)
+
+ assert result["output_value"] == 10.0
+ assert result["provenance_recorded"] is False
+ lineage = manager.get_lineage("in_transformed_BA-FAIL-001")
+ assert lineage["metadata"]["output_value"] == 6.0
+
+ def test_successful_update_is_recorded(self):
+ manager = ProvenanceManager()
+ axiom = self._axiom()
+ axiom.apply("in", 3, prov_manager=manager)
+
+ result = axiom.apply("in", 5, prov_manager=manager)
+
+ assert result["provenance_recorded"] is True
+ lineage = manager.get_lineage("in_transformed_BA-FAIL-001")
+ assert lineage["metadata"]["output_value"] == 10.0
+
+ def test_trace_layers_without_an_entity_still_carry_both_keys(self):
+ """A consumer walking the trace should not have to check for the key
+ first: a layer that names no entity reports "unavailable", it does not
+ omit the field."""
+ chain = TranslationChain(chain_id="chain_no_entity")
+ chain.add_layer("L2_axiom", "bridge_axiom", 2.0)
+
+ trace = trace_translation_chain(chain, ProvenanceManager())
+
+ layer = trace["layers"][0]
+ assert "provenance" in layer
+ assert "provenance_error" in layer
+ assert layer["provenance"] is None
+ assert layer["provenance_error"] is None
+
+ def test_the_raised_message_does_not_echo_the_storage_error(self):
+ """Storage failures carry SQL and paths. The message reaches logs and
+ API responses, so only the type goes in; the detail stays on the
+ cause."""
+
+ class _LeakyManager:
+ def track_entity(self, **kwargs):
+ raise RuntimeError("no such table: /home/analyst/secret.db")
+
+ with pytest.raises(ProvenanceRecordingError) as caught:
+ self._axiom().apply("in", 3, prov_manager=_LeakyManager())
+
+ message = str(caught.value)
+ assert "BA-FAIL-001" in message
+ assert "RuntimeError" in message
+ assert "secret.db" not in message
+ assert isinstance(caught.value.__cause__, RuntimeError)
+
+ def test_best_effort_and_trace_errors_do_not_echo_the_storage_error(self):
+ """The opt-out result and the trace layer reach the same logs and API
+ responses as the raised message, so they carry only the type too."""
+
+ class _LeakyManager:
+ def track_entity(self, **kwargs):
+ raise RuntimeError("no such table: /home/analyst/secret.db")
+
+ def get_lineage(self, entity_id):
+ raise RuntimeError("no such table: /home/analyst/secret.db")
+
+ result = self._axiom().apply(
+ "in", 3, prov_manager=_LeakyManager(), require_provenance=False
+ )
+ assert result["provenance_error"] == "RuntimeError"
+
+ chain = TranslationChain(chain_id="chain_leaky")
+ chain.add_layer("L1", "input", 1, entity_id="e1")
+ layer = trace_translation_chain(chain, _LeakyManager())["layers"][0]
+ assert layer["provenance_error"] == "RuntimeError"
+
+ def test_real_manager_storage_failure_names_the_reason(self, monkeypatch):
+ # ProvenanceManager swallows the storage exception, so the message
+ # has to say what went wrong rather than name an exception type.
+ manager = ProvenanceManager()
+ self._broken_storage(manager, monkeypatch)
+
+ with pytest.raises(ProvenanceRecordingError, match="did not persist"):
+ self._axiom().apply("in", 3, prov_manager=manager)
+
+ def test_falsy_manager_still_fails_closed(self):
+ """A manager that defines __len__ (an empty store) is falsy, but it is
+ still a manager: a failed write must raise, not be skipped."""
+
+ class _EmptyManager:
+ def __len__(self):
+ return 0
+
+ def track_entity(self, **kwargs):
+ raise RuntimeError("write failed")
+
+ with pytest.raises(ProvenanceRecordingError):
+ self._axiom().apply("in", 3, prov_manager=_EmptyManager())