Coverage for app / services / review.py: 94%

181 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2The reviewer queue — where ``flag_for_review`` lands. 

3 

4An audit rule that fires ``flag_for_review`` used to produce a trace event and 

5nothing more: the flag showed up inside a conversation's execution trace, which 

6is not a place anybody reviews. This turns that event into a row somebody works 

7through. 

8 

9Three functions: 

10 

11``record_flags`` Turn the audit events from one invocation into queue rows. 

12``record_withheld`` Keep an answer an Output rule withheld, for its reviewers. 

13``purge_expired`` Delete rows whose retention period has passed. 

14 

15Flags are recorded *after* the turn is persisted, so they can point at the 

16conversation a reviewer needs to read, and so a turn that failed to persist 

17leaves no flag behind pointing at nothing. 

18""" 

19 

20from __future__ import annotations 

21 

22import logging 

23from datetime import timedelta 

24from typing import Any 

25from uuid import UUID 

26 

27from sqlalchemy.exc import SQLAlchemyError 

28from sqlalchemy.orm import Session 

29 

30from app.db.postgres.enums import ReviewEnum, RuleEnum 

31from app.db.postgres.models import ReviewFlag 

32from app.util.time import aware_utcnow 

33 

34logger = logging.getLogger(__name__) 

35 

36#: The audit action that produces a queue row. Other audit actions record 

37#: themselves in the trace and need no follow-up from a person. 

38FLAG_ACTION = "flag_for_review" 

39 

40#: How much of the flagged response to keep alongside the flag. Enough to 

41#: triage from the queue without opening the conversation; not so much that the 

42#: queue becomes a second copy of every conversation it points at. 

43EXCERPT_LIMIT = 2000 

44 

45 

46def _uuid(value: Any) -> UUID | None: 

47 """UUID form of ``value``, or None when absent or malformed.""" 

48 if value is None: 

49 return None 

50 if isinstance(value, UUID): 

51 return value 

52 try: 

53 return UUID(str(value)) 

54 except (ValueError, AttributeError, TypeError): 

55 return None 

56 

57 

58def _scope(value: Any) -> RuleEnum.Scope | None: 

59 if isinstance(value, RuleEnum.Scope): 

60 return value 

61 if not value: 

62 return None 

63 try: 

64 return RuleEnum.Scope["global_" if value == "global" else str(value)] 

65 except KeyError: 

66 return None 

67 

68 

69def _retention_expiry(event: dict[str, Any]): 

70 """When this flag may be purged, or None to keep it indefinitely. 

71 

72 Indefinite is the default on purpose: a retention period is a deliberate 

73 decision to destroy audit evidence, so it has to be stated on the rule 

74 rather than inherited from a platform default nobody chose. 

75 """ 

76 raw = event.get("retention_days") 

77 if raw in (None, ""): 

78 return None 

79 try: 

80 days = float(raw) 

81 except (TypeError, ValueError): 

82 logger.warning( 

83 "flag_for_review retention_days %r is not a number — the flag will " 

84 "be kept indefinitely", 

85 raw, 

86 ) 

87 return None 

88 if days <= 0: 

89 return None 

90 return aware_utcnow() + timedelta(days=days) 

91 

92 

93def _rule_owners(db: Session, rule_ids: list[Any]) -> dict[str, tuple]: 

94 """``rule id → (owner_organisation_id, owner_project_id)`` for the rules 

95 that flagged — both None for a personal rule.""" 

96 from app.db.postgres.models import Rule 

97 

98 ids = [i for i in (_uuid(r) for r in rule_ids) if i is not None] 

99 if not ids: 

100 return {} 

101 rows = ( 

102 db.query(Rule.id, Rule.owner_organisation_id, Rule.owner_project_id) 

103 .filter(Rule.id.in_(ids)) 

104 .all() 

105 ) 

106 return {str(r.id): (r.owner_organisation_id, r.owner_project_id) for r in rows} 

107 

108 

109def _workspace(db: Session, key: Any, cache: dict[str, Any]): 

110 """The workspace an event names, read once per key; None for none.""" 

111 if not key: 

112 return None 

113 if key not in cache: 

114 from app.services import workspace as workspace_service 

115 

116 try: 

117 cache[key] = workspace_service.from_key(db, str(key)) 

118 except Exception: 

119 cache[key] = None 

120 return cache[key] 

121 

122 

123def may_review(db: Session, flag: ReviewFlag, user: Any) -> bool: 

124 """Whether ``user`` may open and resolve ``flag`` — and so read the 

