Coverage for app / router / app / reviews / router.py: 89%
97 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"""
2The reviewer queue — `/app/reviews`.
4The other half of `flag_for_review`. The audit action raises a flag; this is
5where a person works through them.
7Scoped by *workspace*: a flag is filed under the workspace the flagged
8invocation was made in (its owner columns), and the queue a page shows is
9that workspace's — Personal never lists an organisation's flags, nor an
10organisation a member's personal ones. Within it, a caller sees what they
11review (``membership.review_visibility``); superusers see every flag in it.
13Resolution is terminal. There is no reopen endpoint, and that is deliberate:
14it is what lets one `reviewed_by_user_id`/`reviewed_at` pair on the row stand
15in for a full version history. If reopening is ever wanted, the flag needs a
16history trail first.
17"""
19import logging
20from datetime import datetime
21from uuid import UUID
23from fastapi import APIRouter, Depends, HTTPException, Query, status
24from sqlalchemy import func, or_
25from sqlalchemy.orm import Session
27from app.services import membership
29from app.db.postgres.crud_schemas import Schema
30from app.db.postgres.enums import ReviewEnum
31from app.db.postgres.models import ReviewFlag, User
32from app.dependency.base import get_db
33from app.dependency.user.context import get_current_user
34from app.dependency.workspace import request_workspace
35from app.services import review as review_service
36from app.util.time import aware_utcnow
38logger = logging.getLogger(__name__)
40reviews_router = APIRouter(prefix="/reviews", tags=["App - Reviews"])
42#: Hard ceiling on a single page, so a client cannot ask for the whole queue.
43MAX_LIMIT = 200
46def _scoped(db: Session, current_user: User):
47 """Base query for flags the caller is entitled to see, in the workspace
48 the request was made in."""
49 query = db.query(ReviewFlag).filter(
50 review_service.in_workspace(request_workspace(db, current_user))
51 )
52 if not current_user.is_superuser:
53 # Your own flags, and those of every organisation or project you are
54 # an admin of: an organisation's rule flags for the organisation.
55 query = query.filter(membership.review_visibility(ReviewFlag, current_user))
56 return query
59def _purge(db: Session, current_user: User) -> None:
60 """Drop anything past its retention period before answering.
62 Retention is enforced here as well as by the hourly ``review_retention``
63 job, for the same reason dashboards still refresh on view: this path is
64 what covers a deployment with the scheduler disabled, or a replica that
65 is not the elected leader. A retention
66 period is therefore "deleted no earlier than" rather than "deleted exactly
67 at"; over-retention is the safer direction to be wrong in, and the
68 alternative is a promise the platform cannot keep.
69 """
70 owner = None if current_user.is_superuser else current_user.id
71 if review_service.purge_expired(db, owner):
72 db.commit()
75@reviews_router.get("/summary", response_model=Schema.Review.Summary)
76def review_summary(
77 db: Session = Depends(get_db),
78 current_user: User = Depends(get_current_user),
79):
80 """Counts per status — the queue header, and a stat widget's source.
82 Declared before /{flag_id} so the literal path is not parsed as an id.
83 """
84 _purge(db, current_user)
85 rows = (
86 _scoped(db, current_user)
87 .with_entities(ReviewFlag.status, func.count(ReviewFlag.id))
88 .group_by(ReviewFlag.status)
89 .all()
90 )
91 counts = {
92 (row[0].value if hasattr(row[0], "value") else str(row[0])): int(row[1])
93 for row in rows
94 }
95 return Schema.Review.Summary(
96 pending=counts.get("pending", 0),
97 reviewed=counts.get("reviewed", 0),
98 dismissed=counts.get("dismissed", 0),
99 total=sum(counts.values()),
100 )
103@reviews_router.get("", response_model=Schema.Review.List)
104def list_reviews(
105 status_filter: ReviewEnum.Status | None = Query(default=None, alias="status"),
106 kind: ReviewEnum.Kind | None = None,
107 q: str | None = Query(default=None, max_length=200),
108 reviewer: str | None = None,
109 rule_id: UUID | None = None,
110 agent_id: UUID | None = None,
111 since: datetime | None = None,
112 limit: int = Query(default=50, ge=1, le=MAX_LIMIT),
113 offset: int = Query(default=0, ge=0),
114 db: Session = Depends(get_db),
115 current_user: User = Depends(get_current_user),
116):
117 """The queue, newest first — audit rules' flags and regressed evaluation
118 runs (``kind``) in one list.
120 ``q`` is a free-text match over the rule name, the reviewer and the
121 excerpt. ``total`` counts everything matching the filters, not the page, so
122 a client can page through the backlog.
123 """
124 _purge(db, current_user)
126 query = _scoped(db, current_user)
127 if status_filter is not None:
128 query = query.filter(ReviewFlag.status == status_filter)
129 if kind is not None:
130 query = query.filter(ReviewFlag.kind == kind.value)
131 if q and q.strip():
132 # Searched here rather than in the browser: the client holds one page,
133 # so filtering there answers "does this term appear in the fifty flags
134 # you happen to be looking at" while looking like it searched the
135 # queue. A reviewer working a backlog would be told there is nothing.
136 term = f"%{q.strip()}%"
137 query = query.filter(
138 or_(
139 ReviewFlag.rule_name.ilike(term),
140 ReviewFlag.reviewer.ilike(term),
141 ReviewFlag.excerpt.ilike(term),
142 ReviewFlag.withheld_text.ilike(term),
143 )
144 )
145 if reviewer:
146 query = query.filter(ReviewFlag.reviewer == reviewer)
147 if rule_id:
148 query = query.filter(ReviewFlag.rule_id == rule_id)
149 if agent_id:
150 query = query.filter(ReviewFlag.agent_id == agent_id)
151 if since:
152 query = query.filter(ReviewFlag.created_at >= since)
154 total = query.count()
155 flags = (
156 query.order_by(ReviewFlag.created_at.desc()).offset(offset).limit(limit).all()
157 )
158 return Schema.Review.List(flags=_with_questions(db, flags), total=total)
161def _with_questions(db: Session, flags: list[ReviewFlag]) -> list[Schema.Review.Queued]:
162 """Each flag as the queue serves it, with the question its turn answered:
163 validated from the row (every declared field, a withheld answer
164 included — every route here is a reviewer's), then given the question."""
165 asked = review_service.questions(db, flags)
166 return [
167 Schema.Review.Queued.model_validate(flag).model_copy(
168 update={"question": asked.get(flag.id)}
169 )
170 for flag in flags
171 ]
174def _record_verdict(
175 db: Session, flag: ReviewFlag, body: Schema.Review.Resolve, reviewer: User
176) -> None:
177 """The reviewer's verdict on the flagged answer, as its decision outcome,
178 in the same transaction as the decision. A turn that is gone (its
179 conversation deleted) has nothing left to judge, and the flag still
180 resolves."""
181 from app.services import decisions
182 from app.services.decisions import outcomes
184 ctx = decisions.locate(db, flag.invocation_id)
185 if ctx is None:
186 logger.info("Flag %s resolved; its turn is gone, so no verdict", flag.id)
187 return
188 outcomes.record(
189 db,
190 ctx,
191 actor_id=reviewer.id,
192 verdict=body.verdict,
193 note=body.note,
194 source=outcomes.Source.review,
195 review_flag_id=flag.id,
196 )
199@reviews_router.get("/{flag_id}", response_model=Schema.Review.Queued)
200def get_review(
201 flag_id: UUID,
202 db: Session = Depends(get_db),
203 current_user: User = Depends(get_current_user),
204):
205 flag = db.get(ReviewFlag, flag_id)
206 if not flag:
207 raise HTTPException(
208 status_code=status.HTTP_404_NOT_FOUND, detail="Review flag not found"
209 )
210 if not review_service.may_review(db, flag, current_user):
211 raise HTTPException(
212 status_code=status.HTTP_403_FORBIDDEN,
213 detail="You do not have access to this review flag",
214 )
215 return _with_questions(db, [flag])[0]
218@reviews_router.patch("/{flag_id}", response_model=Schema.Review.Queued)
219def resolve_review(
220 flag_id: UUID,
221 body: Schema.Review.Resolve,
222 db: Session = Depends(get_db),
223 current_user: User = Depends(get_current_user),
224):
225 """Record a reviewer's decision. Terminal — an already-resolved flag is
226 not re-resolvable, so the recorded decision cannot be overwritten."""
227 flag = db.get(ReviewFlag, flag_id)
228 if not flag:
229 raise HTTPException(
230 status_code=status.HTTP_404_NOT_FOUND, detail="Review flag not found"
231 )
232 if not review_service.may_review(db, flag, current_user):
233 raise HTTPException(
234 status_code=status.HTTP_403_FORBIDDEN,
235 detail="You do not have access to this review flag",
236 )
237 if flag.status != ReviewEnum.Status.pending:
238 raise HTTPException(
239 status_code=status.HTTP_409_CONFLICT,
240 detail=(
241 f"This flag was already {flag.status.value}. A review decision "
242 "is a record, not a setting."
243 ),
244 )
246 flag.status = ReviewEnum.Status(body.status)
247 flag.reviewed_by_user_id = current_user.id
248 flag.reviewed_at = aware_utcnow()
249 flag.reviewer_note = body.note
250 if body.verdict and flag.invocation_id:
251 _record_verdict(db, flag, body, current_user)
252 try:
253 db.commit()
254 db.refresh(flag)
255 except Exception:
256 db.rollback()
257 logger.exception("Failed to resolve review flag %s", flag_id)
258 raise
259 return _with_questions(db, [flag])[0]