Coverage for app / services / rules / proposals.py: 89%
125 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"""Proposed rule blocks, checked against the registries — the one implementation.
3Every flow that asks a model for rules (rule setup, agent setup) writes them in
4the vocabulary ``catalogue.generation_vocabulary`` sends, and every rule that
5comes back passes through here before it is shown for review or stored: once
6when proposed (a rule that fails is dropped with the reason) and again when the
7reviewed proposal is created (it is refused with the reason). There is no
8second copy of the grammar to keep in step — agent setup had one, and it
9disagreed with the registry on which actions exist.
11A rule is checked whole and dropped whole rather than repaired. Dropping a
12condition widens a rule, and a widened ``block`` refuses traffic nobody asked
13it to refuse.
14"""
16from __future__ import annotations
18from typing import Any
20from app.db.postgres.enums import RuleEnum
21from app.services.rules import actions as action_registry
22from app.services.rules import fields as field_registry
23from app.services.rules import layers as layer_registry
24from app.services.rules import operators as operator_registry
27def coerce(value_type: str, raw: Any) -> Any:
28 """Coerce a model-supplied string to the type the registry declares.
30 Structured output gives every value as text; the engine compares against
31 numbers and booleans. A value that will not convert is left as the string
32 it was, so the caller's own validity check is what rejects it rather than
33 an exception here.
34 """
35 if value_type == "number":
36 try:
37 number = float(raw)
38 except (TypeError, ValueError):
39 return raw
40 return int(number) if number.is_integer() else number
41 if value_type == "boolean":
42 if isinstance(raw, bool):
43 return raw
44 return str(raw).strip().lower() in {"true", "yes", "1"}
45 if value_type == "list":
46 if isinstance(raw, list):
47 return [str(item).strip() for item in raw if str(item).strip()]
48 return [part.strip() for part in str(raw).split(",") if part.strip()]
49 return raw
52def _outside(options: tuple[str, ...] | list[str], raw: Any) -> list[str]:
53 """The values in ``raw`` (a list, or the builder's comma-separated text)
54 that ``options`` does not hold."""
55 offered = {str(option).lower() for option in options}
56 return [value for value in coerce("list", raw) if value.lower() not in offered]
59def unknown_terms(
60 layer: RuleEnum.Layer | str | None,
61 conditions: list[dict] | None,
62 actions: list[dict] | None,
63) -> list[str]:
64 """Values a rule names that the registry behind them does not hold — a PII
65 kind no detector knows, say.
67 Only fields and parameters drawn from a named vocabulary are checked: an
68 ``enum`` field's options are what the builder offers, and an invocation
69 may carry a value beyond them.
70 """
71 try:
72 layer = RuleEnum.Layer(layer) if layer else None
73 except ValueError:
74 return []
75 problems: list[str] = []
76 for raw in conditions or []:
77 if not isinstance(raw, dict):
78 continue
79 field = field_registry.get_field(str(raw.get("field", "")))
80 if field is not None and field.vocabulary and field.options:
81 for value in _outside(field.options, raw.get("value", "")):
82 problems.append(
83 f"'{value}' is not one of the values '{field.key}' holds"
84 )
85 for raw in actions or []:
86 if not isinstance(raw, dict) or layer is None:
87 continue
88 action = action_registry.get_action(layer, str(raw.get("type", "")))
89 if action is None:
90 continue
91 supplied = _supplied_params(raw)
92 for param in action.params:
93 if param.vocabulary and param.options and supplied.get(param.key):
94 for value in _outside(param.options, supplied[param.key]):
95 problems.append(
96 f"'{value}' is not one of the values '{action.type}' "
97 f"takes for '{param.key}'"
98 )
99 problems.extend(action.problems(supplied))
100 return problems
103def normalise_actions(
104 layer: RuleEnum.Layer | str | None, actions: list[dict] | None
105) -> list[dict] | None:
106 """Action blocks as they are stored: each through its action's own
107 :meth:`~app.services.rules.actions.Action.normalise`. A block its layer
108 does not carry is kept as written."""
109 try:
110 layer = RuleEnum.Layer(layer) if layer else None
111 except ValueError:
112 return actions
113 if layer is None or actions is None:
114 return actions
115 stored: list[dict] = []
116 for raw in actions:
117 action = (
118 action_registry.get_action(layer, str(raw.get("type", "")))
119 if isinstance(raw, dict)
120 else None
121 )
122 stored.append(action.normalise(raw) if action is not None else raw)
123 return stored
126def validate_conditions(
127 raw_conditions: list[dict], layer: RuleEnum.Layer
128) -> tuple[list[dict], str | None]:
129 """Condition blocks, or the reason this rule cannot be kept.
131 Returns ``(blocks, None)`` or ``([], reason)`` — never a partial list. A
132 rule missing one of its conditions is a *broader* rule than the one that
133 was proposed, and silently broadening a block rule is the failure this
134 whole module exists to prevent.
135 """
136 registered = layer_registry.get(layer)
137 phase = registered.phase
138 blocks: list[dict] = []
139 for raw in raw_conditions:
140 key = str(raw.get("field", "")).strip()
141 field = field_registry.get_field(key)
142 if field is None:
143 return [], f"condition field '{key}' is not one the engine evaluates"
144 if phase not in field.phases:
145 return [], (
146 f"condition field '{key}' has no value in the {registered.label} layer"
147 )
148 # A field with no value type (``always``) carries no comparison — the
149 # way to write "every invocation in this scope" — so it is not held to
150 # operator validity.
151 if field.value_type is operator_registry.ValueType.none:
152 blocks.append({"field": key, "operator": "eq", "value": ""})
153 continue
154 operator_key = str(raw.get("operator", "eq")).strip()
155 operator = operator_registry.get_operator(operator_key)
156 if operator is None:
157 return [], f"operator '{operator_key}' is not one the engine evaluates"
158 if not field_registry.supports(field, operator):
159 return [], (
160 f"operator '{operator_key}' cannot be applied to "
161 f"'{key}' ({field.value_type.value})"
162 )
163 if field.vocabulary and field.options:
164 unknown = _outside(field.options, raw.get("value", ""))
165 if unknown:
166 return [], f"'{unknown[0]}' is not one of the values '{key}' holds"
167 blocks.append(
168 {
169 "field": key,
170 "operator": operator_key,
171 "value": coerce(field.value_type.value, raw.get("value", "")),
172 }
173 )
174 return blocks, None
177def _supplied_params(raw: dict) -> dict[str, Any]:
178 """An action block's parameters, in whichever shape they arrived.
180 A model's proposal lists them as key/value pairs (``params``); a reviewed
181 rule — the proposal as the review step shows it and posts it back — carries
182 them inline, as stored (``{"type": "block", "message": …}``). Reading only
183 the first shape threw away every parameter a reviewed rule carried: its
184 block message was replaced by the default, and a ``rate_limit`` was refused
185 for want of the limit it had.
186 """
187 supplied = {
188 str(key): value for key, value in raw.items() if key not in ("type", "params")
189 }
190 for param in raw.get("params") or []:
191 if isinstance(param, dict) and str(param.get("key", "")):
192 supplied[str(param["key"])] = param.get("value", "")
193 return supplied
196def validate_actions(
197 raw_actions: list[dict], layer: RuleEnum.Layer
198) -> tuple[list[dict], str | None]:
199 """Action blocks in their stored shape, or the reason this rule cannot be kept."""
200 if not raw_actions:
201 return [], "it has no actions, so it would do nothing"
202 blocks: list[dict] = []
203 for raw in raw_actions:
204 action_type = str(raw.get("type", "")).strip()
205 action = action_registry.get_action(layer, action_type)
206 if action is None:
207 valid = ", ".join(sorted(action_registry.action_types(layer)))
208 return [], (
209 f"'{action_type}' is not an action a rule in the "
210 f"{layer_registry.get(layer).label} layer can take (valid: {valid})"
211 )
212 supplied = _supplied_params(raw)
213 block: dict[str, Any] = {"type": action_type}
214 for param in action.params:
215 value = supplied.get(param.key)
216 if value is not None and str(value).strip() != "":
217 if param.vocabulary and param.options:
218 unknown = _outside(param.options, value)
219 if unknown:
220 return [], (
221 f"'{unknown[0]}' is not one of the values "
222 f"'{action_type}' takes for '{param.key}'"
223 )
224 block[param.key] = coerce(param.value_type.value, value)
225 elif param.default is not None:
226 block[param.key] = param.default
227 elif param.required:
228 return [], (
229 f"action '{action_type}' needs a value for "
230 f"'{param.key}' ({param.label})"
231 )
232 found = action.problems(block)
233 if found:
234 return [], found[0]
235 blocks.append(action.normalise(block))
236 return blocks, None