Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(context): raise instead of silently returning False when compliance check fails (#1160)

cxzg007097c0d41db7c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c0a3fd77..b6a58baa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Changed
+
+- **`PolicyEngine.check_compliance` now raises `ProcessingError` for rules it cannot evaluate** (#1160, fixes #1159) by @cxzg007
+ - `check_compliance` previously swallowed evaluation failures and returned `False`, making an unevaluable rule — a `min_confidence` of `"high"` compared against a numeric confidence, an unhashable rule value, a policy loading error — indistinguishable from a policy violation. A rule that cannot be executed now raises `ProcessingError` from `semantica.utils.exceptions`, while `False` keeps its meaning of "evaluated and found non-compliant", including the case where the decision simply lacks the evidence a rule needs (absent metadata is non-compliance by policy)
+ - `False` continues to mean "evaluated and found non-compliant"; callers acting on a genuine non-compliant verdict are unaffected. Callers that previously received `False` as a silent stand-in for an operational failure (e.g. a graph-store error or malformed rule value) will now receive `ProcessingError` instead — wrap the call in `try/except ProcessingError` to handle that case separately, as documented in `docs/guides/policy-engine.md`
+ - `docs/guides/policy-engine.md` and `docs/guides/decision-intelligence.md` document the contract, and the `check_compliance` docstring states the design boundary between the two failure modes
+
### Added
- **Pluggable, persistent backend for `ExtractionCache`** (#1581) by @Besokus
@@ -308,11 +315,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Security
-- **Agno's `AgnoKnowledgeGraph.load_urls()` made outbound requests with no SSRF protection beyond a scheme check** (#1212) by @Sameer6305 — caller-supplied URLs went straight to `urllib.request.urlopen()`, unguarded against loopback/private addresses, cloud metadata endpoints (`169.254.169.254`), IPv6-internal addresses, hostnames resolving to private space, or redirects into any of the above. Found during a project-wide SSRF audit following #936/#959. Now routed through the shared `request_with_ssrf_guard()`; an unsafe URL is skipped rather than aborting the rest of the ingestion batch. `OpenClawKGTool` (operator-configured, intentionally allowed to target `localhost` for local deployments) gains scheme/malformed-URL validation as defense in depth, without restricting its legitimate private-network use case. 29 new Agno tests, 26 new OpenClaw tests, all passing alongside the 15 pre-existing Agno integration tests
-
-### Dependencies
-
-- Routine version bumps with no application-facing behavior change: `anthropic` 0.121.0→0.122.0 (#1045), `botocore` 1.43.69→1.43.73 (#1047), `agno` 2.8.7→2.9.0 (#1050), `google-genai` 2.17.0→2.18.1→2.19.0 (#1163, #1205), `lxml` 6.1.1→6.1.2 (#1197), `charset-normalizer` 3.5.0→3.5.1 (#1201), `pypickle` 2.0.1→2.0.2 (#1203)
## [0.6.6] - 2026-08-20
diff --git a/docs/guides/decision-intelligence.md b/docs/guides/decision-intelligence.md
index e097c20e..1c8505cd 100644
--- a/docs/guides/decision-intelligence.md
+++ b/docs/guides/decision-intelligence.md
@@ -294,6 +294,8 @@ else:
# → "Decision blocked — confidence 0.62 below policy minimum 0.80."
```
+A `False` return from `check_compliance` means the rules were evaluated and the decision did not satisfy them. If the check itself cannot be executed — for example, a policy rule that cannot be compared against the decision's data — the call raises `ProcessingError` instead of returning `False`, so an evaluation failure is never reported as a compliance verdict. See the [Policy Engine guide](policy-engine) for the full contract.
+
When a high-urgency situation requires bypassing the policy gate, record the exception with the approver identity and justification:
```python
@@ -607,6 +609,8 @@ d = Decision(
decision_maker = "credit_model_v3",
)
+# False = evaluated and non-compliant; if the check cannot run at
+# all, check_compliance raises ProcessingError (see policy-engine guide).
if engine.check_compliance(d, "lending_policy_v3"):
loan_id = context.record_decision(
category=d.category, scenario=d.scenario,
diff --git a/docs/guides/policy-engine.md b/docs/guides/policy-engine.md
index fc284518..2baf69e6 100644
--- a/docs/guides/policy-engine.md
+++ b/docs/guides/policy-engine.md
@@ -132,7 +132,7 @@ The policy is now a node in the graph. It has a version string, a creation times
## Checking a decision for compliance
-`check_compliance` takes a `Decision` object and the policy ID and returns a boolean.
+`check_compliance` takes a `Decision` object and the policy ID and returns a boolean: `True` if the decision complies with the policy, `False` if it was evaluated and found non-compliant. If the check itself cannot be executed — for example, a rule value that cannot be compared against the decision's metadata — `check_compliance` raises `ProcessingError` instead of returning `False`.
```python
from semantica.context import Decision
@@ -172,6 +172,23 @@ print(f"Compliant: {is_compliant}")
The engine returns `False`. The decision has not been rejected — it has been flagged. What happens next depends on your workflow. In some organisations, a non-compliant result simply blocks the write to the authoritative graph. In others, it triggers an exception process where a human approver reviews the evidence and signs off.
+### When the check itself fails
+
+A returned `False` is always a verdict: the rules ran, and the decision did not satisfy them. That includes the case where the decision simply lacks the evidence a rule needs — a `min_`/`max_`/`required_` rule targeting a metadata field the decision does not carry counts as non-compliant by policy.
+
+The separate case is a rule that cannot be evaluated at all, for instance a `min_confidence` of `"high"` that cannot be compared against a numeric decision confidence. Rather than reporting that as non-compliance, `check_compliance` raises `ProcessingError`, so an evaluation bug can never masquerade as a policy violation. If you need failures reported separately from verdicts, wrap the call:
+
+```python
+from semantica.utils.exceptions import ProcessingError
+
+try:
+ is_compliant = engine.check_compliance(decision, policy_id)
+except ProcessingError as e:
+ # The rules could not be evaluated — an operational error,
+ # not a compliance verdict.
+ print(f"Compliance check failed: {e}")
+```
+
---
## Recording a policy exception
diff --git a/semantica/context/policy_engine.py b/semantica/context/policy_engine.py
index 1bce0804..e6ad4597 100644
--- a/semantica/context/policy_engine.py
+++ b/semantica/context/policy_engine.py
@@ -72,6 +72,7 @@ from typing import Any, Dict, List, Optional, Tuple
import uuid
from ..graph_store import GraphStore
+from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
from .decision_models import Decision, Policy, PolicyException
@@ -384,7 +385,24 @@ class PolicyEngine:
policy_id: Policy ID to check against
Returns:
- True if compliant, False otherwise
+ True if the decision complies with the policy, False otherwise.
+ A returned ``False`` always means "evaluated and found
+ non-compliant" - including the case where the decision simply
+ lacks the evidence a rule needs (e.g. a metadata field targeted
+ by a ``min_``/``max_``/``required_`` rule is absent): absent
+ evidence is non-compliance by policy. Only a rule that cannot
+ be executed at all counts as "could not determine compliance"
+ (see ``ProcessingError`` below).
+
+ Raises:
+ ValueError: If the policy cannot be found.
+ ProcessingError: If the compliance check itself fails to execute
+ (e.g. malformed rules or metadata). This is deliberately
+ distinct from returning ``False``: a returned ``False`` means
+ "evaluated and found non-compliant", whereas a raised error
+ means "could not determine compliance". Conflating the two
+ would let evaluation bugs masquerade as policy violations,
+ which is unacceptable in an audit/compliance context.
"""
try:
policy = self.get_policy(policy_id)
@@ -395,7 +413,9 @@ class PolicyEngine:
raise
except Exception as e:
self.logger.exception("Failed to check compliance")
- return False
+ raise ProcessingError(
+ f"Compliance check failed for policy '{policy_id}': {e}"
+ ) from e
def record_policy_application(
self,
@@ -1004,24 +1024,29 @@ class PolicyEngine:
decision_data: Dict[str, Any],
rules: Dict[str, Any]
) -> bool:
- """Check compliance with given rules."""
- try:
- if "min_confidence" in rules:
- if decision_data.get("confidence", 0) < rules["min_confidence"]:
- return False
-
- if "allowed_outcomes" in rules:
- if decision_data.get("outcome", "") not in rules["allowed_outcomes"]:
- return False
-
- if "required_categories" in rules:
- if decision_data.get("category", "") not in rules["required_categories"]:
- return False
-
- return True
-
- except Exception:
- return False
+ """Check compliance with given rules.
+
+ Note:
+ Evaluation failures (e.g. malformed rule values such as a
+ non-numeric ``min_confidence``) are intentionally *not* caught
+ here. They propagate to :meth:`check_compliance`, which converts
+ them into a :class:`ProcessingError`, so that an execution failure
+ is never conflated with a legitimate non-compliant (``False``)
+ result.
+ """
+ if "min_confidence" in rules:
+ if decision_data.get("confidence", 0) < rules["min_confidence"]:
+ return False
+
+ if "allowed_outcomes" in rules:
+ if decision_data.get("outcome", "") not in rules["allowed_outcomes"]:
+ return False
+
+ if "required_categories" in rules:
+ if decision_data.get("category", "") not in rules["required_categories"]:
+ return False
+
+ return True
def _dict_to_policy(self, data: Dict[str, Any]) -> Policy:
"""Convert dictionary to Policy object."""
diff --git a/tests/context/test_policy_engine.py b/tests/context/test_policy_engine.py
index 3d24a75b..e89e31a2 100644
--- a/tests/context/test_policy_engine.py
+++ b/tests/context/test_policy_engine.py
@@ -352,7 +352,166 @@ class TestPolicyEngine:
with pytest.raises(ValueError, match="Policy.*not found"):
policy_engine.check_compliance(decision, "nonexistent_policy")
-
+
+ def test_check_compliance_raises_on_evaluation_error(
+ self, policy_engine, mock_graph_store
+ ):
+ """A failure while evaluating compliance must raise, not return False.
+
+ Returning False would conflate "checked and found non-compliant" with
+ "the check itself failed", which is dangerous in an audit/compliance
+ context. The engine must surface such failures as ProcessingError.
+ """
+ from semantica.context.decision_models import Decision
+ from semantica.utils.exceptions import ProcessingError
+
+ decision = Decision(
+ decision_id="decision_001",
+ category="credit_approval",
+ scenario="Credit limit increase",
+ reasoning="Customer meets all criteria",
+ outcome="approved",
+ confidence=0.9,
+ timestamp=datetime.now(),
+ decision_maker="ai_agent_001",
+ )
+
+ policy_id = "policy_001"
+
+ mock_graph_store.execute_query.return_value = [
+ {
+ "policy_id": policy_id,
+ "rules": {"min_credit_score": 650, "max_debt_ratio": 0.4},
+ }
+ ]
+
+ with patch.object(
+ policy_engine,
+ "_evaluate_compliance",
+ side_effect=RuntimeError("unexpected evaluation failure"),
+ ):
+ with pytest.raises(ProcessingError, match="Compliance check failed") as exc_info:
+ policy_engine.check_compliance(decision, policy_id)
+
+ assert isinstance(exc_info.value.__cause__, RuntimeError)
+
+ def test_check_compliance_raises_on_malformed_rule(
+ self, policy_engine, mock_graph_store
+ ):
+ """A malformed rule value must raise, not be swallowed into False.
+
+ This exercises the real evaluation path (no mocking of
+ ``_evaluate_compliance``): a non-numeric ``min_confidence`` triggers a
+ ``TypeError`` deep inside ``_check_compliance_with_rules``. That helper
+ must let the failure propagate so ``check_compliance`` reports it as a
+ ``ProcessingError`` rather than a spurious non-compliant verdict.
+ """
+ from semantica.context.decision_models import Decision
+ from semantica.utils.exceptions import ProcessingError
+
+ decision = Decision(
+ decision_id="decision_001",
+ category="credit_approval",
+ scenario="Credit limit increase",
+ reasoning="Customer meets all criteria",
+ outcome="approved",
+ confidence=0.9,
+ timestamp=datetime.now(),
+ decision_maker="ai_agent_001",
+ )
+
+ policy_id = "policy_001"
+
+ # min_confidence is malformed (str vs float) -> comparison raises.
+ mock_graph_store.execute_query.return_value = [
+ {"policy_id": policy_id, "rules": {"min_confidence": "high"}}
+ ]
+
+ with pytest.raises(ProcessingError, match="Compliance check failed"):
+ policy_engine.check_compliance(decision, policy_id)
+
+ def test_check_compliance_raises_when_check_rule_helper_fails(
+ self, policy_engine, mock_graph_store
+ ):
+ """A failure inside _check_compliance_with_rules must reach check_compliance.
+
+ ``allowed_outcomes`` is the only rule key that routes through the
+ ``_check_compliance_with_rules`` helper (keys starting with ``min_``,
+ ``max_``, or ``required_`` are handled by their own branches in
+ ``_evaluate_compliance``). Supplying a non-iterable value (``True``)
+ triggers a ``TypeError`` inside that helper. The old broad
+ ``except Exception: return False`` in ``_check_compliance_with_rules``
+ was removed by this PR, so the ``TypeError`` must propagate all the way
+ to ``check_compliance``, which wraps it as ``ProcessingError``.
+
+ This test exercises the real execution path without mocking
+ ``_evaluate_compliance``.
+ """
+ from semantica.context.decision_models import Decision
+ from semantica.utils.exceptions import ProcessingError
+
+ decision = Decision(
+ decision_id="decision_001",
+ category="credit_approval",
+ scenario="Credit limit increase",
+ reasoning="Customer meets all criteria",
+ outcome="approved",
+ confidence=0.9,
+ timestamp=datetime.now(),
+ decision_maker="ai_agent_001",
+ )
+
+ policy_id = "policy_001"
+
+ # allowed_outcomes=True is a bool (not iterable):
+ # "approved" not in True -> TypeError inside _check_compliance_with_rules.
+ mock_graph_store.execute_query.return_value = [
+ {"policy_id": policy_id, "rules": {"allowed_outcomes": True}}
+ ]
+
+ with pytest.raises(ProcessingError, match="Compliance check failed") as exc_info:
+ policy_engine.check_compliance(decision, policy_id)
+
+ assert isinstance(exc_info.value.__cause__, TypeError)
+
+ def test_check_compliance_raises_on_policy_lookup_failure(
+ self, policy_engine, mock_graph_store
+ ):
+ """An infrastructure failure during policy lookup must raise ProcessingError.
+
+ Before this fix, a graph-store error inside ``get_policy()`` was caught
+ by ``check_compliance``'s broad ``except Exception`` and silently
+ returned as ``False``, making an infrastructure failure
+ indistinguishable from a genuine non-compliant verdict. The call must
+ now raise ``ProcessingError`` so that an operational failure is never
+ reported as a compliance verdict.
+ """
+ from semantica.context.decision_models import Decision
+ from semantica.utils.exceptions import ProcessingError
+
+ decision = Decision(
+ decision_id="decision_001",
+ category="credit_approval",
+ scenario="Credit limit increase",
+ reasoning="Customer meets all criteria",
+ outcome="approved",
+ confidence=0.9,
+ timestamp=datetime.now(),
+ decision_maker="ai_agent_001",
+ )
+
+ policy_id = "policy_001"
+
+ # Simulate a persistent infrastructure failure: every execute_query call raises.
+ mock_graph_store.execute_query.side_effect = RuntimeError(
+ "DB connection pool exhausted"
+ )
+
+ with pytest.raises(ProcessingError, match="Compliance check failed") as exc_info:
+ policy_engine.check_compliance(decision, policy_id)
+
+ assert isinstance(exc_info.value.__cause__, RuntimeError)
+
def test_record_policy_application_success(self, policy_engine, mock_graph_store):
"""Test successful policy application recording."""
decision_id = "decision_001"