125 decision record of the turn it flagged (``app/services/decisions``). 

126 

127 A superuser may review anything. A flag filed under an organisation or 

128 project is its governance editors' (and, raised there by an 

129 organisation's rule, that organisation's: ``membership. 

130 reviews_for_owner``); a personal flag is its owner's. 

131 """ 

132 if getattr(user, "is_superuser", False): 

133 return True 

134 if flag.owner_organisation_id or flag.owner_project_id: 

135 from app.services import membership 

136 

137 return membership.reviews_for_owner(db, flag, user) 

138 return flag.owner_user_id == user.id 

139 

140 

141def record_flags( 

142 db: Session, 

143 events: list[dict[str, Any]] | None, 

144 *, 

145 owner_user_id: str | UUID, 

146 response: str | None = None, 

147 execution_type: str | None = None, 

148 conversation_id: str | UUID | None = None, 

149 agent_id: str | UUID | None = None, 

150 ai_model_id: str | UUID | None = None, 

151 workspace: Any = None, 

152 invocation_id: str | UUID | None = None, 

153) -> list[ReviewFlag]: 

154 """Create a queue row for every ``flag_for_review`` event in ``events``. 

155 

156 ``invocation_id`` is the flagged turn (``rule_engine.new_invocation_id``), 

157 so a flag opens the decision record of the answer it is about. 

158 

159 A flag lands in the review queue of the workspace the invocation 

160 happened in — ``workspace``, or the one the rule engine stamped on the 

161 event — so a project's reviewers see what its rules, and the rules it 

162 inherits, flagged there. One raised in an organisation's project by the 

163 organisation's rule also names the organisation 

164 (``rule_organisation_id``), whose governance editors see it too. An 

165 event with no workspace (one svc-ai enforced and reported back) goes to 

166 the rule's owner, as before workspaces. 

167 

168 ``events`` may mix flags enforced here with flags svc-ai enforced and 

169 reported back — they carry the same identity fields, so a reviewer never 

170 has to know which service noticed. 

171 

172 **One flag per rule per turn.** A forwarded audit rule runs in svc-ai on 

173 the finished answer and here on the same answer, and a turn that paused 

174 is audited at the pause too; each raised its own flag, so one flagged 

175 answer showed as two or three items. Repeats in ``events`` collapse to 

