Coverage for app / services / governance_activity.py: 83%

178 statements  

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

1""" 

2The governance activity log — evidence that the rules ran. 

3 

4``usage`` records what an invocation *consumed*, ``review`` records what a 

5rule asked a person to *look at*, and this records the evaluation itself: 

6every applicable rule, against every governed invocation, and what came of it. 

7 

8Why the rules that did nothing are the point 

9──────────────────────────────────────────── 

10 

11Before this, a rule's effects were visible only as events inside a 

12conversation's execution trace, and an action with nothing to do emitted no 

13event at all. A redaction rule over a prompt containing no PII therefore 

14looked exactly like a rule that had never been evaluated — and "was this 

15invocation governed, and by what?" is the first question an audit asks, not 

16the second. 

17 

18So every applicable rule produces a row, and :class:`GovernanceEnum.Outcome` 

19separates the four answers that matter: 

20 

21 blocked the rule refused the invocation 

22 applied it matched and its actions changed something 

23 no_change it matched, its actions ran, there was nothing to do 

24 not_matched its conditions did not hold 

25 

26``no_change`` is a rule working. ``not_matched`` is a rule correctly standing 

27aside. Neither is a failure, and neither was visible anywhere before. 

28 

29What is recorded, and what deliberately is not 

30────────────────────────────────────────────── 

31 

32``detail`` carries redaction kinds and counts (``{"redacted": {"email": 2}}``), 

33the message a block gave, and the figures a quota was judged against. It never 

34carries the matched text. A log that quoted what a redaction rule removed 

35would be a durable copy of exactly the thing the rule exists to destroy, kept 

36longer than the conversation it came from. 

37 

38Transaction semantics 

39───────────────────── 

40 

41Rows are added to the caller's session and **not committed** here, exactly as 

42``usage.record_usage`` does: the log is written in the same transaction as the 

43turn it describes, so it cannot claim to have governed an invocation that was 

44rolled back. The one place that needs care is a *blocked* turn — the rules ran 

45and refused, which is the most important thing this log records — so the call 

46sites that evaluate rules in a short-lived session commit it themselves. 

47 

48Never raises. A record *about* an invocation is worth less than the invocation: 

49failing a user's request because the log write failed would compound one 

50problem into two, and the failure is logged loudly instead. 

51""" 

52 

53from __future__ import annotations 

54 

55import logging 

56from datetime import datetime 

57from typing import Any 

58from uuid import UUID, uuid4 

59 

60from sqlalchemy import func 

61from sqlalchemy.exc import SQLAlchemyError 

62from sqlalchemy.orm import Session 

63 

64from app.db.postgres.enums import GovernanceEnum, RuleEnum 

65from app.db.postgres.models import GovernanceEvent 

66 

67logger = logging.getLogger(__name__) 

68 

69#: Action keys whose parameters are safe to keep on the event, and worth 

70#: keeping: they are the figures a reader needs to judge the decision. Any 

71#: other key an action emits is dropped rather than stored blind — an action 

72#: added later must opt its parameters in, so a future action that carries 

73#: matched text cannot start leaking it into the log by default. 

74DETAIL_KEYS: frozenset[str] = frozenset( 

75 { 

76 "redacted", 

77 "message", 

78 "reviewer", 

79 "limit", 

80 "used", 

81 "cap_usd", 

82 "spent_usd", 

83 "window_seconds", 

84 # A quota's period and what was left of it: "$31.20 of $50 this 

85 # month, resets on the 1st" is what a budget's reader wants. 

86 "period", 

87 "resets_at", 

88 "remaining_usd", 

89 "share", 

90 # Passed, and let through (``on_reach: warn``). 

91 "warned", 

92 # Room to finish a turn (``reserve``): what a turn like it usually 

93 # costs, and whether that was read from its history or the default. 

94 "reserve_usd", 

95 "reserve_basis", 

96 # A turn stopped part-way at what was left of a cap (``X-Spend-Limit``). 

97 "stopped_mid_turn", 

98 "limit_usd", 

99 # The web sources a Tools rule set on the run — domains are the 

100 # rule's own words, never what the turn searched for. 

101 "domains", 

102 "only", 

103 # A withheld answer: whether it went to review (its ``message`` is 

104 # already kept above). Never the answer itself. 

105 "review", 

106 # What a Tools rule did to the turn's web searches, settled after the 

107 # run (``services/web_search_summary.py``): counts, never a host. 

108 "web", 

109 } 

110) 

