Coverage for app / inference / rule_vocabulary.py: 92%
469 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""
2The rule vocabulary, as svc-ai enforces it.
4svc-core owns the authoritative definition in ``app.services.rules`` and
5serves it to the rule builder; this is the enforcement-side mirror. The two
6services do not share code — they are separate images with separate
7dependency trees — so the mirror is maintained by hand and pinned by test:
8``tests/inference/test_rule_vocabulary.py`` here and
9``tests/test_rule_vocabulary.py`` in svc-core both assert the same explicit
10key lists. Widen one side only and the other's test fails, which is the
11point: a field svc-core offers in the builder but svc-ai cannot evaluate is a
12rule that silently stops being enforced the moment execution moves inside a
13LangGraph run.
15The quota and evidence actions are absent: they read svc-core's usage ledger
16and evaluations, and svc-core resolves them before this service is called.
18Three registries, one class per entry:
20``Operator`` How two values are compared.
21``Field`` What a condition can ask about, and how to resolve it from the
22 inference context.
23``Action`` What a matched rule does, and the parameters it takes.
24"""
26from __future__ import annotations
28import logging
29import re
30from abc import ABC, abstractmethod
31from dataclasses import dataclass
32from dataclasses import field as dataclass_field
33from enum import StrEnum
34from functools import lru_cache
35from typing import Any, ClassVar
37from app.inference import pii
39logger = logging.getLogger(__name__)
42class ValueType(StrEnum):
43 """The shape of a value, on both sides of a comparison."""
45 text = "text"
46 number = "number"
47 enum = "enum"
48 boolean = "boolean"
49 list = "list"
50 none = "none"
53class Phase(StrEnum):
54 """When a condition is evaluated, and therefore what it can see."""
56 input = "input"
57 output = "output"
60#: Mirrors svc-core. `re` has no match timeout, so bounding the pattern and
61#: the text it scans is the ReDoS defence — rules can be model-authored.
62MAX_PATTERN_LENGTH = 512
63MAX_REGEX_INPUT_LENGTH = 100_000
66# ─── PII ──────────────────────────────────────────────────────────────────────
67#
68# Detection is ``app.inference.pii``, the same file svc-core carries, so a value
69# either service redacts the other redacts too — behind the same placeholder,
70# because both derive the placeholder key from ``INTERNAL_JWT_SECRET`` and key
71# it to the invoking user. ``filter_pii`` / ``detect_pii`` / ``redact`` stay
72# importable from here, where callers have always found them.
74filter_pii = pii.filter_pii
75detect_pii = pii.detect_pii
76redact = pii.redact
79@lru_cache(maxsize=1)
80def placeholder_key() -> bytes:
81 """This deployment's placeholder key — svc-core derives the same one."""
82 from app.common.settings import get_settings
84 return pii.placeholder_key(get_settings().INTERNAL_JWT_SECRET)
87def redactor_for(config: dict[str, Any], context: dict[str, Any]) -> pii.Redactor:
88 """The redaction one action block asks for: its ``kinds``, keyed to the
89 invoking user."""
90 kinds, unknown = pii.parse_kinds((config or {}).get("kinds"))
91 if unknown:
92 logger.warning(
93 "PII rule names kinds the detectors do not know (%s) — ignored",
94 ", ".join(unknown),
95 )
96 owner = (context or {}).get("user_id")
97 return pii.Redactor(
98 kinds, key=placeholder_key(), owner=str(owner) if owner else None
99 )
102def redaction_outcome(
103 action_type: str,
104 text: str,
105 config: dict[str, Any] | None = None,
106 context: dict[str, Any] | None = None,
107) -> ActionOutcome:
108 """One redaction pass, as an event that says whether it did anything.
110 ``changed`` is what separates "removed two email addresses" from "ran and
111 found nothing to remove" once svc-core records this. Actions that always
112 do something omit the flag; it defaults to True there. Kinds and counts
113 travel; the values never do.
114 """
115 redacted, counts = redactor_for(config or {}, context or {}).redact(text)
116 event: dict[str, Any] = {"action": action_type, "changed": bool(counts)}
117 if counts:
118 event["redacted"] = counts
119 return ActionOutcome(text=redacted, events=[event])
122# ─── Operators ────────────────────────────────────────────────────────────────
125class Operator(ABC):
126 """Base class for every comparison a condition can make."""
128 key: ClassVar[str]
129 applies_to: ClassVar[frozenset[ValueType]]
131 @abstractmethod
132 def evaluate(self, actual: Any, expected: Any) -> bool:
133 """True when ``actual`` satisfies this comparison."""
136_OPERATORS: dict[str, Operator] = {}
139def register_operator(cls: type[Operator]) -> type[Operator]:
140 instance = cls()
141 if instance.key in _OPERATORS:
142 raise RuntimeError(f"Operator '{instance.key}' is already registered.")
143 _OPERATORS[instance.key] = instance
144 return cls
147def get_operator(key: str) -> Operator | None:
148 return _OPERATORS.get(key)
151def operator_keys() -> frozenset[str]:
152 return frozenset(_OPERATORS)
155def _text(value: Any) -> str:
156 return str(value).lower()
159def _number(value: Any) -> float | None:
160 """Numeric form, rejecting booleans — True is not a token count."""
161 if isinstance(value, bool):
162 return None
163 try:
164 return float(value)
165 except (TypeError, ValueError):
166 return None
169def _as_list(value: Any) -> list[str]:
170 if isinstance(value, (list, tuple, set, frozenset)):
171 return [_text(item).strip() for item in value]
172 return [part.strip() for part in _text(value).split(",") if part.strip()]
175def _search(pattern: Any, actual: Any) -> bool | None:
176 """Run a regex, or None when the pattern is unusable."""
177 text = str(pattern)
178 if len(text) > MAX_PATTERN_LENGTH:
179 logger.warning(
180 "Rule condition regex is %d characters, over the %d limit — "
181 "condition will never match.",
182 len(text),
183 MAX_PATTERN_LENGTH,
184 )
185 return None
186 try:
187 compiled = re.compile(text, re.IGNORECASE)
188 except re.error as exc:
189 logger.warning(
190 "Rule condition regex %r is invalid (%s) — condition will never match.",
191 text,
192 exc,
193 )
194 return None
195 return compiled.search(str(actual)[:MAX_REGEX_INPUT_LENGTH]) is not None
198_TEXTUAL: frozenset[ValueType] = frozenset(
199 {ValueType.text, ValueType.enum, ValueType.boolean}
200)
201_TEXTUAL_OR_NUMERIC: frozenset[ValueType] = _TEXTUAL | {ValueType.number}
204@register_operator
205class EqualsOperator(Operator):
206 key = "eq"
207 applies_to = _TEXTUAL_OR_NUMERIC
209 def evaluate(self, actual: Any, expected: Any) -> bool:
210 left, right = _number(actual), _number(expected)
211 if left is not None and right is not None:
212 return left == right
213 return _text(actual) == _text(expected)
216@register_operator
217class NotEqualsOperator(Operator):
218 key = "neq"
219 applies_to = _TEXTUAL_OR_NUMERIC
221 def evaluate(self, actual: Any, expected: Any) -> bool:
222 return not EqualsOperator().evaluate(actual, expected)
225@register_operator
226class ContainsOperator(Operator):
227 key = "contains"
228 applies_to = _TEXTUAL
230 def evaluate(self, actual: Any, expected: Any) -> bool:
231 return _text(expected) in _text(actual)
234@register_operator
235class NotContainsOperator(Operator):
236 key = "not_contains"
237 applies_to = _TEXTUAL
239 def evaluate(self, actual: Any, expected: Any) -> bool:
240 return _text(expected) not in _text(actual)
243@register_operator
244class StartsWithOperator(Operator):
245 key = "starts_with"
246 applies_to = _TEXTUAL
248 def evaluate(self, actual: Any, expected: Any) -> bool:
249 return _text(actual).startswith(_text(expected))
252@register_operator
253class EndsWithOperator(Operator):
254 key = "ends_with"
255 applies_to = _TEXTUAL
257 def evaluate(self, actual: Any, expected: Any) -> bool:
258 return _text(actual).endswith(_text(expected))
261@register_operator
262class MatchesOperator(Operator):
263 key = "matches"
264 applies_to = _TEXTUAL
266 def evaluate(self, actual: Any, expected: Any) -> bool:
267 return _search(expected, actual) is True
270@register_operator
271class NotMatchesOperator(Operator):
272 key = "not_matches"
273 applies_to = _TEXTUAL
275 def evaluate(self, actual: Any, expected: Any) -> bool:
276 # An unusable pattern is inert for both polarities — a broken negative
277 # rule must not start firing on everything.
278 return _search(expected, actual) is False
281class _NumericOperator(Operator):
282 applies_to = frozenset({ValueType.number})
284 def evaluate(self, actual: Any, expected: Any) -> bool:
285 left, right = _number(actual), _number(expected)
286 if left is None or right is None:
287 logger.warning(
288 "Rule condition compares %r %s %r, which is not numeric — "
289 "condition will never match.",
290 actual,
291 self.key,
292 expected,
293 )
294 return False
295 return self.compare(left, right)
297 @abstractmethod
298 def compare(self, left: float, right: float) -> bool: ...
301@register_operator
302class GreaterThanOperator(_NumericOperator):
303 key = "gt"
305 def compare(self, left: float, right: float) -> bool:
306 return left > right
309@register_operator
310class GreaterOrEqualOperator(_NumericOperator):
311 key = "gte"
313 def compare(self, left: float, right: float) -> bool:
314 return left >= right
317@register_operator
318class LessThanOperator(_NumericOperator):
319 key = "lt"
321 def compare(self, left: float, right: float) -> bool:
322 return left < right
325@register_operator
326class LessOrEqualOperator(_NumericOperator):
327 key = "lte"
329 def compare(self, left: float, right: float) -> bool:
330 return left <= right
333@register_operator
334class InOperator(Operator):
335 key = "in"
336 applies_to = _TEXTUAL_OR_NUMERIC
338 def evaluate(self, actual: Any, expected: Any) -> bool:
339 return _text(actual) in _as_list(expected)
342@register_operator
343class NotInOperator(Operator):
344 key = "not_in"
345 applies_to = _TEXTUAL_OR_NUMERIC
347 def evaluate(self, actual: Any, expected: Any) -> bool:
348 return _text(actual) not in _as_list(expected)
351@register_operator
352class HasAnyOperator(Operator):
353 key = "has_any"
354 applies_to = frozenset({ValueType.list})
356 def evaluate(self, actual: Any, expected: Any) -> bool:
357 return bool(set(_as_list(actual)) & set(_as_list(expected)))
360@register_operator
361class HasAllOperator(Operator):
362 key = "has_all"
363 applies_to = frozenset({ValueType.list})
365 def evaluate(self, actual: Any, expected: Any) -> bool:
366 wanted = set(_as_list(expected))
367 return bool(wanted) and wanted <= set(_as_list(actual))
370@register_operator
371class HasNoneOperator(Operator):
372 key = "has_none"
373 applies_to = frozenset({ValueType.list})
375 def evaluate(self, actual: Any, expected: Any) -> bool:
376 return not (set(_as_list(actual)) & set(_as_list(expected)))
379# ─── Fields ───────────────────────────────────────────────────────────────────
382class Field(ABC):
383 """Base class for every value a condition can be written against."""
385 key: ClassVar[str]
386 value_type: ClassVar[ValueType]
387 phases: ClassVar[frozenset[Phase]]
389 @abstractmethod
390 def resolve(self, context: dict[str, Any]) -> Any:
391 """The field's value for this invocation, or None if unavailable."""
394_FIELDS: dict[str, Field] = {}
396BOTH_PHASES: frozenset[Phase] = frozenset({Phase.input, Phase.output})
399def register_field(cls: type[Field]) -> type[Field]:
400 instance = cls()
401 if instance.key in _FIELDS:
402 raise RuntimeError(f"Condition field '{instance.key}' is already registered.")
403 _FIELDS[instance.key] = instance
404 return cls
407def get_field(key: str) -> Field | None:
408 return _FIELDS.get(key)
411def field_keys() -> frozenset[str]:
412 return frozenset(_FIELDS)
415def supports(field: Field, operator: Operator) -> bool:
416 return field.value_type in operator.applies_to
419def _passthrough(context: dict[str, Any], *keys: str) -> Any:
420 """First non-None value among ``keys`` — call sites name things differently."""
421 for key in keys:
422 value = context.get(key)
423 if value is not None:
424 return value
425 return None
428_TOKENISER = None
431def _count_tokens(text: str) -> int:
432 """Token count for ``text``, falling back to an estimate.
434 tiktoken reaches svc-ai transitively through litellm rather than as a
435 declared dependency, so this must survive its absence: a governance rule
436 that silently stops being evaluated is worse than one evaluated against
437 an approximation.
438 """
439 global _TOKENISER
440 if not text:
441 return 0
442 if _TOKENISER is None:
443 try:
444 import tiktoken
446 _TOKENISER = tiktoken.get_encoding("cl100k_base")
447 except Exception: # noqa: BLE001 — a missing tokeniser must not fail the turn
448 logger.warning(
449 "tiktoken unavailable — token-count conditions will use an estimate"
450 )
451 _TOKENISER = False
452 if _TOKENISER is False:
453 return max(1, len(text) // 4)
454 return len(_TOKENISER.encode(text))
457@register_field
458class AlwaysField(Field):
459 key = "always"
460 value_type = ValueType.none
461 phases = BOTH_PHASES
463 def resolve(self, context: dict[str, Any]) -> Any:
464 return True
467@register_field
468class PromptField(Field):
469 key = "prompt"
470 value_type = ValueType.text
471 phases = BOTH_PHASES
473 def resolve(self, context: dict[str, Any]) -> Any:
474 return context.get("prompt")
477@register_field
478class ResponseField(Field):
479 key = "response"
480 value_type = ValueType.text
481 phases = frozenset({Phase.output})
483 def resolve(self, context: dict[str, Any]) -> Any:
484 return context.get("response")
487def _phase_text(context: dict[str, Any]) -> str | None:
488 """The response in the output phase, the prompt in the input phase."""
489 text = context.get("response")
490 if text is None:
491 text = context.get("prompt")
492 return None if text is None else str(text)
495@register_field
496class PiiDetectedField(Field):
497 key = "pii_detected"
498 value_type = ValueType.boolean
499 phases = BOTH_PHASES
501 def resolve(self, context: dict[str, Any]) -> Any:
502 text = _phase_text(context)
503 return None if text is None else detect_pii(text)
506@register_field
507class PiiTypesField(Field):
508 """Every kind of personal data present — default or not."""
510 key = "pii_types"
511 value_type = ValueType.list
512 phases = BOTH_PHASES
514 def resolve(self, context: dict[str, Any]) -> Any:
515 text = _phase_text(context)
516 return None if text is None else pii.detected_kinds(text)
519@register_field
520class ExecutionTypeField(Field):
521 key = "execution_type"
522 value_type = ValueType.enum
523 phases = BOTH_PHASES
525 def resolve(self, context: dict[str, Any]) -> Any:
526 return context.get("execution_type")
529@register_field
530class UserIdField(Field):
531 key = "user_id"
532 value_type = ValueType.text
533 phases = BOTH_PHASES
535 def resolve(self, context: dict[str, Any]) -> Any:
536 return context.get("user_id")
539@register_field
540class AgentIdField(Field):
541 key = "agent_id"
542 value_type = ValueType.text
543 phases = BOTH_PHASES
545 def resolve(self, context: dict[str, Any]) -> Any:
546 return context.get("agent_id")
549@register_field
550class AgentNameField(Field):
551 key = "agent_name"
552 value_type = ValueType.text
553 phases = BOTH_PHASES
555 def resolve(self, context: dict[str, Any]) -> Any:
556 return context.get("agent_name")
559@register_field
560class TagsField(Field):
561 key = "tags"
562 value_type = ValueType.list
563 phases = BOTH_PHASES
565 def resolve(self, context: dict[str, Any]) -> Any:
566 return context.get("tags")
569@register_field
570class ModelNameField(Field):
571 key = "model_name"
572 value_type = ValueType.text
573 phases = BOTH_PHASES
575 def resolve(self, context: dict[str, Any]) -> Any:
576 return _passthrough(context, "model_name", "model")
579@register_field
580class ProviderField(Field):
581 key = "provider"
582 value_type = ValueType.text
583 phases = BOTH_PHASES
585 def resolve(self, context: dict[str, Any]) -> Any:
586 return context.get("provider")
589@register_field
590class PromptTokensField(Field):
591 key = "prompt_tokens"
592 value_type = ValueType.number
593 phases = BOTH_PHASES
595 def resolve(self, context: dict[str, Any]) -> Any:
596 supplied = _passthrough(context, "prompt_tokens", "input_tokens")
597 if supplied is not None:
598 return supplied
599 prompt = context.get("prompt")
600 return _count_tokens(str(prompt)) if prompt is not None else None
603@register_field
604class ResponseTokensField(Field):
605 key = "response_tokens"
606 value_type = ValueType.number
607 phases = frozenset({Phase.output})
609 def resolve(self, context: dict[str, Any]) -> Any:
610 supplied = _passthrough(context, "response_tokens", "output_tokens")
611 if supplied is not None:
612 return supplied
613 response = context.get("response")
614 return _count_tokens(str(response)) if response is not None else None
617@register_field
618class TotalTokensField(Field):
619 key = "total_tokens"
620 value_type = ValueType.number
621 phases = frozenset({Phase.output})
623 def resolve(self, context: dict[str, Any]) -> Any:
624 supplied = context.get("total_tokens")
625 if supplied is not None:
626 return supplied
627 prompt_tokens = PromptTokensField().resolve(context)
628 response_tokens = ResponseTokensField().resolve(context)
629 if prompt_tokens is None and response_tokens is None:
630 return None
631 return (prompt_tokens or 0) + (response_tokens or 0)
634@register_field
635class EstimatedCostField(Field):
636 key = "estimated_cost_usd"
637 value_type = ValueType.number
638 phases = frozenset({Phase.output})
640 def resolve(self, context: dict[str, Any]) -> Any:
641 return _passthrough(context, "estimated_cost_usd", "cost_usd")
644@register_field
645class LatencyField(Field):
646 key = "latency_ms"
647 value_type = ValueType.number
648 phases = frozenset({Phase.output})
650 def resolve(self, context: dict[str, Any]) -> Any:
651 return context.get("latency_ms")
654@register_field
655class QualityCheckField(Field):
656 # svc-core's audit rules read it after the turn; inside a graph run no
657 # check has finished, so it is unknown here and a condition does not match.
658 key = "quality_check"
659 value_type = ValueType.enum
660 phases = frozenset({Phase.output})
662 def resolve(self, context: dict[str, Any]) -> Any:
663 return context.get("quality_check")
666@register_field
667class QualityScoreField(Field):
668 key = "quality_score"
669 value_type = ValueType.number
670 phases = frozenset({Phase.output})
672 def resolve(self, context: dict[str, Any]) -> Any:
673 return context.get("quality_score")
676# ─── Conditions ───────────────────────────────────────────────────────────────
679def condition_matches(condition: dict[str, Any], context: dict[str, Any]) -> bool:
680 """True when one condition block is satisfied by ``context``.
682 Every failure mode returns False and logs: a rule svc-ai cannot evaluate
683 must not be treated as satisfied, or one malformed block rule refuses
684 every inference this service runs.
685 """
686 field_key: str = condition.get("field", "")
687 operator_key: str = condition.get("operator", "eq")
688 expected: Any = condition.get("value", "")
690 field = get_field(field_key)
691 if field is None:
692 logger.warning(
693 "Rule condition references unknown field %r — condition will never "
694 "match. Valid fields: %s",
695 field_key,
696 ", ".join(sorted(field_keys())),
697 )
698 return False
700 if field.value_type is ValueType.none:
701 return True
703 operator = get_operator(operator_key)
704 if operator is None:
705 logger.warning(
706 "Rule condition uses unsupported operator %r for field %r — condition "
707 "will never match. Valid operators: %s",
708 operator_key,
709 field_key,
710 ", ".join(sorted(operator_keys())),
711 )
712 return False
714 if not supports(field, operator):
715 logger.warning(
716 "Rule condition pairs field %r (%s) with operator %r, which only "
717 "applies to %s — condition will never match.",
718 field_key,
719 field.value_type.value,
720 operator_key,
721 ", ".join(sorted(t.value for t in operator.applies_to)),
722 )
723 return False
725 actual = field.resolve(context)
726 if actual is None:
727 return False
729 return operator.evaluate(actual, expected)
732def all_conditions_match(
733 conditions: list[dict[str, Any]] | None,
734 context: dict[str, Any],
735) -> bool:
736 """All conditions must match (AND semantics). Empty list → always matches."""
737 return all(condition_matches(c, context) for c in (conditions or []))
740# ─── Actions ──────────────────────────────────────────────────────────────────
743@dataclass(frozen=True)
744class BlockDecision:
745 """An action's decision that this invocation must not proceed."""
747 message: str
750@dataclass
751class ActionOutcome:
752 """What a text action did. ``text`` is always present, mutated or not."""
754 text: str
755 events: list[dict[str, Any]] = dataclass_field(default_factory=list)
756 block: BlockDecision | None = None
759class Action(ABC):
760 """An Input or Output action, applied to the text under evaluation."""
762 type: ClassVar[str]
763 #: "input" or "output" — the layer whose rules may carry this action (the
764 #: two svc-ai enforces; Access rules are resolved in svc-core). One key may
765 #: be registered in both (``redact_pii``), one class each.
766 layer: ClassVar[str]
768 @abstractmethod
769 def apply(
770 self,
771 config: dict[str, Any],
772 text: str,
773 context: dict[str, Any],
774 ) -> ActionOutcome:
775 """Act on ``text``. ``config`` is the stored action block."""
778_ACTIONS: dict[tuple[str, str], Action] = {}
781def register_action(cls: type[Action]) -> type[Action]:
782 instance = cls()
783 key = (instance.layer, instance.type)
784 if key in _ACTIONS:
785 raise RuntimeError(
786 f"Action '{instance.type}' is already registered in the "
787 f"{instance.layer} layer."
788 )
789 _ACTIONS[key] = instance
790 return cls
793def get_action(layer: str, action_type: str) -> Action | None:
794 return _ACTIONS.get((layer, action_type))
797def action_types(layer: str) -> frozenset[str]:
798 return frozenset(action for registered, action in _ACTIONS if registered == layer)
801@register_action
802class BlockAction(Action):
803 type = "block"
804 layer = "input"
806 def apply(
807 self, config: dict[str, Any], text: str, context: dict[str, Any]
808 ) -> ActionOutcome:
809 message = config.get("message") or "This request is not permitted."
810 return ActionOutcome(text=text, block=BlockDecision(message=str(message)))
813@register_action
814class RedactPromptPiiAction(Action):
815 """Input's redaction — ``filter_pii`` until svc-core's migration 105."""
817 type = "redact_pii"
818 layer = "input"
820 def apply(
821 self, config: dict[str, Any], text: str, context: dict[str, Any]
822 ) -> ActionOutcome:
823 return redaction_outcome(self.type, text, config, context)
826@register_action
827class RedactPiiAction(Action):
828 type = "redact_pii"
829 layer = "output"
831 def apply(
832 self, config: dict[str, Any], text: str, context: dict[str, Any]
833 ) -> ActionOutcome:
834 return redaction_outcome(self.type, text, config, context)
837@register_action
838class WithholdAction(Action):
839 """Observed, never carried out here. svc-core withholds the answer once
840 every Output rule has run on it; what a run governed by such a rule does
841 in svc-ai is keep nothing of the answer — no memory of it, no preview in
842 the trace, no tool's arguments (``RulesEnforcer.may_withhold``)."""
844 type = "withhold"
845 layer = "output"
847 def apply(
848 self, config: dict[str, Any], text: str, context: dict[str, Any]
849 ) -> ActionOutcome:
850 return ActionOutcome(text=text)
853@register_action
854class FlagForReviewAction(Action):
855 type = "flag_for_review"
856 layer = "output"
858 def apply(
859 self, config: dict[str, Any], text: str, context: dict[str, Any]
860 ) -> ActionOutcome:
861 reviewer = config.get("reviewer") or "admin"
862 return ActionOutcome(
863 text=text,
864 events=[{"action": self.type, "reviewer": str(reviewer)}],
865 )