176 the last (svc-core's own, which carries its workspace), and a rule that 

177 already flagged ``invocation_id`` — a skill run's pause, say — is not 

178 flagged again. 

179 

180 Does not commit; the caller owns the transaction. 

181 

182 Never raises. A flag is a record *about* an invocation that has already 

183 happened and already been persisted — failing the user's request because 

184 the queue write failed would compound one problem into two. The failure is 

185 logged loudly instead. 

186 """ 

187 flagged = _one_per_rule( 

188 event 

189 for event in (events or []) 

190 if isinstance(event, dict) and event.get("action") == FLAG_ACTION 

191 ) 

192 if not flagged: 

193 return [] 

194 

195 excerpt = (response or "")[:EXCERPT_LIMIT] or None 

196 created: list[ReviewFlag] = [] 

197 try: 

198 turn = _uuid(invocation_id) 

199 if turn is not None: 

200 already = { 

201 str(rule_id) 

202 for (rule_id,) in db.query(ReviewFlag.rule_id) 

203 .filter(ReviewFlag.invocation_id == turn) 

204 .all() 

205 } 

206 flagged = [e for e in flagged if _rule_key(e) not in already] 

207 if not flagged: 

208 return [] 

209 owners = _rule_owners(db, [event.get("rule_id") for event in flagged]) 

210 workspaces: dict[str, Any] = {} 

211 for event in flagged: 

212 ws = workspace or _workspace(db, event.get("workspace"), workspaces) 

213 flag = ReviewFlag( 

214 owner_user_id=_uuid(owner_user_id), 

215 **_placement(owners.get(str(event.get("rule_id")), (None, None)), ws), 

216 rule_id=_uuid(event.get("rule_id")), 

217 rule_name=event.get("rule"), 

218 rule_version=event.get("rule_version"), 

219 scope_type=_scope(event.get("scope_type")), 

220 scope_id=_uuid(event.get("scope_id")), 

221 reviewer=event.get("reviewer"), 

222 execution_type=execution_type, 

223 conversation_id=_uuid(conversation_id), 

224 agent_id=_uuid(agent_id), 

225 ai_model_id=_uuid(ai_model_id), 

226 invocation_id=_uuid(invocation_id), 

227 # Taken after audit rules have run, so a rule that redacts PII 

228 # has already done so — the queue must not become the one place 

229 # the unredacted text survives. 

230 excerpt=excerpt, 

231 status=ReviewEnum.Status.pending, 

232 created_at=aware_utcnow(), 

233 expires_at=_retention_expiry(event), 

234 ) 

235 db.add(flag) 

236 created.append(flag) 

237 logger.info( 

238 "Recorded %d review flag(s) for user %s", len(created), owner_user_id 

239 ) 

240 except Exception: 

241 logger.exception( 

242 "Could not record review flags for user %s — the invocation stands, " 

243 "but it will not appear in the reviewer queue", 

244 owner_user_id, 

245 ) 

246 return created 

247 

248 

249def _placement(rule_owner: tuple[Any, Any], ws: Any) -> dict[str, Any]: 

250 """Which queue an item lands in: the workspace it happened in — a 

251 project's, an organisation's, or (neither) the person's own — and, for an 

252 organisation's rule acting in one of its projects, that organisation, whose 

253 reviewers see it too. With no workspace, the rule's owner's.""" 

254 rule_org, rule_project = rule_owner 

255 organisation_id, project_id = rule_org, rule_project 

256 rule_organisation_id = None 

257 if ws is not None: 

258 stamp = ws.ledger_stamp() 

259 project_id = stamp["owner_project_id"] 

260 organisation_id = ( 

261 None if project_id is not None else stamp["owner_organisation_id"] 

262 ) 

263 if ( 

264 project_id is not None 

265 and rule_org is not None 

266 and stamp["owner_organisation_id"] == rule_org 

267 ): 

268 rule_organisation_id = rule_org 

269 return { 

270 "owner_organisation_id": organisation_id, 

271 "owner_project_id": project_id, 

272 "rule_organisation_id": rule_organisation_id, 

273 } 

274 

275 

276def record_withheld( 

277 db: Session, 

278 withheld: Any, 

279 *, 

280 owner_user_id: str | UUID, 

281 execution_type: str | None = None, 

282 conversation_id: str | UUID | None = None, 

283 agent_id: str | UUID | None = None, 

284 ai_model_id: str | UUID | None = None, 

285 workspace: Any = None, 

286 invocation_id: str | UUID | None = None, 

287) -> ReviewFlag | None: 

288 """Keep an answer an Output rule withheld (``rule_engine.Withheld``) on a 

289 review item of kind ``withheld``, when its rule sends it to review. 

290 

291 The item is filed like a flag (the workspace's queue), and the answer — 

292 redacted by the turn's other Output rules — is on ``withheld_text``, 

293 which only the queue serves, to those who may review it. ``excerpt`` 

294 stays empty: the decision record, which the person the answer was 

295 withheld from may read, lists the turn's items with their excerpts. 

296 

297 Once per turn and rule. Does not commit; never raises. 

298 """ 

299 if withheld is None or not getattr(withheld, "review", False): 

300 return None 

301 ref = withheld.ref or {} 

302 try: 

303 turn = _uuid(invocation_id) 

304 rule_id = _uuid(ref.get("rule_id")) 

305 if turn is not None: 

306 existing = ( 

307 db.query(ReviewFlag.id) 

308 .filter( 

309 ReviewFlag.invocation_id == turn, 

310 ReviewFlag.kind == ReviewEnum.Kind.withheld.value, 

311 ReviewFlag.rule_id == rule_id, 

312 ) 

313 .first() 

314 ) 

315 if existing is not None: 

316 return None 

317 owners = _rule_owners(db, [ref.get("rule_id")]) 

318 ws = workspace or _workspace(db, withheld.workspace, {}) 

319 item = ReviewFlag( 

320 kind=ReviewEnum.Kind.withheld.value, 

321 owner_user_id=_uuid(owner_user_id), 

322 **_placement(owners.get(str(ref.get("rule_id")), (None, None)), ws), 

323 rule_id=rule_id, 

324 rule_name=ref.get("rule"), 

325 rule_version=ref.get("rule_version"), 

326 scope_type=_scope(ref.get("scope_type")), 

327 scope_id=_uuid(ref.get("scope_id")), 

328 execution_type=execution_type, 

329 conversation_id=_uuid(conversation_id), 

330 agent_id=_uuid(agent_id), 

331 ai_model_id=_uuid(ai_model_id), 

332 invocation_id=turn, 

333 withheld_text=withheld.original, 

334 status=ReviewEnum.Status.pending, 

335 created_at=aware_utcnow(), 

336 ) 

337 db.add(item) 

338 logger.info("Kept a withheld answer for review (user %s)", owner_user_id) 

339 return item 

340 except Exception: 

341 logger.exception( 

342 "Could not keep a withheld answer for review (user %s) — it was " 

343 "withheld all the same", 

344 owner_user_id, 

345 ) 

346 return None 

347 

348 

349def _rule_key(event: dict[str, Any]) -> str: 

350 return str(event.get("rule_id") or event.get("rule") or "") 

351 

352 

353def _one_per_rule(events: Any) -> list[dict[str, Any]]: 

354 """The last event of each rule, in the order the rules first flagged.""" 

355 by_rule: dict[str, dict[str, Any]] = {} 

356 for event in events: 

357 key = _rule_key(event) 

358 by_rule.pop(key, None) 

359 by_rule[key] = event 

360 return list(by_rule.values()) 

361 

362 

363def questions(db: Session, flags: list[ReviewFlag]) -> dict[UUID, str]: 

364 """The question each rule flag's turn answered, by flag id — the stored 

365 question (after the policy rules ran) of the answer, or the skill run's 

366 request — cut like the excerpt. Read from the turn rather than copied 

367 onto the flag, so it goes when the conversation does. Flags from before 

368 turns had ids (migration 91) have none.""" 

369 from app.db.postgres.enums import MessageEnum 

370 from app.db.postgres.models import ChatMessage, SkillRun 

371 

372 turns = {f.invocation_id for f in flags if getattr(f, "invocation_id", None)} 

373 if not turns: 

374 return {} 

375 asked: dict[UUID, str] = {} 

376 for turn, content in ( 

377 db.query(ChatMessage.invocation_id, ChatMessage.content) 

378 .filter( 

379 ChatMessage.invocation_id.in_(turns), 

380 ChatMessage.role == MessageEnum.Role.USER, 

381 ) 

382 .all() 

383 ): 

384 asked[turn] = content 

385 for turn, prompt, task in ( 

386 db.query(SkillRun.invocation_id, SkillRun.prompt, SkillRun.task) 

387 .filter(SkillRun.invocation_id.in_(turns)) 

388 .all() 

389 ): 

390 asked.setdefault(turn, prompt or task or "") 

391 return { 

392 flag.id: asked[flag.invocation_id][:EXCERPT_LIMIT] 

393 for flag in flags 

394 if asked.get(getattr(flag, "invocation_id", None)) 

395 } 

396 

397 

398def in_workspace(ws: Any): 

399 """SQL: the flags filed under workspace ``ws`` — raised by an invocation 

400 made there. An organisation's also include those its Required rules 

401 raised in its projects (``rule_organisation_id``), which its reviewers 

402 work through beside its own.""" 

403 from sqlalchemy import or_ 

404 

405 from app.services.workspace import WorkspaceKind 

406 

407 if ws.kind is WorkspaceKind.organisation: 

408 return or_( 

409 ReviewFlag.owner_organisation_id == ws.id, 

410 ReviewFlag.rule_organisation_id == ws.id, 

411 ) 

412 return ws.filed_under(ReviewFlag) 

413 

414 

415def purge_expired(db: Session, owner_user_id: str | UUID | None = None) -> int: 

416 """Delete flags whose retention period has passed. Returns how many. 

417 

418 Called from two places. ``app.services.scheduler``'s ``review_retention`` 

419 job runs hourly across *every* owner, which is what makes a retention 

420 period mean something for a queue nobody opens; and the queue's own read 

421 path calls it for the owner being read, as the fallback for when the 

422 scheduler is off or this replica is not the leader. 

423 

424 A retention period is still "deleted no earlier than" rather than 

425 "deleted exactly at" — the job's interval bounds how late — but the gap is 

426 now an hour rather than however long until somebody next opens the queue. 

427 Over-retention remains the safer direction to be wrong in. 

428 

429 Does not commit; the caller owns the transaction. 

430 """ 

431 try: 

432 query = db.query(ReviewFlag).filter( 

433 ReviewFlag.expires_at.isnot(None), 

434 ReviewFlag.expires_at <= aware_utcnow(), 

435 ) 

436 if owner_user_id is not None: 

437 query = query.filter(ReviewFlag.owner_user_id == _uuid(owner_user_id)) 

438 deleted = query.delete(synchronize_session=False) 

439 except SQLAlchemyError: 

440 logger.exception("Could not purge expired review flags") 

441 return 0 

442 if deleted: 

443 logger.info("Purged %d expired review flag(s)", deleted) 

444 return int(deleted or 0) 

445 

446 

447def expired_counts_by_owner(db: Session) -> dict[tuple, int]: 

448 """How many flags each owner has past retention, before they are purged — 

449 keyed by ``(owner_user_id, owner_organisation_id, owner_project_id)``, so 

450 a project's flags are reported to the project, not to whoever's response 

451 was flagged. 

452 

453 Read ahead of :func:`purge_expired` so the retention job can tell each 

454 owner what it deleted of theirs. Empty on a query failure — the purge 

455 still runs, and only the feed line is lost. 

456 """ 

457 from sqlalchemy import func 

458 

459 try: 

460 rows = ( 

461 db.query( 

462 ReviewFlag.owner_user_id, 

463 ReviewFlag.owner_organisation_id, 

464 ReviewFlag.owner_project_id, 

465 func.count(ReviewFlag.id), 

466 ) 

467 .filter( 

468 ReviewFlag.expires_at.isnot(None), 

469 ReviewFlag.expires_at <= aware_utcnow(), 

470 ) 

471 .group_by( 

472 ReviewFlag.owner_user_id, 

473 ReviewFlag.owner_organisation_id, 

474 ReviewFlag.owner_project_id, 

475 ) 

476 .all() 

477 ) 

478 except SQLAlchemyError: 

479 logger.exception("Could not count expired review flags") 

480 return {} 

481 counts: dict[tuple, int] = {} 

482 for user_id, org_id, project_id, count in rows: 

483 if not count or not (user_id or org_id or project_id): 

484 continue 

485 # Filed under the workspace: a project's or organisation's flags are 

486 # its own, whoever's response was flagged. 

487 key = ( 

488 (None, None, project_id) 

489 if project_id 

490 else ((None, org_id, None) if org_id else (user_id, None, None)) 

491 ) 

492 counts[key] = counts.get(key, 0) + int(count) 

493 return counts 

494 

495 

496def record_retention_events(db: Session, counts: dict[tuple, int]) -> None: 

497 """One background event per workspace whose flags retention deleted.""" 

498 from types import SimpleNamespace 

499 

500 from app.db.postgres.enums import BackgroundEnum 

501 from app.services import background_activity 

502 

503 for (owner_user_id, org_id, project_id), count in counts.items(): 

504 background_activity.record( 

505 db, 

506 kind=BackgroundEnum.Kind.review_retention, 

507 trigger=BackgroundEnum.Trigger.scheduled, 

508 status=BackgroundEnum.Status.ok, 

509 summary=f"Deleted {count} review flag(s) past their retention period", 

510 owner=SimpleNamespace( 

511 owner_user_id=owner_user_id, 

512 owner_organisation_id=org_id, 

513 owner_project_id=project_id, 

514 ), 

515 detail={"flags_deleted": count}, 

516 )