Coverage for app / services / rules / operators.py: 99%
224 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Comparison operators available to rule conditions.
4One class per operator, registered with :func:`register_operator` and looked
5up by key — so widening the vocabulary is a class, never a new branch in the
6evaluator (and never a new branch in the rule builder, which reads the same
7set back out of the catalogue endpoint).
9Each operator declares the *value types it can be applied to*. A field
10declares the type of the value it resolves to; the evaluator refuses a
11pairing the operator does not support rather than coercing until something
12compares equal. That refusal is what stops ``estimated_cost_usd contains 5``
13from quietly being true.
15Text comparisons are case-insensitive, matching the behaviour the original
16four operators shipped with — rules written against the old engine keep
17firing identically.
18"""
20from __future__ import annotations
22import logging
23import re
24from abc import ABC, abstractmethod
25from collections.abc import Iterable
26from enum import StrEnum
27from typing import Any, ClassVar
29logger = logging.getLogger(__name__)
32class ValueType(StrEnum):
33 """The shape of a value, on both sides of a comparison.
35 Fields declare what they resolve to; operators declare what they accept.
36 The rule builder uses the same vocabulary to pick an input control.
37 """
39 #: Free text. Compared case-insensitively.
40 text = "text"
41 #: A real number — token counts, costs, latencies.
42 number = "number"
43 #: A closed set of strings, offered as a dropdown.
44 enum = "enum"
45 #: True/false, from a classifier or a derived check.
46 boolean = "boolean"
47 #: A list of strings — tags, labels.
48 list = "list"
49 #: The field takes no comparison value at all (``always``).
50 none = "none"
53#: Longest regex a condition may carry. Rules can be authored by a model, and
54#: `re` has no match timeout, so the blast radius of a pathological pattern is
55#: bounded by capping both the pattern and the text it runs against rather
56#: than by trying to detect catastrophic backtracking.
57MAX_PATTERN_LENGTH = 512
59#: Longest text a regex operator will scan. Prompts and responses are
60#: unbounded in principle; matching the whole of a very long one buys nothing
61#: a governance rule needs and is the other half of the ReDoS bound above.
62MAX_REGEX_INPUT_LENGTH = 100_000
65class Operator(ABC):
66 """Base class for every comparison a condition can make."""
68 #: Stable key stored in the condition block and sent over the API.
69 key: ClassVar[str]
70 #: Human label for the rule builder.
71 label: ClassVar[str]
72 #: One line explaining the comparison, surfaced in the catalogue.
73 description: ClassVar[str] = ""
74 #: Field value types this operator may be paired with.
75 applies_to: ClassVar[frozenset[ValueType]]
76 #: What the builder should collect as the comparison value. ``none`` means
77 #: the operator is unary and the value input is hidden.
78 operand: ClassVar[ValueType] = ValueType.text
80 @abstractmethod
81 def evaluate(self, actual: Any, expected: Any) -> bool:
82 """Return True when ``actual`` satisfies this comparison.
84 ``actual`` has already been coerced to the field's value type and is
85 never None — the evaluator treats an unresolvable context value as a
86 non-match before an operator is consulted.
87 """
89 def spec(self) -> dict[str, Any]:
90 """Catalogue entry for this operator."""
91 return {
92 "key": self.key,
93 "label": self.label,
94 "description": self.description,
95 "applies_to": sorted(value_type.value for value_type in self.applies_to),
96 "operand": self.operand.value,
97 }
100# ── Registry ──────────────────────────────────────────────────────────────────
102_REGISTRY: dict[str, Operator] = {}
105def register_operator(cls: type[Operator]) -> type[Operator]:
106 """Class decorator adding one operator to the registry."""
107 instance = cls()
108 if instance.key in _REGISTRY:
109 raise RuntimeError(f"Operator '{instance.key}' is already registered.")
110 _REGISTRY[instance.key] = instance
111 return cls
114def get_operator(key: str) -> Operator | None:
115 """The operator registered under ``key``, or None if there is none."""
116 return _REGISTRY.get(key)
119def operator_keys() -> frozenset[str]:
120 """Every registered operator key."""
121 return frozenset(_REGISTRY)
124def catalogue() -> list[dict[str, Any]]:
125 """Every registered operator, in registration order."""
126 return [operator.spec() for operator in _REGISTRY.values()]
129# ── Coercion helpers ──────────────────────────────────────────────────────────
132def _text(value: Any) -> str:
133 """Case-folded string form, the basis of every text comparison."""
134 return str(value).lower()
137def _number(value: Any) -> float | None:
138 """Numeric form of ``value``, or None when it is not a number.
140 Booleans are rejected rather than silently read as 0/1: ``True`` is not a
141 meaningful token count, and a rule that compared one would be a mistake
142 worth surfacing, not honouring.
143 """
144 if isinstance(value, bool):
145 return None
146 try:
147 return float(value)
148 except (TypeError, ValueError):
149 return None
152def _as_list(value: Any) -> list[str]:
153 """Case-folded list form — accepts a real list or a comma-separated string.
155 The rule builder collects a set as free text, so ``"eu, uk"`` and
156 ``["eu", "uk"]`` have to mean the same thing.
157 """
158 if isinstance(value, (list, tuple, set, frozenset)):
159 return [_text(item).strip() for item in value]
160 return [part.strip() for part in _text(value).split(",") if part.strip()]
163def _compile(pattern: Any) -> re.Pattern[str] | None:
164 """Compile a condition's regex, or None if it is unusable.
166 Length is capped before compilation (see :data:`MAX_PATTERN_LENGTH`) and
167 an invalid pattern logs rather than raises, so one malformed rule cannot
168 fail an invocation that a dozen well-formed rules also govern.
169 """
170 text = str(pattern)
171 if len(text) > MAX_PATTERN_LENGTH:
172 logger.warning(
173 "Rule condition regex is %d characters, over the %d limit — "
174 "condition will never match.",
175 len(text),
176 MAX_PATTERN_LENGTH,
177 )
178 return None
179 try:
180 return re.compile(text, re.IGNORECASE)
181 except re.error as exc:
182 logger.warning(
183 "Rule condition regex %r is invalid (%s) — condition will never match.",
184 text,
185 exc,
186 )
187 return None
190def _search(pattern: Any, actual: Any) -> bool | None:
191 """Run a regex against ``actual``, or None when the pattern is unusable."""
192 compiled = _compile(pattern)
193 if compiled is None:
194 return None
195 return compiled.search(str(actual)[:MAX_REGEX_INPUT_LENGTH]) is not None
198#: Every type a text operator is willing to compare. Enums and booleans are
199#: included because "is this execution_type agent" and "is pii_detected true"
200#: are both equality questions a user will reasonably write as text.
201_TEXTUAL: frozenset[ValueType] = frozenset(
202 {ValueType.text, ValueType.enum, ValueType.boolean}
203)
205_TEXTUAL_OR_NUMERIC: frozenset[ValueType] = _TEXTUAL | {ValueType.number}
208# ── Equality ──────────────────────────────────────────────────────────────────
211@register_operator
212class EqualsOperator(Operator):
213 key = "eq"
214 label = "is"
215 description = "Exactly equal, ignoring case."
216 applies_to = _TEXTUAL_OR_NUMERIC
218 def evaluate(self, actual: Any, expected: Any) -> bool:
219 left, right = _number(actual), _number(expected)
220 if left is not None and right is not None:
221 return left == right
222 return _text(actual) == _text(expected)
225@register_operator
226class NotEqualsOperator(Operator):
227 key = "neq"
228 label = "is not"
229 description = "Not equal, ignoring case."
230 applies_to = _TEXTUAL_OR_NUMERIC
232 def evaluate(self, actual: Any, expected: Any) -> bool:
233 return not EqualsOperator().evaluate(actual, expected)
236# ── Substring ─────────────────────────────────────────────────────────────────
239@register_operator
240class ContainsOperator(Operator):
241 key = "contains"
242 label = "contains"
243 description = "Contains the given text, ignoring case."
244 applies_to = _TEXTUAL
246 def evaluate(self, actual: Any, expected: Any) -> bool:
247 return _text(expected) in _text(actual)
250@register_operator
251class NotContainsOperator(Operator):
252 key = "not_contains"
253 label = "does not contain"
254 description = "Does not contain the given text, ignoring case."
255 applies_to = _TEXTUAL
257 def evaluate(self, actual: Any, expected: Any) -> bool:
258 return _text(expected) not in _text(actual)
261@register_operator
262class StartsWithOperator(Operator):
263 key = "starts_with"
264 label = "starts with"
265 description = "Begins with the given text, ignoring case."
266 applies_to = _TEXTUAL
268 def evaluate(self, actual: Any, expected: Any) -> bool:
269 return _text(actual).startswith(_text(expected))
272@register_operator
273class EndsWithOperator(Operator):
274 key = "ends_with"
275 label = "ends with"
276 description = "Ends with the given text, ignoring case."
277 applies_to = _TEXTUAL
279 def evaluate(self, actual: Any, expected: Any) -> bool:
280 return _text(actual).endswith(_text(expected))
283# ── Pattern ───────────────────────────────────────────────────────────────────
286@register_operator
287class MatchesOperator(Operator):
288 key = "matches"
289 label = "matches regex"
290 description = (
291 "Matches the given regular expression, ignoring case. "
292 f"Patterns are limited to {MAX_PATTERN_LENGTH} characters."
293 )
294 applies_to = _TEXTUAL
296 def evaluate(self, actual: Any, expected: Any) -> bool:
297 return _search(expected, actual) is True
300@register_operator
301class NotMatchesOperator(Operator):
302 key = "not_matches"
303 label = "does not match regex"
304 description = "Does not match the given regular expression, ignoring case."
305 applies_to = _TEXTUAL
307 def evaluate(self, actual: Any, expected: Any) -> bool:
308 # An unusable pattern is a non-match for both polarities: a rule whose
309 # regex does not compile must not start firing merely because it was
310 # phrased in the negative.
311 return _search(expected, actual) is False
314# ── Ordering ──────────────────────────────────────────────────────────────────
317class _NumericOperator(Operator):
318 """Shared coercion for the four ordering comparisons."""
320 applies_to = frozenset({ValueType.number})
321 operand = ValueType.number
323 def evaluate(self, actual: Any, expected: Any) -> bool:
324 left, right = _number(actual), _number(expected)
325 if left is None or right is None:
326 logger.warning(
327 "Rule condition compares %r %s %r, which is not numeric — "
328 "condition will never match.",
329 actual,
330 self.key,
331 expected,
332 )
333 return False
334 return self.compare(left, right)
336 @abstractmethod
337 def compare(self, left: float, right: float) -> bool:
338 """Order ``left`` against ``right``."""
341@register_operator
342class GreaterThanOperator(_NumericOperator):
343 key = "gt"
344 label = "is greater than"
345 description = "Strictly greater than the given number."
347 def compare(self, left: float, right: float) -> bool:
348 return left > right
351@register_operator
352class GreaterOrEqualOperator(_NumericOperator):
353 key = "gte"
354 label = "is at least"
355 description = "Greater than or equal to the given number."
357 def compare(self, left: float, right: float) -> bool:
358 return left >= right
361@register_operator
362class LessThanOperator(_NumericOperator):
363 key = "lt"
364 label = "is less than"
365 description = "Strictly less than the given number."
367 def compare(self, left: float, right: float) -> bool:
368 return left < right
371@register_operator
372class LessOrEqualOperator(_NumericOperator):
373 key = "lte"
374 label = "is at most"
375 description = "Less than or equal to the given number."
377 def compare(self, left: float, right: float) -> bool:
378 return left <= right
381# ── Set membership ────────────────────────────────────────────────────────────
384@register_operator
385class InOperator(Operator):
386 key = "in"
387 label = "is one of"
388 description = "Equal to any member of the given comma-separated set."
389 applies_to = _TEXTUAL_OR_NUMERIC
390 operand = ValueType.list
392 def evaluate(self, actual: Any, expected: Any) -> bool:
393 return _text(actual) in _as_list(expected)
396@register_operator
397class NotInOperator(Operator):
398 key = "not_in"
399 label = "is none of"
400 description = "Not equal to any member of the given comma-separated set."
401 applies_to = _TEXTUAL_OR_NUMERIC
402 operand = ValueType.list
404 def evaluate(self, actual: Any, expected: Any) -> bool:
405 return _text(actual) not in _as_list(expected)
408@register_operator
409class HasAnyOperator(Operator):
410 key = "has_any"
411 label = "has any of"
412 description = "The list shares at least one member with the given set."
413 applies_to = frozenset({ValueType.list})
414 operand = ValueType.list
416 def evaluate(self, actual: Any, expected: Any) -> bool:
417 return bool(set(_as_list(actual)) & set(_as_list(expected)))
420@register_operator
421class HasAllOperator(Operator):
422 key = "has_all"
423 label = "has all of"
424 description = "The list contains every member of the given set."
425 applies_to = frozenset({ValueType.list})
426 operand = ValueType.list
428 def evaluate(self, actual: Any, expected: Any) -> bool:
429 wanted = set(_as_list(expected))
430 return bool(wanted) and wanted <= set(_as_list(actual))
433@register_operator
434class HasNoneOperator(Operator):
435 key = "has_none"
436 label = "has none of"
437 description = "The list shares no member with the given set."
438 applies_to = frozenset({ValueType.list})
439 operand = ValueType.list
441 def evaluate(self, actual: Any, expected: Any) -> bool:
442 return not (set(_as_list(actual)) & set(_as_list(expected)))
445def operators_for(value_type: ValueType) -> Iterable[Operator]:
446 """Every operator that may be paired with a field of ``value_type``."""
447 return [op for op in _REGISTRY.values() if value_type in op.applies_to]