Coverage for app / inference / rules.py: 97%
184 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"""
2RulesEnforcer — applies governance rules inside svc-ai at inference time.
4Rules are pre-resolved by svc-core and forwarded in ExecuteRequest.rules so
5svc-ai can enforce them without a cross-service DB round-trip.
7──────────────────────────────────────────────────────────────────────────────
8Layers enforced here
9──────────────────────────────────────────────────────────────────────────────
11 input Applied to the *input prompt* before the LLM is called.
12 output Applied to the *LLM response* after it returns.
14svc-core's Access rules (budgets, rate limits, the evaluation gate) read its
15own ledger and evaluations, so it resolves them and never forwards one.
17──────────────────────────────────────────────────────────────────────────────
18Where the vocabulary lives
19──────────────────────────────────────────────────────────────────────────────
21This module owns *when* rules are applied and how their effects reach the
22caller. The grammar — which fields a condition may reference, which operators
23it may use, and what each action does — lives in
24``app.inference.rule_vocabulary``, the enforcement-side mirror of svc-core's
25``app.services.rules``.
27The two are maintained by hand (separate services, separate images) and
28pinned by matching tests on both sides, because a field svc-core offers in
29the rule builder but svc-ai cannot evaluate is a rule that silently stops
30being enforced the moment execution moves inside a LangGraph run.
32Unknown fields, operators and actions never match and never fire — they log a
33warning instead.
34"""
36from __future__ import annotations
38import json
39import logging
40import time
41from typing import TYPE_CHECKING, Any
43from app.inference import pii
44from app.util import safe_json
45from app.inference import rule_vocabulary as vocabulary
46from app.inference.rule_vocabulary import (
47 filter_pii as _filter_pii, # noqa: F401 — re-exported; imported from here since before the split
48)
50if TYPE_CHECKING:
51 from app.models.spec import RuleSpec
53logger = logging.getLogger(__name__)
55# ─── Vocabulary ───────────────────────────────────────────────────────────────
56#
57# Views of the registry rather than second lists to maintain. See
58# ``app.inference.rule_vocabulary``.
61def _valid_context_fields() -> frozenset[str]:
62 """Every condition field this service can evaluate."""
63 return vocabulary.field_keys()
66def _valid_operators() -> frozenset[str]:
67 """Every comparison operator this service can evaluate."""
68 return vocabulary.operator_keys()
71def _valid_actions(layer: str) -> frozenset[str]:
72 """Every action type valid on a rule in ``layer``."""
73 return vocabulary.action_types(layer)
76# ─── Exception ────────────────────────────────────────────────────────────────
79class RuleBlock(Exception):
80 """Raised when an Input rule fires a block action.
82 Carries the firing rule's identity, not just its name. Rule names are
83 mutable and not unique, so a block recorded under a name alone cannot be
84 resolved back to the policy that produced it. svc-core persists these
85 fields into the turn's trace, so they are what make a block raised here
86 defensible after the fact.
88 Identity is optional: a RuleSpec forwarded by an older svc-core, or a
89 rule with no recorded version history, still blocks correctly.
90 """
92 def __init__(
93 self,
94 rule_name: str,
95 message: str,
96 *,
97 rule_id: str | None = None,
98 rule_version: int | None = None,
99 scope_type: str | None = None,
100 scope_id: str | None = None,
101 ) -> None:
102 self.rule_name = rule_name
103 self.message = message
104 self.rule_id = rule_id
105 self.rule_version = rule_version
106 self.scope_type = scope_type
107 self.scope_id = scope_id
108 super().__init__(message)
111def block_payload(exc: RuleBlock) -> dict[str, Any]:
112 """Wire representation of a block.
114 Shared by the SSE ``error`` frame and the HTTP 403 detail so svc-core
115 parses one shape regardless of which transport the block arrived on.
116 """
117 return {
118 "rule": exc.rule_name,
119 "rule_id": exc.rule_id,
120 "rule_version": exc.rule_version,
121 "scope_type": exc.scope_type,
122 "scope_id": exc.scope_id,
123 "message": exc.message,
124 }
127def _rule_ref(rule: "RuleSpec") -> dict[str, Any]:
128 """Identity block stamped onto every event a rule produces.
130 Mirrors svc-core's ``rule_engine._rule_ref`` so an event means the same
131 thing whichever service enforced it.
132 """
133 return {
134 "rule": rule.name,
135 "rule_id": rule.rule_id,
136 "rule_version": rule.rule_version,
137 "scope_type": rule.scope_type,
138 "scope_id": rule.scope_id,
139 }
142# ─── PII ──────────────────────────────────────────────────────────────────────
143#
144# ``_filter_pii`` is imported from the vocabulary module, where the patterns
145# now live so the ``pii_detected`` condition field and the redaction actions
146# cannot disagree about what PII is.
149# ─── Condition evaluation ─────────────────────────────────────────────────────
150#
151# Thin wrappers over the vocabulary module, kept because call sites and tests
152# here name them and because one seam between "the enforcer" and "the
153# grammar" is what lets the grammar be mirrored rather than duplicated.
156def _condition_matches(condition: dict[str, Any], context: dict[str, Any]) -> bool:
157 """Evaluate a single condition against the inference context."""
158 return vocabulary.condition_matches(condition, context)
161def _all_conditions_match(conditions: list[dict], context: dict[str, Any]) -> bool:
162 """All conditions must match (AND semantics). Empty list → always matches."""
163 return vocabulary.all_conditions_match(conditions, context)
166# ─── Enforcer ─────────────────────────────────────────────────────────────────
169class RulesEnforcer:
170 """
171 Evaluates governance rules pre- and post-inference.
173 Constructed once per request from ``ExecuteRequest.rules``.
174 """
176 def __init__(self, rules: list["RuleSpec"]) -> None:
177 self._input: list["RuleSpec"] = sorted(
178 [r for r in rules if r.layer == "input"],
179 key=lambda r: -r.priority,
180 )
181 self._output: list["RuleSpec"] = sorted(
182 [r for r in rules if r.layer == "output"],
183 key=lambda r: -r.priority,
184 )
186 @property
187 def has_input(self) -> bool:
188 """True when at least one Input rule is loaded."""
189 return bool(self._input)
191 @property
192 def has_output(self) -> bool:
193 """True when at least one Output rule is loaded."""
194 return bool(self._output)
196 @property
197 def may_withhold(self) -> bool:
198 """Whether an Output rule that can withhold the answer governs the run
199 — whatever its conditions, which svc-core judges on the finished
200 answer. While one does, svc-ai keeps nothing of the answer: memory
201 keeps only the request, and the trace neither the answer's preview
202 nor any tool's arguments or result (:func:`may_withhold`)."""
203 return may_withhold(self._output)
205 # ── Action dispatch ───────────────────────────────────────────────────────
207 def _apply_actions(
208 self,
209 rule: RuleSpec,
210 layer: str,
211 text: str,
212 context: dict[str, Any],
213 ref: dict[str, Any],
214 ) -> tuple[str, list[dict[str, Any]], vocabulary.BlockDecision | None]:
215 """Run every action on one matched rule against ``text``.
217 Returns the (possibly rewritten) text, the events the actions
218 produced, and a block decision if one of them refused the invocation.
219 Actions after a block are not run: the inference is over, and an
220 action that rewrote text nobody will see would add a misleading entry
221 to the enforcement trail svc-core persists.
222 """
223 events: list[dict[str, Any]] = []
224 for action in rule.actions or []:
225 action_type: str = action.get("type", "")
226 registered = vocabulary.get_action(layer, action_type)
228 if registered is None:
229 logger.warning(
230 "%s rule %r has unsupported action %r — skipped. Valid %s "
231 "actions: %s",
232 layer.capitalize(),
233 rule.name,
234 action_type,
235 layer,
236 ", ".join(sorted(_valid_actions(layer))),
237 )
238 continue
240 outcome = registered.apply(action, text, context)
241 text = outcome.text
242 events.extend({**ref, **event} for event in outcome.events)
244 if outcome.block is not None:
245 return text, events, outcome.block
247 return text, events, None
249 # ── Input ─────────────────────────────────────────────────────────────────
251 def apply_input(
252 self,
253 prompt: str,
254 context: dict[str, Any],
255 ) -> tuple[str, list[dict[str, Any]]]:
256 """
257 Apply Input rules to the prompt before inference.
259 Returns ``(filtered_prompt, events)``. The prompt may be modified when
260 a ``redact_pii`` action fires.
262 Raises:
263 RuleBlock: when a ``block`` action fires.
264 """
265 events: list[dict[str, Any]] = []
266 filtered = prompt
268 for rule in self._input:
269 eval_ctx = {**context, "prompt": filtered}
270 if not _all_conditions_match(rule.conditions, eval_ctx):
271 continue
273 ref = {**_rule_ref(rule), "phase": "input"}
274 filtered, rule_events, block = self._apply_actions(
275 rule, "input", filtered, eval_ctx, ref
276 )
277 events.extend(rule_events)
279 if block is not None:
280 logger.info(
281 "Rule %r (id=%s v%s) blocked inference: %s",
282 rule.name,
283 rule.rule_id,
284 rule.rule_version,
285 block.message,
286 )
287 raise RuleBlock(
288 rule_name=rule.name,
289 message=block.message,
290 rule_id=rule.rule_id,
291 rule_version=rule.rule_version,
292 scope_type=rule.scope_type,
293 scope_id=rule.scope_id,
294 )
296 return filtered, events
298 # ── Output ────────────────────────────────────────────────────────────────
300 def apply_output(
301 self,
302 response: str,
303 context: dict[str, Any],
304 ) -> tuple[str, list[dict[str, Any]]]:
305 """
306 Apply Output rules to the LLM response after inference.
308 Returns ``(filtered_response, events)``. The response may be modified
309 when a ``redact_pii`` action fires.
310 """
311 events: list[dict[str, Any]] = []
312 filtered = response
314 for rule in self._output:
315 eval_ctx = {**context, "response": filtered}
316 if not _all_conditions_match(rule.conditions, eval_ctx):
317 continue
319 ref = {**_rule_ref(rule), "phase": "output"}
320 # No Output action registers a block decision, but the same helper
321 # serves both phases so the two record events identically.
322 filtered, rule_events, _ = self._apply_actions(
323 rule, "output", filtered, eval_ctx, ref
324 )
325 events.extend(rule_events)
326 for event in rule_events:
327 if event.get("action") == "flag_for_review":
328 logger.warning(
329 "Output rule %r: flagging invocation for review by %r",
330 rule.name,
331 event.get("reviewer"),
332 )
334 return filtered, events
336 # ── Streams ───────────────────────────────────────────────────────────────
338 def output_redactor(self, context: dict[str, Any]) -> pii.Redactor | None:
339 """What the Output rules would redact from this invocation's output,
340 for the text that reaches a person before the final answer does —
341 streamed tokens, node results in the trace, citations, a pause.
343 Every Output rule carrying ``redact_pii`` counts, whatever its
344 conditions: those are judged on the finished answer, which does not
345 exist yet. Redacting a stream that turns out not to need it costs
346 nothing — the final answer replaces the streamed text — while showing
347 what a rule exists to hide cannot be taken back.
348 """
349 redactor: pii.Redactor | None = None
350 for rule in self._output:
351 for action in rule.actions or []:
352 if action.get("type") == "redact_pii":
353 redactor = vocabulary.redactor_for(action, context).merged(redactor)
354 return redactor
356 def input_redactor(self, context: dict[str, Any]) -> pii.Redactor | None:
357 """What the Input rules would redact from text a model reads beside
358 the prompt — the memories recalled into it (``app.memory.service``).
360 Every Input rule carrying ``redact_pii`` counts, whatever its
361 conditions, as ``output_redactor`` does: a memory written before the
362 rule existed is recalled unredacted otherwise, into a prompt the rule
363 redacted.
364 """
365 redactor: pii.Redactor | None = None
366 for rule in self._input:
367 for action in rule.actions or []:
368 if action.get("type") == "redact_pii":
369 redactor = vocabulary.redactor_for(action, context).merged(redactor)
370 return redactor
373def may_withhold(rules: list[RuleSpec] | None) -> bool:
374 """Whether any Output rule in ``rules`` carries the ``withhold`` action."""
375 return any(
376 getattr(rule, "layer", None) == "output"
377 and any(
378 isinstance(action, dict) and action.get("type") == "withhold"
379 for action in getattr(rule, "actions", None) or []
380 )
381 for rule in rules or []
382 )
385# ─── SSE stream redaction ─────────────────────────────────────────────────────
388def _frame_data(frame: str) -> dict[str, Any] | None:
389 """The JSON payload of one ``data: {...}`` SSE frame, or None."""
390 _, _, payload = frame.partition("data: ")
391 try:
392 data = json.loads(payload)
393 except (json.JSONDecodeError, ValueError):
394 return None
395 return data if isinstance(data, dict) else None
398def _frame(data: dict[str, Any]) -> str:
399 return f"data: {safe_json.dumps(data)}\n\n"
402class StreamGuard:
403 """Redacts an SSE stream's frames as they pass, for a ``redact_pii`` rule.
405 Without it the rule redacted only the final answer: every token reached
406 the browser as the model wrote it, and node results, citations and pauses
407 in the trace were never redacted at all.
409 ``token`` frames go through a :class:`pii.StreamRedactor` per stream — one
410 per ``worker_agent_slug``, because nodes' tokens interleave — which holds
411 back text until nothing after it could make it part of a value. Held text
412 is released, redacted, before a frame that ends the answer. Every other
413 frame has every string in it redacted whole. The ``done`` frame's output
414 passes untouched: it is the authoritative answer, which
415 :func:`audit_done_frame` judges by the rules' own conditions. Its source
416 lists are redacted like any streamed ``citations`` frame — svc-core
417 forwards ``cited_citations`` to the browser as the answer's sources
418 before its own output rules run.
419 """
421 #: Frames after which no more of the answer streams.
422 _TERMINAL = frozenset({"done", "error", "hitl_interrupt"})
423 #: The ``done`` frame's lists of sources, redacted like a citations frame.
424 _DONE_SOURCES = ("citations", "cited_citations")
425 #: A node's streamed text taken back (``graph_based.TOKEN_RESET``).
426 _RESET = "token_reset"
428 def __init__(self, redactor: pii.Redactor) -> None:
429 self._redactor = redactor
430 self._streams: dict[str, pii.StreamRedactor] = {}
431 self._last: dict[str, dict[str, Any]] = {}
433 def process(self, frame: str) -> list[str]:
434 """The frames to send in place of ``frame`` — none, while a token is
435 held back; several, when held text is released before a final one."""
436 data = _frame_data(frame)
437 if data is None:
438 return [frame]
439 kind = data.get("type")
440 if kind == "token":
441 key = str(data.get("worker_agent_slug") or "")
442 stream = self._streams.setdefault(key, pii.StreamRedactor(self._redactor))
443 self._last[key] = data
444 released = stream.feed(str(data.get("token") or ""))
445 return [_frame({**data, "token": released})] if released else []
446 if kind == self._RESET:
447 # What the stream holds back is of the text being taken back:
448 # released after the reset, it would reappear in the preview.
449 self._streams.pop(str(data.get("worker_agent_slug") or ""), None)
450 return [frame]
451 released = self.flush() if kind in self._TERMINAL else []
452 if kind == "done":
453 sources = {
454 key: self._redactor.redact_values(data[key])
455 for key in self._DONE_SOURCES
456 if key in data
457 }
458 return [*released, _frame({**data, **sources}) if sources else frame]
459 return [*released, _frame(self._redactor.redact_values(data))]
461 def flush(self) -> list[str]:
462 """Everything still held, released as token frames of its stream."""
463 frames = []
464 for key, stream in self._streams.items():
465 released = stream.flush()
466 if released:
467 frames.append(_frame({**self._last[key], "token": released}))
468 return frames
471def stream_guard(
472 enforcer: RulesEnforcer, context: dict[str, Any]
473) -> StreamGuard | None:
474 """A guard for one stream, or None when no Output rule redacts."""
475 redactor = enforcer.output_redactor(context)
476 return StreamGuard(redactor) if redactor is not None else None
479def output_figures(data: dict[str, Any], started: float | None) -> dict[str, Any]:
480 """What an Output rule may ask of a finished run here: how long it took and
481 what it cost, as metered on the ``done`` frame — so svc-ai judges a rule
482 on ``latency_ms`` or ``estimated_cost_usd`` as svc-core does."""
483 figures: dict[str, Any] = {}
484 if started is not None:
485 figures["latency_ms"] = round((time.monotonic() - started) * 1000, 1)
486 usage = data.get("usage")
487 cost = usage.get("estimated_cost_usd") if isinstance(usage, dict) else None
488 if cost is not None:
489 try:
490 figures["estimated_cost_usd"] = float(cost)
491 except (TypeError, ValueError):
492 pass
493 return figures
496# ─── SSE stream auditing ──────────────────────────────────────────────────────
499def audit_done_frame(
500 enforcer: RulesEnforcer,
501 frame: str,
502 context: dict[str, Any],
503 prior_events: list[dict[str, Any]] | None = None,
504 started: float | None = None,
505) -> tuple[str, list[dict[str, Any]]]:
506 """
507 Apply Output rules to the final output carried by an SSE ``done`` frame,
508 and attach the request's full rule-event trail to it.
510 Streaming engines emit their complete output in the terminal
511 ``data: {"type": "done", "output": ...}`` frame; this helper rewrites
512 that frame with the filtered output so redactions reach the client.
513 Non-``done`` frames pass through untouched here; a :class:`StreamGuard`
514 in front of this redacts them when an Output rule redacts. ``started`` is
515 when the run began, for a rule on ``latency_ms``.
517 ``prior_events`` are events that fired earlier in the request (policy
518 rules run before the stream opens, so they have nowhere else to go). They
519 are written onto the done frame together with any audit events from this
520 frame, under ``rule_events``, so svc-core can persist and display what
521 was enforced here rather than losing it at the service boundary.
523 Returns:
524 (frame, events) — the (possibly rewritten) SSE frame and the audit
525 events that fired *on this frame* (``prior_events`` are not repeated,
526 so callers can extend their accumulator without double-counting).
527 """
528 # Cheap pre-filter: _sse serialises with json.dumps defaults, so every
529 # done frame contains this exact substring. Token frames that happen to
530 # embed it are disambiguated by the JSON parse below.
531 prior = prior_events or []
532 if '"type": "done"' not in frame:
533 return frame, []
534 if not enforcer.has_output and not prior:
535 return frame, []
537 _, _, payload = frame.partition("data: ")
538 try:
539 data = json.loads(payload)
540 except json.JSONDecodeError:
541 return frame, []
543 if not isinstance(data, dict) or data.get("type") != "done":
544 return frame, []
546 if enforcer.has_output:
547 filtered, events = enforcer.apply_output(
548 data.get("output", ""), {**context, **output_figures(data, started)}
549 )
550 else:
551 filtered, events = data.get("output", ""), []
553 all_events = [*prior, *events]
554 if not all_events:
555 return frame, []
557 data["output"] = filtered
558 data["rule_events"] = all_events
559 return f"data: {safe_json.dumps(data)}\n\n", events