Coverage for app / router / app / decisions / router.py: 95%
81 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"""``/app/decisions`` — the decision record of one governed turn.
3Read by the turn's id (``invocation_id``), which answers, skill runs and
4review flags carry. Two people may read one:
6* **the person whose turn it was** — their conversation, their skill run;
7* **a reviewer of a flag raised on it** — whoever may open and resolve that
8 flag in the review queue (``review.may_review``). Judging a flagged answer
9 needs the question it answered and how it got there, not only the excerpt
10 the queue shows.
12Nobody else: the record holds a person's question, inputs and the whole
13answer. And every read by a reviewer is logged (``decision_reads``) before
14the record is served — the record is refused if the read cannot be logged
15— and listed on the record, so its owner can see who has looked.
17Whoever may read a record may give the turn a verdict (``/outcome``) and,
18with write access to a dataset, add it there as a case (``/case``):
19``app/services/decisions/outcomes.py``.
20"""
22import logging
24from uuid import UUID
26from fastapi import APIRouter, Depends, HTTPException, status
27from sqlalchemy.orm import Session
29from app.db.postgres.enums import DecisionEnum, HistoryEnum
30from app.db.postgres.models import (
31 DecisionReadLog,
32 ReviewFlag,
33 TestCase,
34 TestSuite,
35 User,
36)
37from app.dependency.base import get_db
38from app.dependency.resource_access import verify_resource_access
39from app.dependency.user.context import get_current_user
40from app.services import decisions
41from app.services import review as review_service
42from app.services.decisions import DecisionContext, DecisionRead, outcomes
43from app.services.decisions.schema import (
44 CaseCreate,
45 CaseCreated,
46 OutcomeCreate,
47 OutcomeRead,
48)
49from app.services.evaluation import dataset_versions
50from app.util.time import aware_utcnow
52logger = logging.getLogger(__name__)
54decisions_router = APIRouter(prefix="/decisions", tags=["App - Decisions"])
57@decisions_router.get("/{invocation_id}", response_model=DecisionRead)
58def get_decision(
59 invocation_id: UUID,
60 db: Session = Depends(get_db),
61 current_user: User = Depends(get_current_user),
62):
63 """Everything one answer or skill run recorded: what was asked, what
64 came back, the configuration that answered, every rule that ran, the
65 quality check, human input, review flags, steps, model and tool calls,
66 and cost. A section the turn did not record says so (``status``).
68 ``access`` says why the caller may read it. 404 for an id no turn has,
69 and for a turn the caller neither had nor reviews alike, so the
70 endpoint does not say whose turns exist. A reviewer's read is logged
71 first; 503 when it cannot be, and nothing is served.
72 """
73 ctx, access, flag = _readable(db, invocation_id, current_user)
74 if access == DecisionEnum.Access.reviewer:
75 _log_read(db, ctx, current_user, access, flag)
76 return decisions.assemble(ctx, access)
79@decisions_router.post(
80 "/{invocation_id}/outcome",
81 status_code=status.HTTP_201_CREATED,
82 response_model=OutcomeRead,
83)
84def record_outcome(
85 invocation_id: UUID,
86 body: OutcomeCreate,
87 db: Session = Depends(get_db),
88 current_user: User = Depends(get_current_user),
89):
90 """Give the turn a verdict: accepted, edited (with the corrected text)
91 or rejected, with an optional business-outcome label and note. A changed
92 mind is a new verdict; the newest is the turn's. 422 for an edit with no
93 correction or text past its limit."""
94 ctx, access, flag = _readable(db, invocation_id, current_user)
95 try:
96 row = outcomes.record(
97 db,
98 ctx,
99 actor_id=current_user.id,
100 verdict=body.verdict,
101 corrected_text=body.corrected_text,
102 label=body.label,
103 note=body.note,
104 # A reviewer's verdict names the flag that let them judge it.
105 review_flag_id=getattr(flag, "id", None),
106 )
107 db.commit()
108 db.refresh(row)
109 except outcomes.OutcomeError as exc:
110 db.rollback()
111 raise _refusal(exc) from exc
112 return OutcomeRead.model_validate(row).model_copy(
113 update={"actor_name": current_user.name or current_user.email}
114 )
117@decisions_router.post(
118 "/{invocation_id}/case",
119 status_code=status.HTTP_201_CREATED,
120 response_model=CaseCreated,
121)
122def add_to_dataset(
123 invocation_id: UUID,
124 body: CaseCreate,
125 db: Session = Depends(get_db),
126 current_user: User = Depends(get_current_user),
127):
128 """Add the turn to a dataset as a case — the flywheel. Its verdict
129 decides the label: an accepted answer or a correction becomes the
130 reference answer, a rejected answer an example graded 0. Personal data
131 is redacted unless ``redact_pii`` is off, and ``redacted`` says what was.
132 The case names the turn (``source_invocation_id``), and the dataset
133 takes a new version as for any case added. 409 when the turn has no
134 verdict yet."""
135 ctx, _, _ = _readable(db, invocation_id, current_user)
136 suite = db.get(TestSuite, body.test_suite_id)
137 if suite is None:
138 raise HTTPException(
139 status_code=status.HTTP_404_NOT_FOUND, detail="Dataset not found"
140 )
141 # The dataset's own create-case check: a writer in its area, and never a
142 # gold dataset.
143 verify_resource_access(suite, current_user, db)
144 verdict = outcomes.latest(db, [ctx.invocation_id]).get(ctx.invocation_id)
145 try:
146 fields, redacted = outcomes.case_from_turn(ctx, verdict, redact=body.redact_pii)
147 except outcomes.OutcomeError as exc:
148 raise _refusal(exc) from exc
149 case = TestCase(
150 **fields.model_dump(),
151 test_suite_id=suite.id,
152 source_invocation_id=ctx.invocation_id,
153 )
154 try:
155 db.add(case)
156 db.flush()
157 dataset_versions.record_suite_version(
158 db, suite, HistoryEnum.Action.updated, current_user
159 )
160 db.commit()
161 db.refresh(case)
162 except Exception:
163 db.rollback()
164 logger.exception("Could not add decision %s to a dataset", invocation_id)
165 raise
166 return CaseCreated(case=case, redacted=redacted)
169def _readable(
170 db: Session, invocation_id: UUID, user: User
171) -> tuple[DecisionContext, DecisionEnum.Access, ReviewFlag | None]:
172 """The turn, if ``user`` may read it, with why; 404 otherwise."""
173 ctx = decisions.locate(db, invocation_id)
174 access, flag = _access(db, ctx, user) if ctx is not None else (None, None)
175 if access is None:
176 raise HTTPException(
177 status_code=status.HTTP_404_NOT_FOUND, detail="Decision not found"
178 )
179 return ctx, access, flag
182def _refusal(exc: outcomes.OutcomeError) -> HTTPException:
183 return HTTPException(
184 status_code=status.HTTP_409_CONFLICT
185 if exc.conflict
186 else status.HTTP_422_UNPROCESSABLE_ENTITY,
187 detail=exc.message,
188 )
191def _access(
192 db: Session, ctx: DecisionContext, user: User
193) -> tuple[DecisionEnum.Access | None, ReviewFlag | None]:
194 """Why ``user`` may read the turn — and, for a reviewer, the flag that
195 lets them in — or ``(None, None)`` when they may not."""
196 if ctx.owner_user_id is not None and ctx.owner_user_id == user.id:
197 return DecisionEnum.Access.owner, None
198 flag = next((f for f in ctx.flags if review_service.may_review(db, f, user)), None)
199 if flag is not None:
200 return DecisionEnum.Access.reviewer, flag
201 return None, None
204def _log_read(
205 db: Session,
206 ctx: DecisionContext,
207 user: User,
208 access: DecisionEnum.Access,
209 flag: ReviewFlag | None,
210) -> None:
211 """Append the read and commit it, or refuse the read: somebody else's
212 record is not served unless the log says who saw it."""
213 try:
214 db.add(
215 DecisionReadLog(
216 invocation_id=ctx.invocation_id,
217 owner_user_id=ctx.owner_user_id,
218 reader_user_id=user.id,
219 access=access.value,
220 flag_id=getattr(flag, "id", None),
221 read_at=aware_utcnow(),
222 )
223 )
224 db.commit()
225 except Exception:
226 db.rollback()
227 logger.exception(
228 "Could not log a read of decision %s by user %s",
229 ctx.invocation_id,
230 user.id,
231 )
232 raise HTTPException(
233 status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
234 detail="This record could not be opened right now. Try again.",
235 )