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
fix(agno): make _eval_rule raise instead of silently returning compliant=True on unevaluable rules (closes #778) (#822)
Sameer Kadam76edaeb1c000
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 22e57a25..b03a6065 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -43,6 +43,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **`AgnoDecisionKit.check_policy` silently treated unevaluable policy rules as compliant** (#778, #822) by @Sameer6305+ - `_eval_rule()` previously `return`ed `True` when a rule referenced a field missing from the decision payload, or when the rule string didn't match the expected `<field> <op> <value>` format — the docstring's claim that exceptions never silently return `compliant=True` didn't cover this, since neither path raised+ - Both cases now raise `ValueError` instead, which routes through `check_policy`'s existing exception handler and records a `warnings` entry (e.g. `"Could not evaluate rule 'minimum_score >= 0.9': rule references undefined field 'minimum_score'"`) instead of disappearing with no signal+ - `violations`/`compliant` are unaffected — an unevaluable rule is not counted as a violation, since it's genuinely unknown whether it would have passed; this matches the existing `compliant`/`violations`/`warnings` shape already used by `ContextGraph.enforce_decision_policy`+ - This is additive: `warnings` was already part of the return contract and populated for other exception cases, so no caller that only checks `compliant` is affected, and no existing test asserts `warnings == []` for a payload that hits either of these paths+ - **Follow-up review fix**: `check_policy` decoded `policy_rules` with `json.loads` and iterated the result without checking it was actually a list; a JSON-encoded bare string (e.g. `policy_rules='"confidence >= 0.7"'`) decodes to a `str`, so iterating it evaluated one "rule" per character — combined with the fix above, an 18-character rule string produced 17 warnings instead of being treated as the single rule it was meant to be. A decoded string is now wrapped as a single-element rule list; any other non-list shape (number, object, etc.) or non-string list element now produces exactly one `warnings` entry instead of silently misbehaving or being iterated character-by-character+ - **Follow-up review fix**: `_eval_rule` used `data.get(field) is None` to detect a missing field, which can't distinguish a genuinely absent key from a key explicitly present with a JSON `null` value — both produced the same "undefined field" warning, misdiagnosing nullable fields. Field presence is now checked with `field not in data` first; a present-but-`null` value now raises a distinct `"field {field!r} is null — cannot evaluate rule"` message instead of the misleading "undefined field" one+ - **Follow-up review fix**: `check_policy` only checked that `decision_data` was valid JSON, not that it decoded to an object. When it decoded to a list, `field not in data` silently became list-*membership* testing instead of a key check (e.g. `"confidence" not in ["confidence", 0.95]` is `False`), so a matching rule fell through to `data["confidence"]`, which raised a raw, confusing `TypeError: list indices must be integers or slices, not str` instead of any meaningful diagnostic; numbers/strings/bools produced similarly opaque `TypeError`s. `check_policy` now rejects any `decision_data` that doesn't decode to a JSON object upfront with a single clear `violations` entry, the same way it already rejects malformed JSON+ - Added 15 tests to `tests/integrations/agno/test_decision_kit.py` covering the missing-field case (the issue's traced example), the malformed-rule-string case, the bare-JSON-string `policy_rules` amplification case, non-list/non-string `policy_rules` shapes, the missing-key-vs-null-value distinction, non-object `decision_data` shapes (list/number/string/bool/null), and regression checks confirming normal rule evaluation on present fields is unchanged+- **No cycle detection for SKOS concepts at write time** (#774, #819) by @mikemikimike, reviewed by @Sameer6305 and @KaifAhmad1- Added cycle detection (`validate_skos_hierarchy`) for `skos:broader` and `skos:narrower` relationships in `ContextGraph.add_edge()` and `ContextGraph.add_edges()`, preventing direct 2-node cycles, self-loops, and multi-hop hierarchy cycles- Added `GraphSession.add_nodes_and_edges()` to validate SKOS hierarchy edges upfront under lock before node insertion, preventing partial-write leaks where nodes remain after a cyclic edge is rejecteddiff --git a/integrations/agno/decision_kit.py b/integrations/agno/decision_kit.pyindex cc64e9c6..6157b95b 100644--- a/integrations/agno/decision_kit.py+++ b/integrations/agno/decision_kit.py@@ -310,18 +310,33 @@ class AgnoDecisionKit(_ToolkitBase): # type: ignore[misc]Rules are evaluated inline using simple comparison expressions. Thisavoids misuse of ``PolicyEngine.check_compliance`` (which requires astored ``Decision`` + ``policy_id``) and ensures exceptions never- silently return ``compliant=True``.+ silently return ``compliant=True``. A rule that references a field+ missing from ``decision_data``, a field whose value is JSON ``null``,+ or a rule that doesn't match the expected ``<field> <op> <value>``+ format, cannot be evaluated — it is recorded in ``warnings`` (not+ ``violations``) since we don't know whether it would have passed or+ failed. These are reported as distinct messages (missing key vs.+ null value) so the warning is actionable.Parameters----------decision_data:JSON string describing the decision (must include ``category``,- ``outcome``, ``confidence`` keys at minimum).+ ``outcome``, ``confidence`` keys at minimum). Must decode to a+ JSON object — any other shape (list, number, string, bool) is+ rejected with a single ``violations`` entry, the same as+ malformed JSON, rather than being passed through to per-rule+ evaluation where it would produce confusing internal errors.policy_rules:JSON list of rule strings, e.g.``'["confidence >= 0.7", "category != \\"test\\""]'``.Each rule is a simple comparison: ``<field> <op> <value>``where op is one of ``>=``, ``<=``, ``!=``, ``==``, ``>``, ``<``.+ A JSON-encoded bare string (e.g. ``'"confidence >= 0.7"'``) is+ treated as a single rule. Any other decoded JSON shape (e.g. a+ number or object), or a non-string list element, is recorded as+ one ``warnings`` entry and otherwise ignored rather than being+ iterated character-by-character.Returns-------@@ -339,15 +354,46 @@ class AgnoDecisionKit(_ToolkitBase): # type: ignore[misc]})+ if not isinstance(data, dict):+ return json.dumps(+ {+ "compliant": False,+ "violations": [+ f"decision_data must decode to a JSON object, "+ f"got {type(data).__name__}: {data!r}"+ ],+ "warnings": [],+ }+ )++ violations: List[str] = []+ warnings: List[str] = []+rules: List[str] = []if policy_rules:try:- rules = json.loads(policy_rules)+ parsed_rules = json.loads(policy_rules)except json.JSONDecodeError:rules = [r.strip() for r in policy_rules.split(",") if r.strip()]-- violations: List[str] = []- warnings: List[str] = []+ else:+ if isinstance(parsed_rules, str):+ # A single rule encoded as a bare JSON string, e.g.+ # policy_rules='"confidence >= 0.7"'. Treat it as one+ # rule rather than iterating it character-by-character.+ rules = [parsed_rules]+ elif isinstance(parsed_rules, list):+ for item in parsed_rules:+ if isinstance(item, str):+ rules.append(item)+ else:+ warnings.append(+ f"Ignoring non-string policy rule entry: {item!r}"+ )+ else:+ warnings.append(+ f"policy_rules must decode to a JSON list of rule strings, "+ f"got {type(parsed_rules).__name__}: {parsed_rules!r}"+ )for rule in rules:try:@@ -367,14 +413,23 @@ class AgnoDecisionKit(_ToolkitBase): # type: ignore[misc])def _eval_rule(self, rule: str, data: Dict[str, Any]) -> bool:- """Evaluate a simple comparison rule (``field op value``) against data."""+ """+ Evaluate a simple comparison rule (``field op value``) against data.++ Raises ``ValueError`` when the rule cannot be evaluated (unrecognised+ format, the referenced field is absent from ``data``, or the field's+ value is JSON ``null``) so that ``check_policy`` records it as a+ ``warnings`` entry instead of silently treating it as passed.+ """m = re.match(r"(\w+)\s*(>=|<=|!=|==|>|<)\s*(.+)", rule.strip())if not m:- return True # unrecognised format — pass through+ raise ValueError(f"unrecognised rule format: {rule!r}")field, op, val_str = m.group(1), m.group(2), m.group(3).strip().strip("\"'")- actual = data.get(field)+ if field not in data:+ raise ValueError(f"rule references undefined field {field!r}")+ actual = data[field]if actual is None:- return True # field absent — cannot evaluate+ raise ValueError(f"field {field!r} is null — cannot evaluate rule")try:val: Any = type(actual)(val_str)except (ValueError, TypeError):diff --git a/tests/integrations/agno/test_decision_kit.py b/tests/integrations/agno/test_decision_kit.pyindex 3f13b6c0..0427a6cc 100644--- a/tests/integrations/agno/test_decision_kit.py+++ b/tests/integrations/agno/test_decision_kit.py@@ -257,6 +257,180 @@ class TestCheckPolicy(unittest.TestCase):violations = result.get("violations", [])self.assertGreater(len(violations), 0)+ def test_decision_data_list_rejected_with_clear_violation(self):+ # decision_data decoding to a list previously passed the isinstance+ # check silently, then `field not in data` did list-membership+ # (not key) testing and `data[field]` raised a raw, confusing+ # TypeError deep inside _eval_rule. Must now be rejected upfront.+ result = json.loads(self.kit.check_policy(+ json.dumps(["confidence", 0.95]),+ json.dumps(["confidence >= 0.9"]),+ ))+ self.assertFalse(result["compliant"])+ self.assertEqual(len(result["violations"]), 1)+ self.assertIn("JSON object", result["violations"][0])+ self.assertEqual(result["warnings"], [])++ def test_decision_data_number_rejected_with_clear_violation(self):+ result = json.loads(self.kit.check_policy(+ json.dumps(42),+ json.dumps(["confidence >= 0.9"]),+ ))+ self.assertFalse(result["compliant"])+ self.assertEqual(len(result["violations"]), 1)+ self.assertIn("JSON object", result["violations"][0])++ def test_decision_data_string_rejected_with_clear_violation(self):+ result = json.loads(self.kit.check_policy(+ json.dumps("confidence"),+ json.dumps(["confidence >= 0.9"]),+ ))+ self.assertFalse(result["compliant"])+ self.assertEqual(len(result["violations"]), 1)+ self.assertIn("JSON object", result["violations"][0])++ def test_decision_data_bool_rejected_with_clear_violation(self):+ result = json.loads(self.kit.check_policy(+ json.dumps(True),+ json.dumps(["confidence >= 0.9"]),+ ))+ self.assertFalse(result["compliant"])+ self.assertEqual(len(result["violations"]), 1)+ self.assertIn("JSON object", result["violations"][0])++ def test_decision_data_null_rejected_with_clear_violation(self):+ result = json.loads(self.kit.check_policy(+ json.dumps(None),+ json.dumps(["confidence >= 0.9"]),+ ))+ self.assertFalse(result["compliant"])+ self.assertEqual(len(result["violations"]), 1)+ self.assertIn("JSON object", result["violations"][0])++ def test_rule_referencing_missing_field_warns_not_silently_compliant(self):+ # Issue #778 traced example: rule references a field absent from the+ # decision payload. This must NOT be silently treated as compliant+ # with no signal — it should surface in `warnings`.+ decision = json.dumps({"confidence": 0.95})+ rules = json.dumps(["minimum_score >= 0.9"])+ result = json.loads(self.kit.check_policy(decision, policy_rules=rules))++ self.assertTrue(result["compliant"])+ self.assertEqual(result["violations"], [])+ self.assertEqual(len(result["warnings"]), 1)+ self.assertIn("minimum_score", result["warnings"][0])+ self.assertIn("minimum_score >= 0.9", result["warnings"][0])++ def test_malformed_rule_string_warns_not_silently_compliant(self):+ # A rule that doesn't match `<field> <op> <value>` must also warn+ # instead of silently passing through as compliant.+ decision = json.dumps({"confidence": 0.95})+ rules = json.dumps(["not a valid rule!!!"])+ result = json.loads(self.kit.check_policy(decision, policy_rules=rules))++ self.assertTrue(result["compliant"])+ self.assertEqual(result["violations"], [])+ self.assertEqual(len(result["warnings"]), 1)+ self.assertIn("not a valid rule!!!", result["warnings"][0])++ def test_valid_rule_against_present_field_still_evaluates_normally(self):+ # Sanity check: a rule referencing a field that IS present is+ # unaffected by the missing-field fix and evaluates as before.+ decision = json.dumps({"confidence": 0.95})+ rules = json.dumps(["confidence >= 0.9"])+ result = json.loads(self.kit.check_policy(decision, policy_rules=rules))++ self.assertTrue(result["compliant"])+ self.assertEqual(result["violations"], [])+ self.assertEqual(result["warnings"], [])++ def test_valid_rule_violation_against_present_field(self):+ decision = json.dumps({"confidence": 0.5})+ rules = json.dumps(["confidence >= 0.9"])+ result = json.loads(self.kit.check_policy(decision, policy_rules=rules))++ self.assertFalse(result["compliant"])+ self.assertEqual(len(result["violations"]), 1)+ self.assertEqual(result["warnings"], [])++ def test_bare_json_string_policy_rules_treated_as_single_rule(self):+ # policy_rules='"confidence >= 0.9"' decodes to a plain str via+ # json.loads. Must be treated as ONE rule, not iterated character+ # by character (which previously produced one warning per char).+ decision = json.dumps({"confidence": 0.95})+ rules = json.dumps("confidence >= 0.9") # -> '"confidence >= 0.9"'+ result = json.loads(self.kit.check_policy(decision, policy_rules=rules))++ self.assertTrue(result["compliant"])+ self.assertEqual(result["violations"], [])+ self.assertEqual(result["warnings"], [])++ def test_bare_json_string_policy_rules_missing_field_warns_once(self):+ decision = json.dumps({"confidence": 0.95})+ rules = json.dumps("minimum_score >= 0.9")+ result = json.loads(self.kit.check_policy(decision, policy_rules=rules))++ self.assertTrue(result["compliant"])+ self.assertEqual(result["violations"], [])+ self.assertEqual(len(result["warnings"]), 1)+ self.assertIn("minimum_score", result["warnings"][0])++ def test_non_list_non_string_policy_rules_produces_single_warning(self):+ # policy_rules is valid JSON but decodes to a number/object, not a+ # list of rule strings. Must produce exactly one warning, not crash+ # or silently no-op.+ decision = json.dumps({"confidence": 0.95})+ rules = json.dumps(42)+ result = json.loads(self.kit.check_policy(decision, policy_rules=rules))++ self.assertTrue(result["compliant"])+ self.assertEqual(result["violations"], [])+ self.assertEqual(len(result["warnings"]), 1)+ self.assertIn("policy_rules", result["warnings"][0])++ def test_non_string_list_elements_warn_and_are_skipped(self):+ # A list containing a non-string entry should warn about that entry+ # specifically and continue evaluating the valid string entries.+ decision = json.dumps({"confidence": 0.5})+ rules = json.dumps(["confidence >= 0.9", 123, None])+ result = json.loads(self.kit.check_policy(decision, policy_rules=rules))++ self.assertFalse(result["compliant"])+ self.assertEqual(len(result["violations"]), 1)+ self.assertEqual(len(result["warnings"]), 2)++ def test_missing_key_and_null_value_produce_distinct_warnings(self):+ # dict.get(field) can't distinguish an absent key from a key present+ # with JSON null. `minimum_score` is truly absent; `flagged_reason`+ # is present but explicitly null. Both are unevaluable, but the+ # warning text must say something different for each so the+ # diagnosis is accurate rather than always claiming "undefined".+ decision = json.dumps({"confidence": 0.95, "flagged_reason": None})+ rules = json.dumps(["minimum_score >= 0.9", "flagged_reason != none"])+ result = json.loads(self.kit.check_policy(decision, policy_rules=rules))++ self.assertTrue(result["compliant"])+ self.assertEqual(result["violations"], [])+ self.assertEqual(len(result["warnings"]), 2)++ missing_warning = next(w for w in result["warnings"] if "minimum_score" in w)+ null_warning = next(w for w in result["warnings"] if "flagged_reason" in w)++ self.assertIn("undefined field", missing_warning)+ self.assertNotIn("undefined field", null_warning)+ self.assertIn("null", null_warning)++ def test_field_present_with_null_value_alone(self):+ decision = json.dumps({"score": None})+ rules = json.dumps(["score >= 0.9"])+ result = json.loads(self.kit.check_policy(decision, policy_rules=rules))++ self.assertTrue(result["compliant"])+ self.assertEqual(result["violations"], [])+ self.assertEqual(len(result["warnings"]), 1)+ self.assertIn("null", result["warnings"][0])+ self.assertNotIn("undefined field", result["warnings"][0])+class TestGetDecisionSummary(unittest.TestCase):