111 

112 

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

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

115 if value is None: 

116 return None 

117 if isinstance(value, UUID): 

118 return value 

119 try: 

120 return UUID(str(value)) 

121 except (ValueError, AttributeError, TypeError): 

122 return None 

123 

124 

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

126 """A scope enum from the stored key, tolerating ``global``/``global_``.""" 

127 if isinstance(value, RuleEnum.Scope): 

128 return value 

129 if not value: 

130 return None 

131 try: 

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

133 except KeyError: 

134 return None 

135 

136 

137def outcome_of( 

138 events: list[dict[str, Any]], *, blocked: bool = False 

139) -> GovernanceEnum.Outcome: 

140 """What a matched rule's actions came to. 

141 

142 ``changed`` is absent on events from actions that do something by 

143 definition (``flag_for_review``), so it defaults to True. The 

144 actions that can run and find nothing to do — the redactors — set it 

145 explicitly, and the quota actions emit no event at all while under their 

146 limit. Either way the answer is the same: nothing changed. 

147 """ 

148 if blocked: 

149 return GovernanceEnum.Outcome.blocked 

150 if any(event.get("changed", True) for event in events): 

151 return GovernanceEnum.Outcome.applied 

152 return GovernanceEnum.Outcome.no_change 

153 

154 

155def detail_of(events: list[dict[str, Any]]) -> dict[str, Any]: 

156 """The per-action specifics worth keeping, keyed by action type. 

157 

158 Filtered through :data:`DETAIL_KEYS` rather than copied wholesale, so an 

159 action cannot put text it matched into the log by accident. 

160 """ 

161 detail: dict[str, Any] = {} 

162 for event in events: 

163 action = str(event.get("action", "") or "") 

164 if not action: 

165 continue 

166 kept = { 

167 key: value 

168 for key, value in event.items() 

169 if key in DETAIL_KEYS and value not in (None, "") 

170 } 

171 if kept: 

172 detail[action] = {**detail.get(action, {}), **kept} 

173 return detail 

174 

175 

176def record( 

177 db: Session, 

178 evaluations: list[dict[str, Any]] | None, 

179 *, 

180 owner_user_id: str | UUID, 

181 phase: GovernanceEnum.Phase, 

182 enforced_in: GovernanceEnum.EnforcedIn = GovernanceEnum.EnforcedIn.core, 

183 invocation_id: str | UUID | None = None, 

184 execution_type: str | None = None, 

185 conversation_id: str | UUID | None = None, 

186 agent_id: str | UUID | None = None, 

187 ai_model_id: str | UUID | None = None, 

188 workspace: Any = None, 

189) -> list[GovernanceEvent]: 

190 """Append one row per evaluated rule. Does not commit. 

191 

192 ``workspace`` is where the invocation happened; its stamp is what a 

193 workspace's activity view reads (``scoped_query``). 

194 

195 ``evaluations`` is what :func:`app.services.rule_engine.evaluate_input` and 

196 ``evaluate_output`` build: the rule's identity block, the outcome, the 

197 actions that ran and their events. 

198 """ 

199 owner = _uuid(owner_user_id) 

200 if not evaluations or owner is None: 

201 return [] 

202 rows: list[GovernanceEvent] = [] 

203 try: 

204 stamp = workspace.ledger_stamp() if workspace is not None else {} 

205 for evaluation in evaluations: 

206 layer = evaluation.get("layer") 

207 rows.append( 

208 GovernanceEvent( 

209 id=uuid4(), 

210 owner_user_id=owner, 

211 rule_id=_uuid(evaluation.get("rule_id")), 

212 rule_name=(evaluation.get("rule") or None), 

213 rule_version=evaluation.get("rule_version"), 

214 layer=( 

215 layer 

216 if isinstance(layer, RuleEnum.Layer) 

217 else RuleEnum.Layer(str(layer)) 

218 ), 

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

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

221 phase=phase, 

222 outcome=evaluation.get("outcome"), 

223 enforced_in=enforced_in, 

224 actions=list(evaluation.get("actions") or []), 

225 detail=dict(evaluation.get("detail") or {}), 

226 invocation_id=_uuid(invocation_id), 

227 execution_type=execution_type, 

228 conversation_id=_uuid(conversation_id), 

229 agent_id=_uuid(agent_id), 

230 ai_model_id=_uuid(ai_model_id), 

231 **stamp, 

232 ) 

233 ) 

