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
feat(context): opt-in semantica.evals hook on decision recording (#1324)
Sakshi Jain3d64bde3a172
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d18f85a6..62bd238d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- `DecisionRecorder` and `AgentContext` gain opt-in `evaluators`/`eval_config` constructor parameters that run `semantica.evals` evaluators (e.g. `decision_scores`) automatically during `record_decision()`, storing `eval_score`/`eval_passed`/`eval_details` in `Decision.metadata`. Fully backward-compatible: omitting `evaluators` leaves recording behavior unchanged. Evaluator failures are logged and never block decision persistence. Wired for the `graph_store` backend only; the `context_graph` `AgentContext` backend is a known follow-up.+- **`RelationalSchemaMapper`** (#1386, part 1) by @costajohnt- `semantica.kg.RelationalSchemaMapper` maps rows from a relational source (`DBIngestor`, `SnowflakeIngestor`, `DatabricksIngestor`, `PandasIngestor`, a DataFrame or plain row dicts) to the `{"entities", "relationships"}` shape `GraphBuilder` and `OntologyGenerator` consume: entity tables become entities keyed by primary key, foreign keys become typed relationships, junction tables become relationships only- Every entity and relationship is tagged with the `source` it came from so `ConflictDetector` can key credibility on it. New `tests/kg/test_schema_mapper.py`@@ -567,7 +569,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Security-## [0.6.6] - 2026-08-20### Addeddiff --git a/docs/guides/decision-intelligence.md b/docs/guides/decision-intelligence.mdindex 1c8505cd..c923947a 100644--- a/docs/guides/decision-intelligence.md+++ b/docs/guides/decision-intelligence.md@@ -316,7 +316,27 @@ print("Policy exception recorded:", exception_id)For multi-level approval workflows, use `DecisionRecorder.record_approval_chain()` with a graph database backend (for example Neo4j/FalkorDB). The in-memory `ContextGraph` examples used in this guide do not support approval-chain persistence via `execute_query()`.+## Scoring Decisions Automatically on Record+`DecisionRecorder` (and `AgentContext`, for its `graph_store` decision-tracking backend) can run `semantica.evals` evaluators automatically every time a decision is recorded, storing the result on `Decision.metadata`. This is opt-in — pass `evaluators`/`eval_config` at construction time, or leave them unset and `record_decision()` behaves exactly as before.++```python+from semantica.context import DecisionRecorder++recorder = DecisionRecorder(+ graph_store=graph,+ evaluators=["decision_scores"],+ eval_config={"decision_scores": {"policy_engine": engine, "policy_id": "cti_confidence_gate"}},+)+decision_id = recorder.record_decision(d, entities=[], source_documents=[])++# d.metadata now also has:+# eval_score: 0.83 (mean score across configured evaluators)+# eval_passed: False+# eval_details: {"decision_scores": {"score": ..., "passed": ..., "meta": {...}}}+```++If an evaluator raises, the failure is logged and the decision is still recorded without `eval_*` metadata — a broken evaluator never blocks decision persistence. `AgentContext(..., decision_tracking=True, evaluators=[...], eval_config={...})` threads the same configuration into the `DecisionRecorder` it constructs for the `graph_store` backend; the `context_graph` backend does not yet run evaluators.## Generating a Decision Audit Reportdiff --git a/semantica/context/agent_context.py b/semantica/context/agent_context.pyindex 839e23db..54d0c5e4 100644--- a/semantica/context/agent_context.py+++ b/semantica/context/agent_context.py@@ -135,6 +135,8 @@ class AgentContext:advanced_analytics: bool = True,kg_algorithms: bool = True,vector_store_features: bool = True,+ evaluators: Optional[List[str]] = None,+ eval_config: Optional[Dict[str, Any]] = None,**kwargs,):"""@@ -153,6 +155,12 @@ class AgentContext:advanced_analytics: Enable advanced analytics (default: True)kg_algorithms: Enable KG algorithms integration (default: True)vector_store_features: Enable vector store features (default: True)+ evaluators: Optional list of semantica.evals evaluator names run+ automatically on every recorded decision (graph_store decision+ backend only). Passed through to DecisionRecorder; see its+ docstring. Omitting this leaves record_decision() unchanged.+ eval_config: Optional semantica.evals config dict, keyed by+ evaluator name, passed through to DecisionRecorder.**kwargs: Additional options passed to underlying componentsRaises:@@ -171,7 +179,9 @@ class AgentContext:self.knowledge_graph = knowledge_graphself._checkpoints: Dict[str, Dict[str, Any]] = {}self._temporal_version_manager = kwargs.get("temporal_version_manager")-+ self.evaluators = evaluators+ self.eval_config = eval_config or {}+# Store advanced feature flagsself.config = {"decision_tracking": decision_tracking,@@ -231,7 +241,11 @@ class AgentContext:if hasattr(knowledge_graph, "execute_query"):self._decision_backend = "graph_store"try:- self._decision_recorder = DecisionRecorder(knowledge_graph)+ self._decision_recorder = DecisionRecorder(+ knowledge_graph,+ evaluators=self.evaluators,+ eval_config=self.eval_config,+ )self._decision_query = DecisionQuery(graph_store=knowledge_graph,vector_store=vector_store if vector_store_features else None,@@ -247,7 +261,11 @@ class AgentContext:self.logger.warning(f"Failed to initialize enhanced decision tracking ({type(e).__name__})")- self._decision_recorder = DecisionRecorder(knowledge_graph)+ self._decision_recorder = DecisionRecorder(+ knowledge_graph,+ evaluators=self.evaluators,+ eval_config=self.eval_config,+ )self._decision_query = DecisionQuery(knowledge_graph)self._causal_analyzer = CausalChainAnalyzer(knowledge_graph)self._policy_engine = PolicyEngine(knowledge_graph)diff --git a/semantica/context/decision_recorder.py b/semantica/context/decision_recorder.pyindex 64256e3d..5a69ad83 100644--- a/semantica/context/decision_recorder.py+++ b/semantica/context/decision_recorder.py@@ -98,21 +98,101 @@ class DecisionRecorder:self,graph_store: GraphStore,embedding_generator: Optional[EmbeddingGenerator] = None,- provenance_manager: Optional[ProvenanceManager] = None+ provenance_manager: Optional[ProvenanceManager] = None,+ evaluators: Optional[List[str]] = None,+ eval_config: Optional[Dict[str, Any]] = None):"""Initialize DecisionRecorder.-+Args:graph_store: Graph database instance for storing decisionsembedding_generator: Optional embedding generator for semantic embeddingsprovenance_manager: Optional provenance manager for W3C PROV-O tracking+ evaluators: Optional list of semantica.evals evaluator names to run+ automatically on every recorded decision (e.g. ["decision_scores"]).+ When omitted, record_decision() behaves exactly as before.+ eval_config: Optional config dict passed to semantica.evals.evaluate(),+ keyed by evaluator name+ (e.g. {"decision_scores": {"policy_engine": pe}})++ Example Usage:+ >>> recorder = DecisionRecorder(+ ... graph_store=graph,+ ... evaluators=["decision_scores"],+ ... eval_config={"decision_scores": {"expected_outcome": "approved"}},+ ... )+ >>> recorder.record_decision(decision, entities=[], source_documents=[])+ >>> decision.metadata["eval_score"], decision.metadata["eval_passed"]"""self.graph_store = graph_storeself.embedding_generator = embedding_generatorself.provenance_manager = provenance_manager+ self.evaluators = evaluators+ self.eval_config = eval_config or {}self.logger = get_logger(__name__)-++ def _evaluate_and_enrich_decision(self, decision: Decision) -> None:+ """+ Run configured semantica.evals evaluators over a decision and store the+ result in its metadata. No-op when no evaluators are configured.++ Args:+ decision: Decision to evaluate; mutated in place (decision.metadata).+ """+ if not self.evaluators:+ return++ # Decision.metadata defaults to {} but callers may pass metadata=None+ # explicitly; normalize before writing eval_* keys below so recording+ # never crashes on that (mirrors record_decision()'s own tolerance+ # for a missing metadata dict).+ if decision.metadata is None:+ decision.metadata = {}++ case = {"id": decision.decision_id, "actual": decision}+ try:+ # Lazy import: semantica.evals is only exercised when evaluators=+ # is configured, and resolving it here (rather than at module+ # import time) lets callers/tests monkeypatch semantica.evals.evaluate.+ from ..evals import evaluate++ summary = evaluate(+ [case], evaluators=self.evaluators, config=self.eval_config+ )+ except Exception as exc:+ # Deliberate, narrow exception to just the evaluate() call: this+ # hook is an optional quality check, and a broken evaluator must+ # never prevent the decision itself from being recorded. Logs and+ # returns (does not re-raise). Per-evaluator failures are already+ # converted to CaseResult(status="error") inside evaluate();+ # reaching here means evaluate() itself failed outright.+ self.logger.warning(+ f"Decision evaluation failed for {decision.decision_id}: {exc}",+ exc_info=True,+ )+ return++ # Outside the try: a summary-shape change here is a bug in this hook,+ # not an evaluator failure, and must not be swallowed as one.+ case_result = summary.cases[0]+ if case_result.status == "error":+ # A named evaluator itself errored (unknown name, or it raised) --+ # evaluate() already downgraded that to CaseResult(status="error")+ # instead of propagating, so without this log the only trace is+ # eval_details on the stored decision.+ self.logger.warning(+ f"Decision evaluator(s) errored for {decision.decision_id}: "+ f"{case_result.details}"+ )+ scores = [metric.score for metric in case_result.metrics.values()]+ decision.metadata["eval_score"] = sum(scores) / len(scores) if scores else 0.0+ decision.metadata["eval_passed"] = case_result.status == "pass"+ decision.metadata["eval_details"] = {+ name: {"score": metric.score, "passed": metric.passed, "meta": metric.meta}+ for name, metric in case_result.metrics.items()+ }+def record_decision(self,decision: Decision,@@ -121,12 +201,12 @@ class DecisionRecorder:) -> str:"""Record decision with full context.-+Args:decision: Decision object to recordentities: List of entity IDs linked to this decisionsource_documents: List of source document identifiers-+Returns:Decision ID"""@@ -136,7 +216,12 @@ class DecisionRecorder:decision.reasoning_embedding = self.embedding_generator.generate(decision.reasoning)-++ # Run configured evaluators (opt-in) before persisting, so+ # eval_score/eval_passed/eval_details are stored with the decision.+ if self.evaluators:+ self._evaluate_and_enrich_decision(decision)+# Store decision in graph databaseself._store_decision_node(decision)diff --git a/tests/context/test_decision_eval_hook.py b/tests/context/test_decision_eval_hook.pynew file mode 100644index 00000000..d77ad7a1--- /dev/null+++ b/tests/context/test_decision_eval_hook.py@@ -0,0 +1,279 @@+"""+Tests for the Decision Evaluation Hook++This module tests the opt-in evaluators/eval_config wiring between+semantica.evals and DecisionRecorder / AgentContext.+"""++import logging+from datetime import datetime+from unittest.mock import Mock++import pytest++from semantica.context.agent_context import AgentContext+from semantica.context.decision_models import Decision+from semantica.context.decision_recorder import DecisionRecorder+from semantica.evals.types import CaseResult, EvalMetric, EvalSummary+++def _decision(**overrides):+ """Build a Decision that passes every decision_scores check by default."""+ base = dict(+ decision_id="eval-hook-d1",+ category="loan",+ scenario="mortgage application",+ reasoning="strong credit history",+ outcome="approved",+ confidence=0.95,+ timestamp=datetime(2026, 1, 1),+ decision_maker="loan_officer",+ metadata={"provenance": {"prov_record": "rid-1"}},+ )+ base.update(overrides)+ return Decision(**base)+++class TestDecisionRecorderEvalHook:+ """Test the opt-in evaluation hook on DecisionRecorder.record_decision()."""++ @pytest.fixture+ def mock_graph_store(self):+ """Mock graph store for testing."""+ mock_store = Mock()+ mock_store.execute_query = Mock()+ return mock_store++ def test_no_evaluators_configured_is_unchanged(self, mock_graph_store):+ """Backward compat: omitting evaluators= adds no eval_* metadata."""+ recorder = DecisionRecorder(graph_store=mock_graph_store)+ decision = _decision()++ decision_id = recorder.record_decision(decision, [], [])++ assert decision_id == decision.decision_id+ assert "eval_score" not in decision.metadata+ assert "eval_passed" not in decision.metadata+ assert "eval_details" not in decision.metadata++ def test_full_pass_enriches_metadata(self, mock_graph_store):+ """All decision_scores checks pass -> eval_score 1.0, eval_passed True."""+ recorder = DecisionRecorder(+ graph_store=mock_graph_store,+ evaluators=["decision_scores"],+ eval_config={"decision_scores": {"expected_outcome": "approved"}},+ )+ decision = _decision()++ recorder.record_decision(decision, [], [])++ assert decision.metadata["eval_score"] == 1.0+ assert decision.metadata["eval_passed"] is True+ assert list(decision.metadata["eval_details"].keys()) == ["decision_scores"]++ def test_failing_check_surfaces_in_metadata(self, mock_graph_store):+ """Empty reasoning fails a field check -> eval_passed False, named in details."""+ recorder = DecisionRecorder(+ graph_store=mock_graph_store,+ evaluators=["decision_scores"],+ )+ decision = _decision(reasoning="")++ recorder.record_decision(decision, [], [])++ assert decision.metadata["eval_passed"] is False+ assert decision.metadata["eval_score"] < 1.0+ assert (+ decision.metadata["eval_details"]["decision_scores"]["meta"]["reasoning"]+ is False+ )++ def test_none_metadata_does_not_crash_recording(self, mock_graph_store):+ """Decision(metadata=None) -> hook normalizes it instead of crashing."""+ recorder = DecisionRecorder(+ graph_store=mock_graph_store,+ evaluators=["decision_scores"],+ )+ decision = _decision(metadata=None)++ decision_id = recorder.record_decision(decision, [], [])++ assert decision_id == decision.decision_id+ assert decision.metadata["eval_passed"] is False # provenance check fails+ assert mock_graph_store.execute_query.called++ def test_policy_mismatch_surfaces_in_metadata(self, mock_graph_store):+ """PolicyEngine.check_compliance() False -> failing 'policy' check surfaced."""++ class FakePolicyEngine:+ def check_compliance(self, decision, policy_id):+ return False++ recorder = DecisionRecorder(+ graph_store=mock_graph_store,+ evaluators=["decision_scores"],+ eval_config={+ "decision_scores": {+ "policy_engine": FakePolicyEngine(),+ "policy_id": "p1",+ }+ },+ )+ decision = _decision()++ recorder.record_decision(decision, [], [])++ assert decision.metadata["eval_passed"] is False+ assert (+ decision.metadata["eval_details"]["decision_scores"]["meta"]["policy"]+ is False+ )++ def test_evaluator_failure_does_not_block_recording(+ self, mock_graph_store, monkeypatch, caplog+ ):+ """evaluate() itself raising -> decision still recorded, no eval_* keys."""+ monkeypatch.setattr(+ "semantica.evals.evaluate",+ Mock(side_effect=RuntimeError("boom")),+ )+ recorder = DecisionRecorder(+ graph_store=mock_graph_store,+ evaluators=["decision_scores"],+ )+ decision = _decision()++ with caplog.at_level(logging.WARNING):+ decision_id = recorder.record_decision(decision, [], [])++ assert decision_id == decision.decision_id+ assert "eval_score" not in decision.metadata+ assert "eval_passed" not in decision.metadata+ assert mock_graph_store.execute_query.called+ # The traceback must survive the log call, not just the message string.+ record = next(r for r in caplog.records if "Decision evaluation failed" in r.message)+ assert record.exc_info is not None++ def test_evaluator_error_status_is_logged(+ self, mock_graph_store, monkeypatch, caplog+ ):+ """A named evaluator erroring (unknown name, internal raise) -> logged,+ not just buried in eval_details on the stored decision."""+ error_summary = EvalSummary(+ total=1,+ passed=0,+ failed=0,+ errors=1,+ pass_rate=0.0,+ cases=[+ CaseResult(+ case_id="eval-hook-d1",+ status="error",+ metrics={"decision_scores": EvalMetric(0.0, False, {"error": "boom"})},+ details={"decision_scores": {"error": "boom"}},+ )+ ],+ )+ monkeypatch.setattr(+ "semantica.evals.evaluate", Mock(return_value=error_summary)+ )+ recorder = DecisionRecorder(+ graph_store=mock_graph_store,+ evaluators=["decision_scores"],+ )+ decision = _decision()++ with caplog.at_level(logging.WARNING):+ recorder.record_decision(decision, [], [])++ assert decision.metadata["eval_passed"] is False+ assert any(+ "evaluator(s) errored" in r.message for r in caplog.records+ )+++class TestAgentContextEvalHookWiring:+ """Test that AgentContext threads evaluators/eval_config into DecisionRecorder."""++ @pytest.fixture(autouse=True)+ def _stub_node_embedder(self, monkeypatch):+ """AgentContext(vector_store=..., knowledge_graph=...) constructs a real+ ContextRetriever, which eagerly builds a DecisionEmbeddingPipeline and a+ DecisionQuery, both of which construct NodeEmbedder(method="node2vec").+ NodeEmbedder raises ImportError when the optional `gensim` dependency+ (semantica[graph-embeddings]) isn't installed. These tests only check+ that evaluators/eval_config land on the DecisionRecorder, so stub+ NodeEmbedder out at both import sites rather than requiring gensim.+ """+ monkeypatch.setattr(+ "semantica.vector_store.decision_embedding_pipeline.NodeEmbedder", Mock()+ )+ monkeypatch.setattr("semantica.context.decision_query.NodeEmbedder", Mock())++ @pytest.fixture+ def mock_vector_store(self):+ """Mock vector store for testing."""+ mock_store = Mock()+ mock_store.add = Mock()+ mock_store.search = Mock(return_value=[])+ return mock_store++ @pytest.fixture+ def mock_knowledge_graph(self):+ """Mock knowledge graph for testing."""+ mock_graph = Mock()+ mock_graph.execute_query = Mock(return_value=[])+ return mock_graph++ def test_evaluators_threaded_into_decision_recorder(+ self, mock_vector_store, mock_knowledge_graph+ ):+ """Constructor-level evaluators/eval_config land on the recorder."""+ context = AgentContext(+ vector_store=mock_vector_store,+ knowledge_graph=mock_knowledge_graph,+ decision_tracking=True,+ evaluators=["decision_scores"],+ eval_config={"decision_scores": {"expected_outcome": "approved"}},+ )++ assert context._decision_recorder.evaluators == ["decision_scores"]+ assert context._decision_recorder.eval_config == {+ "decision_scores": {"expected_outcome": "approved"}+ }++ def test_evaluators_threaded_on_exception_fallback_path(+ self, mock_vector_store, mock_knowledge_graph, monkeypatch+ ):+ """Same wiring survives the DecisionQuery/-Analyzer init failure fallback."""+ # The success path constructs DecisionQuery once; on failure the+ # except block constructs it again as part of the fallback. Only+ # the first call should fail, so the fallback branch itself succeeds.+ monkeypatch.setattr(+ "semantica.context.agent_context.DecisionQuery",+ Mock(side_effect=[RuntimeError("boom"), Mock()]),+ )++ context = AgentContext(+ vector_store=mock_vector_store,+ knowledge_graph=mock_knowledge_graph,+ decision_tracking=True,+ evaluators=["decision_scores"],+ eval_config={"x": 1},+ )++ assert context._decision_recorder.evaluators == ["decision_scores"]+ assert context._decision_recorder.eval_config == {"x": 1}++ def test_no_evaluators_default_is_none(+ self, mock_vector_store, mock_knowledge_graph+ ):+ """Backward compat at the AgentContext layer: default is untouched."""+ context = AgentContext(+ vector_store=mock_vector_store,+ knowledge_graph=mock_knowledge_graph,+ decision_tracking=True,+ )++ assert context._decision_recorder.evaluators is None+ assert context._decision_recorder.eval_config == {}