Coverage for app / services / decisions / outcomes.py: 96%
96 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"""Verdicts on governed turns, and the dataset cases they become.
3A person says whether an answer (or a skill run's output) was right:
4**accepted**, **edited** (keeping the corrected text) or **rejected**, with
5an optional business-outcome label. Each verdict is a ``DecisionOutcome``
6row; the newest is the turn's verdict. Given on the answer, on its decision
7record, or while resolving a review flag raised on it.
9**Add to dataset** turns a turn with a verdict into a case in an evaluation
10dataset — the flywheel: an accepted answer or a correction is the case's
11reference answer; a rejected answer is an example graded 0, so the judge
12learns what not to accept. Personal data is redacted by default, with the
13same detectors the governance rules use (``rules/pii.py``), and the case is
14validated by the same schema as one written by hand.
15"""
17from __future__ import annotations
19from collections import Counter
20from typing import Any
21from uuid import UUID
23from sqlalchemy.orm import Session
25from app.db.postgres.crud_schemas import _TestCaseCreate
26from app.db.postgres.enums import DecisionEnum, MessageEnum
27from app.db.postgres.models import ChatMessage, DecisionOutcome
28from app.services.decisions.context import DecisionContext, Kind
29from app.services.evaluation.context import MAX_HISTORY_MESSAGES, MAX_MESSAGE_CHARS
30from app.services.rules import pii
31from app.util.time import aware_utcnow
33Verdict = DecisionEnum.Verdict
34Source = DecisionEnum.OutcomeSource
36#: The longest correction kept. An answer longer than this is a document,
37#: and a correction to it belongs in the document.
38MAX_CORRECTION_CHARS = 20000
39MAX_NOTE_CHARS = 2000
40MAX_LABEL_CHARS = 120
41#: The tags a case made from a turn carries, beside its verdict.
42CASE_TAG = "from-decision"
43#: The longest graded example a case takes (``CaseExample.output``).
44EXAMPLE_CHARS = 8000
47class OutcomeError(ValueError):
48 """A verdict or a case that cannot be recorded, and why — for a person.
49 ``conflict`` is the turn's state (409); otherwise the request (422)."""
51 def __init__(self, message: str, *, conflict: bool = False):
52 super().__init__(message)
53 self.message = message
54 self.conflict = conflict
57# ── Verdicts ──────────────────────────────────────────────────────────────────
60def record(
61 db: Session,
62 ctx: DecisionContext,
63 *,
64 actor_id: UUID,
65 verdict: Verdict | str,
66 corrected_text: str | None = None,
67 label: str | None = None,
68 note: str | None = None,
69 source: Source = Source.answer,
70 review_flag_id: UUID | None = None,
71) -> DecisionOutcome:
72 """Append a verdict on the turn. Does not commit."""
73 verdict = Verdict(verdict)
74 corrected = (corrected_text or "").strip() or None
75 if verdict == Verdict.edited and corrected is None:
76 raise OutcomeError("An edit needs the corrected answer.")
77 if corrected is not None and len(corrected) > MAX_CORRECTION_CHARS:
78 raise OutcomeError(
79 f"A correction is limited to {MAX_CORRECTION_CHARS} characters."
80 )
81 label = (label or "").strip() or None
82 if label is not None and len(label) > MAX_LABEL_CHARS:
83 raise OutcomeError(f"A label is limited to {MAX_LABEL_CHARS} characters.")
84 note = (note or "").strip() or None
85 if note is not None and len(note) > MAX_NOTE_CHARS:
86 raise OutcomeError(f"A note is limited to {MAX_NOTE_CHARS} characters.")
87 organisation_id, project_id = _workspace(ctx)
88 row = DecisionOutcome(
89 invocation_id=ctx.invocation_id,
90 kind=ctx.kind.value,
91 verdict=verdict.value,
92 # A corrected text belongs to an edit: accepting or rejecting an
93 # answer says nothing about what it should have said.
94 corrected_text=corrected if verdict == Verdict.edited else None,
95 label=label,
96 note=note,
97 source=Source(source).value,
98 review_flag_id=review_flag_id,
99 actor_user_id=actor_id,
100 owner_user_id=ctx.owner_user_id,
101 workspace_organisation_id=organisation_id,
102 workspace_project_id=project_id,
103 created_at=aware_utcnow(),
104 )
105 db.add(row)
106 return row
109def _workspace(ctx: DecisionContext) -> tuple[UUID | None, UUID | None]:
110 holder = {
111 Kind.skill_run: ctx.run,
112 Kind.swarm_task: ctx.swarm_run,
113 }.get(ctx.kind, ctx.conversation)
114 return (
115 getattr(holder, "workspace_organisation_id", None),
116 getattr(holder, "workspace_project_id", None),
117 )
120def history(db: Session, invocation_id: UUID) -> list[DecisionOutcome]:
121 """Every verdict on the turn, oldest first."""
122 return (
123 db.query(DecisionOutcome)
124 .filter(DecisionOutcome.invocation_id == invocation_id)
125 .order_by(DecisionOutcome.created_at.asc())
126 .all()
127 )
130def latest(db: Session, invocation_ids: Any) -> dict[UUID, DecisionOutcome]:
131 """Each turn's verdict — its newest — by invocation id."""
132 ids = {i for i in invocation_ids if i is not None}
133 if not ids:
134 return {}
135 newest: dict[UUID, DecisionOutcome] = {}
136 for row in (
137 db.query(DecisionOutcome)
138 .filter(DecisionOutcome.invocation_id.in_(ids))
139 .order_by(DecisionOutcome.created_at.asc())
140 .all()
141 ):
142 newest[row.invocation_id] = row
143 return newest
146# ── Cases ─────────────────────────────────────────────────────────────────────
149def case_from_turn(
150 ctx: DecisionContext, outcome: DecisionOutcome | None, *, redact: bool = True
151) -> tuple[_TestCaseCreate, dict[str, int]]:
152 """The dataset case a turn with a verdict becomes, validated as a case
153 written by hand is, and how many values of each kind of personal data
154 were redacted from it (none when ``redact`` is off)."""
155 if outcome is None:
156 raise OutcomeError(
157 "Give it a verdict first: an accepted or corrected answer becomes "
158 "the case's reference answer, a rejected one an example of what "
159 "not to say.",
160 conflict=True,
161 )
162 question, answer, prior = _turn_texts(ctx)
163 if not question:
164 raise OutcomeError("This turn stored no question to ask again.", conflict=True)
166 redacted: Counter[str] = Counter()
168 def clean(text: str | None) -> str | None:
169 if not text or not redact:
170 return text
171 cleaned, counts = pii.redact(text)
172 redacted.update(counts)
173 return cleaned
175 verdict = Verdict(outcome.verdict)
176 fields: dict[str, Any] = {
177 "name": _name(question),
178 "input": {"prompt": clean(question)},
179 "tags": [CASE_TAG, verdict.value],
180 }
181 if verdict == Verdict.edited:
182 fields["expected_output"] = clean(outcome.corrected_text)
183 elif verdict == Verdict.accepted:
184 fields["expected_output"] = clean(answer)
185 elif answer:
186 # What was wrong is evidence too: the judge reads a graded example
187 # as a point on its scale.
188 fields["examples"] = [
189 {
190 "output": clean(answer)[:EXAMPLE_CHARS],
191 "score": 0.0,
192 "note": (outcome.note or "A person rejected this answer.")[
193 :MAX_NOTE_CHARS
194 ],
195 }
196 ]
197 history = [{"role": m["role"], "content": clean(m["content"])} for m in prior]
198 if history:
199 fields["situation"] = {"history": history}
200 return _TestCaseCreate.model_validate(fields), dict(redacted)
203def _turn_texts(ctx: DecisionContext) -> tuple[str | None, str | None, list[dict]]:
204 """The question, the answer, and the conversation before the question."""
205 if ctx.kind == Kind.skill_run:
206 run = ctx.run
207 return (run.task or run.prompt), run.output, []
208 if ctx.kind == Kind.swarm_task:
209 task = ctx.task
210 brief = task.brief if isinstance(task.brief, dict) else {}
211 return (brief.get("objective") or task.title), task.output, []
212 question, answer = ctx.question, ctx.answer
213 prior: list[dict] = []
214 if question is not None and ctx.conversation is not None:
215 rows = (
216 ctx.db.query(ChatMessage)
217 .filter(
218 ChatMessage.conversation_id == ctx.conversation.id,
219 ChatMessage.sent_at < question.sent_at,
220 ChatMessage.role.in_(
221 [MessageEnum.Role.USER, MessageEnum.Role.ASSISTANT]
222 ),
223 )
224 .order_by(ChatMessage.sent_at.desc())
225 .limit(MAX_HISTORY_MESSAGES)
226 .all()
227 )
228 prior = [
229 {
230 "role": "user" if m.role == MessageEnum.Role.USER else "assistant",
231 "content": m.content[:MAX_MESSAGE_CHARS],
232 }
233 for m in reversed(rows)
234 if (m.content or "").strip()
235 ]
236 return (
237 getattr(question, "content", None),
238 getattr(answer, "content", None),
239 prior,
240 )
243def _name(question: str) -> str:
244 first = question.strip().splitlines()[0] if question.strip() else "Case"
245 return first if len(first) <= 80 else f"{first[:79]}…"