234 db.add_all(rows) 

235 except Exception: 

236 logger.exception( 

237 "Could not record governance activity for %s — the invocation is " 

238 "unaffected, but this evaluation will not appear in the log", 

239 owner, 

240 ) 

241 return [] 

242 return rows 

243 

244 

245def link_invocation( 

246 db: Session, 

247 invocation_id: str | UUID | None, 

248 *, 

249 conversation_id: str | UUID | None = None, 

250 message_id: str | UUID | None = None, 

251) -> int: 

252 """Point this invocation's events at the message they governed. 

253 

254 Called after the turn is persisted, because that is the first moment the 

255 ids exist: policy rules run before the prompt is sent and audit rules 

256 before the response is saved. Writing them back is what lets the activity 

257 log open *the exact message* a rule ran on, rather than the agent's chat 

258 at whatever it happens to be showing. 

259 

260 Updates every row of the invocation in one statement — both phases, every 

261 rule — so the link cannot end up on half a turn. 

262 

263 Does not commit; the caller owns the transaction, and the rows belong to 

264 the same one as the message they now name. Never raises: a link is an 

265 affordance on a record that already stands without it. 

266 """ 

267 invocation = _uuid(invocation_id) 

268 if invocation is None: 

269 return 0 

270 values: dict[str, Any] = {} 

271 if conversation_id is not None: 

272 values["conversation_id"] = _uuid(conversation_id) 

273 if message_id is not None: 

274 values["message_id"] = _uuid(message_id) 

275 if not values: 

276 return 0 

277 try: 

278 return ( 

279 db.query(GovernanceEvent) 

280 .filter(GovernanceEvent.invocation_id == invocation) 

281 .update(values, synchronize_session=False) 

282 ) 

283 except Exception: 

284 logger.exception( 

285 "Could not link governance activity for invocation %s to its " 

286 "message — the evaluations stand, but will not deep-link", 

287 invocation, 

288 ) 

289 return 0 

290 

291 

292def settle_tools( 

293 db: Session, 

294 invocation_id: str | UUID | None, 

295 changes: dict[str, dict[str, Any]], 

296) -> int: 

297 """Rewrite this turn's Tools rows with what the rules turned out to do. 

298 

299 A Tools rule is recorded as it runs, before the model — "applied", since 

300 its action sets the run's web sources. Only after the run is it known 

301 whether any search met it (``web_search_summary.settle``); ``changes`` 

302 maps each rule's id to its settled outcome and detail. Before the model 

303 only (``phase = input``), on this turn's rows only. 

304 

305 Does not commit; the caller's transaction is the turn's. Never raises: a 

306 settled outcome is an affordance on rows that already stand. 

307 """ 

308 invocation = _uuid(invocation_id) 

309 if invocation is None or not changes: 

310 return 0 

311 updated = 0 

312 try: 

313 for rule_id, change in changes.items(): 

314 rule = _uuid(rule_id) 

315 if rule is None: 

316 continue 

317 updated += ( 

318 db.query(GovernanceEvent) 

319 .filter( 

320 GovernanceEvent.invocation_id == invocation, 

321 GovernanceEvent.rule_id == rule, 

322 GovernanceEvent.layer == RuleEnum.Layer.tools, 

323 GovernanceEvent.phase == GovernanceEnum.Phase.input, 

324 ) 

325 .update( 

326 { 

327 GovernanceEvent.outcome: change["outcome"], 

328 GovernanceEvent.detail: dict(change.get("detail") or {}), 

329 }, 

330 synchronize_session=False, 

331 ) 

332 ) 

333 except Exception: 

334 logger.exception( 

335 "Could not settle the Tools rules of invocation %s — they keep " 

336 "reading as applied", 

337 invocation, 

338 ) 

339 return 0 

340 return updated 

341 

342 

343def commit(db: Session) -> None: 

344 """Commit activity rows appended in a session the caller is about to close. 

345 

346 The agent paths evaluate rules in a short-lived session of their own, so 

347 the rows the engine appended there would be discarded with it — including 

348 on the path that matters most, where a policy refused the invocation and 

349 the exception unwinds past the usual commit. 

350 

351 Never raises, and rolls back on failure so the session is not left in a 

352 broken state: this is called while an exception may already be in flight, 

353 and a logging failure must not replace the reason the caller is unwinding. 

354 """ 

355 try: 

356 db.commit() 

357 except SQLAlchemyError: 

358 db.rollback() 

359 logger.exception("Could not commit governance activity") 

360 

361 

362# ─── Reading ────────────────────────────────────────────────────────────────── 

363 

364 

365def scoped_query(db: Session, current_user: Any, workspace: Any = None): 

366 """Base query for events the caller is entitled to see — in one 

367 workspace when ``workspace`` (a resolved ``Workspace``) is given: the 

368 work done there, everyone's for its reviewers (admins and governance 

369 editors) and the caller's own otherwise; and for an organisation, what 

370 its rules did in its projects too.""" 

371 if workspace is not None: 

372 return _workspace_query(db, current_user, workspace) 

373 query = db.query(GovernanceEvent) 

374 if not getattr(current_user, "is_superuser", False): 

375 # The caller's own invocations, and what the rules of every 

376 # organisation or project whose governance they review (admins and 

377 # governance editors) did to anyone's. 

378 from sqlalchemy import or_, select 

379 

380 from app.db.postgres.models import Rule 

381 from app.services import membership 

382 

383 administered = select(Rule.id).where( 

384 or_( 

385 Rule.owner_organisation_id.in_( 

386 membership.reviewer_scope_ids( 

387 membership.ORGANISATION, current_user.id 

388 ) 

389 ), 

390 Rule.owner_project_id.in_( 

391 membership.reviewer_scope_ids(membership.PROJECT, current_user.id) 

392 ), 

393 ) 

394 ) 

395 query = query.filter( 

396 or_( 

397 GovernanceEvent.owner_user_id == current_user.id, 

398 GovernanceEvent.rule_id.in_(administered), 

399 ) 

400 ) 

401 return query 

402 

403 

404def _workspace_query(db: Session, current_user: Any, ws: Any): 

405 from sqlalchemy import and_, or_, select 

406 

407 from app.db.postgres.models import Rule 

408 from app.services import access, membership 

409 from app.services.workspace import WorkspaceKind 

410 

411 E = GovernanceEvent 

412 where = ws.stamped(E, projects=False) 

413 if ws.kind is WorkspaceKind.organisation: 

414 own_rules = select(Rule.id).where(Rule.owner_organisation_id == ws.id) 

415 where = or_( 

416 where, 

417 and_(E.owner_organisation_id == ws.id, E.rule_id.in_(own_rules)), 

418 ) 

419 query = db.query(E).filter(where) 

420 if ( 

421 getattr(current_user, "is_superuser", False) 

422 or ws.kind is WorkspaceKind.personal 

423 ): 

424 return query 

425 scope = ( 

426 membership.ORGANISATION 

427 if ws.kind is WorkspaceKind.organisation 

428 else membership.PROJECT 

429 ) 

430 m = membership.effective_membership(db, scope, ws.id, current_user.id) 

431 reviews = m is not None and ( 

432 access.effective(m)[access.AccessArea.governance] >= access.AccessLevel.editor 

433 ) 

434 return query if reviews else query.filter(E.owner_user_id == current_user.id) 

435 

436 

437def filtered( 

438 query: Any, 

439 *, 

440 rule_id: UUID | None = None, 

441 layer: RuleEnum.Layer | None = None, 

442 phase: GovernanceEnum.Phase | None = None, 

443 outcome: GovernanceEnum.Outcome | None = None, 

444 execution_type: str | None = None, 

445 conversation_id: UUID | None = None, 

446 since: datetime | None = None, 

447): 

448 """Apply the activity filters the page offers, skipping the unset ones.""" 

449 if rule_id is not None: 

450 query = query.filter(GovernanceEvent.rule_id == rule_id) 

451 if layer is not None: 

452 query = query.filter(GovernanceEvent.layer == layer) 

453 if phase is not None: 

454 query = query.filter(GovernanceEvent.phase == phase) 

455 if outcome is not None: 

456 query = query.filter(GovernanceEvent.outcome == outcome) 

457 if execution_type: 

458 query = query.filter(GovernanceEvent.execution_type == execution_type) 

459 if conversation_id is not None: 

460 query = query.filter(GovernanceEvent.conversation_id == conversation_id) 

461 if since is not None: 

462 query = query.filter(GovernanceEvent.created_at >= since) 

463 return query 

464 

465 

466def invocation_page( 

467 query: Any, 

468 *, 

469 limit: int, 

470 offset: int, 

471) -> tuple[list[Any], int]: 

472 """The ids of one page of *invocations*, newest first, and how many there 

473 are in total. 

474 

475 Paged by invocation rather than by event, because the page renders one 

476 card per turn: paging by row would cut a turn in half at the page 

477 boundary and show a reader half its governance. 

478 

479 An event with no ``invocation_id`` — written before the column existed, or 

480 by a path that mints none — groups under its own id rather than being 

481 lumped in with every other such row under NULL. Coalescing is what makes 

482 that work in one query: the fallback is the event's own primary key, which 

483 is unique, so each stands alone. 

484 """ 

485 key = func.coalesce(GovernanceEvent.invocation_id, GovernanceEvent.id) 

486 grouped = query.with_entities( 

487 key.label("invocation"), 

488 func.max(GovernanceEvent.created_at).label("latest"), 

489 ).group_by(key) 

490 total = grouped.count() 

491 rows = ( 

492 grouped.order_by(func.max(GovernanceEvent.created_at).desc()) 

493 .offset(offset) 

494 .limit(limit) 

495 .all() 

496 ) 

497 return [row[0] for row in rows], total 

498 

499 

500def events_for(query: Any, invocation_ids: list[Any]) -> list[GovernanceEvent]: 

501 """Every event of the given invocations, oldest first. 

502 

503 Oldest first *within* a group on purpose: a turn reads in the order it 

504 happened — what the policy rules did to the prompt, then what the audit 

505 rules did to the response — while the groups themselves are newest first. 

506 """ 

507 if not invocation_ids: 

508 return [] 

509 key = func.coalesce(GovernanceEvent.invocation_id, GovernanceEvent.id) 

510 return ( 

511 query.filter(key.in_(invocation_ids)) 

512 .order_by(GovernanceEvent.created_at.asc()) 

513 .all() 

514 ) 

515 

516 

517def group(events: list[GovernanceEvent]) -> list[dict[str, Any]]: 

518 """Fold a flat list of events into one entry per invocation. 

519 

520 The order events arrive in is the order they are kept in, so a caller that 

521 sorted its query has already decided how the page reads. 

522 """ 

523 groups: dict[Any, dict[str, Any]] = {} 

524 for event in events: 

525 key = event.invocation_id or event.id 

526 entry = groups.get(key) 

527 if entry is None: 

528 entry = { 

529 "invocation_id": event.invocation_id, 

530 "occurred_at": event.created_at, 

531 "execution_type": event.execution_type, 

532 "conversation_id": event.conversation_id, 

533 "message_id": event.message_id, 

534 "agent_id": event.agent_id, 

535 "ai_model_id": event.ai_model_id, 

536 "events": [], 

537 "outcomes": {outcome.value: 0 for outcome in GovernanceEnum.Outcome}, 

538 } 

539 groups[key] = entry 

540 entry["events"].append(event) 

541 outcome = event.outcome 

542 entry["outcomes"][ 

543 outcome.value if hasattr(outcome, "value") else str(outcome) 

544 ] += 1 

545 # The turn is stamped with when it started; its later events are the 

546 # same turn, not a second one. 

547 if event.created_at and ( 

548 entry["occurred_at"] is None or event.created_at < entry["occurred_at"] 

549 ): 

550 entry["occurred_at"] = event.created_at 

551 # A group's identity comes from whichever of its events knows most: 

552 # the input phase of a model prompt has no conversation yet, and the 

553 # output phase does. 

554 for field in ( 

555 "execution_type", 

556 "conversation_id", 

557 "message_id", 

558 "agent_id", 

559 "ai_model_id", 

560 ): 

561 if entry[field] is None: 

562 entry[field] = getattr(event, field) 

563 return list(groups.values()) 

564 

565 

566def summarise(query: Any) -> dict[str, int]: 

567 """Counts per outcome over the *filtered* set, for the page header. 

568 

569 Computed in the database rather than from the returned page: a summary 

570 that only counted the fifty rows on screen would answer a different 

571 question from the one it appears to. 

572 """ 

573 counts = {outcome.value: 0 for outcome in GovernanceEnum.Outcome} 

574 rows = ( 

575 query.with_entities(GovernanceEvent.outcome, func.count(GovernanceEvent.id)) 

576 .group_by(GovernanceEvent.outcome) 

577 .all() 

578 ) 

579 for outcome, count in rows: 

580 key = outcome.value if hasattr(outcome, "value") else str(outcome) 

581 counts[key] = int(count) 

582 counts["total"] = sum(value for key, value in counts.items() if key != "total") 

583 return counts