Coverage for app / services / stats / dimensions.py: 89%

376 statements  

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

1""" 

2Dimensions — *what* a platform metric is sliced by. 

3 

4One class per dimension, registered with :func:`register_dimension`, mirroring 

5how rule scopes, conditions, actions and widget types already work. A 

6dimension owns three things: the ledger column its buckets are keyed on, how 

7to narrow the ledger to one bucket, and how to turn the keys it produced back 

8into names a person recognises. 

9 

10────────────────────────────────────────────────────────────────────────────── 

11Why these and not others 

12────────────────────────────────────────────────────────────────────────────── 

13 

14A dimension can only exist if the ledger records it. ``governance_usage`` 

15stamps the resource that ran (``scope_type`` + ``scope_id``), the project and 

16organisation it belongs to, how the invocation was started, and whether it 

17came back — so those are the dimensions, and adding one means the ledger 

18learning a new column first, not this module gaining a branch. 

19 

20``skill`` buckets standalone skill runs, which are scoped to the skill. A 

21skill run *through an agent* is still recorded against the agent, because 

22that is the resource whose quota it consumes. ``worker`` is registered and 

23produces nothing yet: no invocation is scoped to a worker. Registering it 

24anyway is deliberate — it is a real scope with real rules written against it, 

25and a dimension that returns nothing is an honest answer. 

26 

27``source`` is the other axis: not what ran, but what the spend is 

28*attributed* to — the dashboard a tile belongs to, the evaluation a cell was 

29part of. See ``services/llm_paths.py`` and ``docs/guides/cost-monitoring.md``. 

30 

31────────────────────────────────────────────────────────────────────────────── 

32Labels 

33────────────────────────────────────────────────────────────────────────────── 

34 

35Buckets are keyed by id and named on the way out, never denormalised onto the 

36ledger row. The ledger is audit evidence that has to outlive the agent it 

37describes, but while the agent exists its *current* name is the one a reader 

38recognises — the same trade the governance activity log makes. A bucket whose 

39resource has been deleted keeps its id and says so. 

40""" 

41 

42from __future__ import annotations 

43 

44import logging 

45from abc import ABC, abstractmethod 

46from typing import Any, ClassVar 

47from uuid import UUID 

48 

49from sqlalchemy.sql.elements import ColumnElement 

50 

51from app.db.postgres.enums import RuleEnum, UsageEnum 

52from app.services import llm_paths 

53from app.services.rules import scopes as scope_registry 

54 

55logger = logging.getLogger(__name__) 

56 

57 

58class Dimension(ABC): 

59 """One axis a metric can be broken down by.""" 

60 

61 #: Stable key, sent over the API and stored in widget config. 

62 key: ClassVar[str] 

63 #: Which sources this axis can slice. A tuple rather than one key because 

64 #: the redaction expansion carries every governance-event column, so "what 

65 #: did rule X redact?" is the same axis as "how often did rule X block?" 

66 #: — a second, parallel definition of "rule" would be a thing to keep in 

67 #: sync for no gain. 

68 sources: ClassVar[tuple[str, ...]] = ("usage",) 

69 #: Human label for the dimension picker. 

70 label: ClassVar[str] 

71 #: One line explaining what a bucket of this dimension is. 

72 description: ClassVar[str] = "" 

73 #: Plural noun for the axis, e.g. "agents" — used in empty states. 

74 plural: ClassVar[str] = "" 

75 #: Whether a bucket key is an opaque id needing resolution to a name. 

76 resolves_names: ClassVar[bool] = True 

77 

78 # -- query ---------------------------------------------------------- 

79 

80 @abstractmethod 

81 def group_column(self) -> ColumnElement: 

82 """The ledger column whose distinct values are this axis' buckets.""" 

83 

84 def row_filters(self) -> list[Any]: 

85 """Filters restricting the ledger to rows this axis can bucket. 

86 

87 A polymorphic axis needs one: ``scope_id`` holds an agent id on one 

88 row and a model id on the next, so grouping it without first pinning 

89 ``scope_type`` would mix two populations into one chart and give every 

90 bucket a name from the wrong table. 

91 """ 

92 return [] 

93 

94 def value_filters(self, value: str) -> list[Any]: 

95 """Filters narrowing the ledger to the single bucket ``value``. 

96 

97 This is what makes a stat tile sayable: "spend, for this agent, this 

98 month" is the same query as the breakdown with one more clause. 

99 """ 

100 column = self.group_column() 

101 coerced = self.coerce(value) 

102 if coerced is None: 

103 # A filter that cannot be honoured must not silently widen to 

104 # "everything" — the tile would then show the account's total 

105 # under a label naming one agent, which is worse than an error. 

106 raise ValueError(f"'{value}' is not a valid {self.key}.") 

107 return [*self.row_filters(), column == coerced] 

108 

109 def coerce(self, value: str) -> Any: 

110 """``value`` in the column's own type, or None when it is not one.""" 

111 try: 

112 return UUID(str(value)) 

113 except (ValueError, AttributeError, TypeError): 

114 return None 

115 

116 # -- labels --------------------------------------------------------- 

117 

118 def labels(self, db: Any, keys: list[str]) -> dict[str, str]: 

119 """Display names for the bucket keys this axis produced. 

120 

121 One query for the whole page rather than a lookup per bucket. Keys 

122 that resolve to nothing are simply absent, and the caller decides how 

123 to render a bucket whose resource has been deleted. 

124 """ 

125 return {} 

126 

127 # -- catalogue ------------------------------------------------------ 

128 

129 def spec(self) -> dict[str, Any]: 

130 """Catalogue entry for this dimension, for the widget editor.""" 

131 return { 

132 "key": self.key, 

133 "label": self.label, 

134 "description": self.description, 

135 "plural": self.plural, 

136 "resolves_names": self.resolves_names, 

137 "sources": list(self.sources), 

138 } 

139 

140 

141# ─── Registry ───────────────────────────────────────────────────────────────── 

142 

143_REGISTRY: dict[str, Dimension] = {} 

144#: Insertion order is the order the picker offers them, so the registration 

145#: order below is the UI's ordering decision — declared once, not sorted on 

146#: a field that would have to be kept meaningful. 

147_ORDER: list[str] = [] 

148 

149 

150def register_dimension(cls: type[Dimension]) -> type[Dimension]: 

151 """Class decorator adding one dimension to the registry.""" 

152 instance = cls() 

153 if instance.key in _REGISTRY: 

154 raise RuntimeError(f"Stat dimension '{instance.key}' is already registered.") 

155 _REGISTRY[instance.key] = instance 

156 _ORDER.append(instance.key) 

157 return cls 

158 

159 

160def get_dimension(key: str | None) -> Dimension | None: 

161 """The dimension registered under ``key``, or None if there is none.""" 

162 if not key: 

163 return None 

164 return _REGISTRY.get(str(key)) 

165 

166 

167def dimension_keys() -> frozenset[str]: 

168 """Every registered dimension key.""" 

169 return frozenset(_REGISTRY) 

170 

171 

172def catalogue() -> list[dict[str, Any]]: 

173 """Registered dimensions, in picker order.""" 

174 return [_REGISTRY[key].spec() for key in _ORDER] 

175 

176 

177def dimensions_for_source(source: str) -> list[Dimension]: 

178 """Every dimension that can slice ``source``, in picker order.""" 

179 return [_REGISTRY[key] for key in _ORDER if source in _REGISTRY[key].sources] 

180 

181 

182# ─── Resource dimensions ────────────────────────────────────────────────────── 

183 

184 

185class ResourceDimension(Dimension): 

186 """A dimension bucketing on the resource the invocation ran as. 

187 

188 Every one of these is one line of definition plus a scope key, because the 

189 rule scope registry already answers both questions this needs: how to 

190 narrow the ledger to that kind of resource, and which table names it. A 

191 second, parallel description of "what an agent is" would be a thing to 

192 keep in sync for no gain. 

193 """ 

194 

195 #: The rule scope whose ledger rows this dimension buckets. 

196 scope: ClassVar[RuleEnum.Scope] 

197 

198 def group_column(self) -> ColumnElement: 

199 from app.db.postgres.models import GovernanceUsage 

200 

201 return GovernanceUsage.scope_id 

202 

203 def row_filters(self) -> list[Any]: 

204 from app.db.postgres.models import GovernanceUsage 

205 

206 return [GovernanceUsage.scope_type == self.scope] 

207 

208 def labels(self, db: Any, keys: list[str]) -> dict[str, str]: 

209 scope = scope_registry.get_scope(self.scope) 

210 model = scope.target_model() if scope else None 

211 if model is None or not keys: 

212 return {} 

213 ids = [parsed for parsed in (self.coerce(key) for key in keys) if parsed] 

214 if not ids: 

215 return {} 

216 try: 

217 rows = db.query(model).filter(model.id.in_(ids)).all() 

218 except Exception: # a missing name is not a failed page 

219 logger.exception( 

220 "Could not resolve %s names for a stats breakdown", self.key 

221 ) 

222 return {} 

223 return {str(row.id): row.name for row in rows} 

224 

225 

226@register_dimension 

227class AgentDimension(ResourceDimension): 

228 key = "agent" 

229 label = "Agent" 

230 description = "One bucket per agent that ran, including the skills it ran." 

231 plural = "agents" 

232 scope = RuleEnum.Scope.agent 

233 

234 

235@register_dimension 

236class ModelDimension(ResourceDimension): 

237 key = "model" 

238 label = "Model" 

239 description = "One bucket per model prompted directly." 

240 plural = "models" 

241 scope = RuleEnum.Scope.model 

242 

243 def labels(self, db: Any, keys: list[str]) -> dict[str, str]: 

244 """Models are svc-ai's records, so the names come from svc-ai. 

245 

246 The governance activity log deliberately does not resolve them — it 

247 would put a cross-service call on a log page where the execution type 

248 already says what ran. A breakdown *by model* is different: without 

249 the name every bar is a UUID, which is not a chart. So the call is 

250 made, once for the page, and a svc-ai outage costs the labels rather 

251 than the figures. 

252 """ 

253 from app.services.ai_client import list_models 

254 

255 if not keys: 

256 return {} 

257 try: 

258 models = list_models() or [] 

259 except Exception: # noqa: BLE001 — any transport fault means "no names" 

260 logger.warning( 

261 "Model catalogue unavailable; a stats breakdown by model will " 

262 "show ids instead of names" 

263 ) 

264 return {} 

265 wanted = set(keys) 

266 named: dict[str, str] = {} 

267 for model in models: 

268 model_id = str(model.get("id") or "") 

269 if model_id in wanted: 

270 named[model_id] = str( 

271 model.get("model_name") or model.get("name") or model_id 

272 ) 

273 return named 

274 

275 

276@register_dimension 

277class SkillDimension(ResourceDimension): 

278 key = "skill" 

279 label = "Skill" 

280 description = ( 

281 "One bucket per skill run in its own right. A skill run through an " 

282 "agent is recorded against that agent." 

283 ) 

284 plural = "skills" 

285 scope = RuleEnum.Scope.skill 

286 

287 

288@register_dimension 

289class WorkerDimension(ResourceDimension): 

290 key = "worker" 

291 label = "Worker" 

292 description = "One bucket per worker run in its own right." 

293 plural = "workers" 

294 scope = RuleEnum.Scope.worker 

295 

296 

297# ─── Ownership dimensions ───────────────────────────────────────────────────── 

298 

299 

300class OwnershipDimension(Dimension): 

301 """A dimension bucketing on who the invoked resource belonged to. 

302 

303 Not a scope column: no ledger row is ever *scoped* to a project, because 

304 no invocation names one. The row records what ran and, alongside it, where 

305 that lives. These are the axes ownership-scoped quotas already count on. 

306 """ 

307 

308 #: Name of the ledger column carrying the owning resource's id. 

309 column_name: ClassVar[str] 

310 #: Model naming the owner, looked up lazily to keep this import-safe. 

311 model_name: ClassVar[str] 

312 

313 def group_column(self) -> ColumnElement: 

314 from app.db.postgres import models 

315 

316 return getattr(models.GovernanceUsage, self.column_name) 

317 

318 def labels(self, db: Any, keys: list[str]) -> dict[str, str]: 

319 from app.db.postgres import models 

320 

321 model = getattr(models, self.model_name) 

322 ids = [parsed for parsed in (self.coerce(key) for key in keys) if parsed] 

323 if not ids: 

324 return {} 

325 try: 

326 rows = db.query(model).filter(model.id.in_(ids)).all() 

327 except Exception: # a missing name is not a failed page 

328 logger.exception( 

329 "Could not resolve %s names for a stats breakdown", self.key 

330 ) 

331 return {} 

332 return {str(row.id): row.name for row in rows} 

333 

334 

335@register_dimension 

336class ProjectDimension(OwnershipDimension): 

337 key = "project" 

338 label = "Project" 

339 description = "One bucket per project, counting everything owned by it." 

340 plural = "projects" 

341 column_name = "owner_project_id" 

342 model_name = "Project" 

343 

344 

345@register_dimension 

346class OrganisationDimension(OwnershipDimension): 

347 key = "organisation" 

348 label = "Organisation" 

349 description = "One bucket per organisation, counting everything inside it." 

350 plural = "organisations" 

351 column_name = "owner_organisation_id" 

352 model_name = "Organisation" 

353 

354 

355# ─── Categorical dimensions ─────────────────────────────────────────────────── 

356 

357 

358class CategoricalDimension(Dimension): 

359 """A dimension whose buckets are a fixed vocabulary, not ids. 

360 

361 ``resolves_names`` is False because a bucket never goes *missing* — there 

362 is no row behind it to delete — so an unrecognised key is shown as-is 

363 rather than marked as a deleted resource. It can still be given a nicer 

364 caption than the stored token, from a static map that touches no database. 

365 """ 

366 

367 resolves_names = False 

368 #: Stored value → what a reader should see. A value absent from the map 

369 #: renders as itself, which is the right answer for one this app has not 

370 #: met: a new execution type should appear on the chart, not vanish. 

371 display_names: ClassVar[dict[str, str]] = {} 

372 

373 def coerce(self, value: str) -> Any: 

374 return str(value) if value else None 

375 

376 def labels(self, db: Any, keys: list[str]) -> dict[str, str]: 

377 return { 

378 key: self.display_names[key] for key in keys if key in self.display_names 

379 } 

380 

381 

382@register_dimension 

383class ExecutionTypeDimension(CategoricalDimension): 

384 key = "execution_type" 

385 label = "Execution type" 

386 description = ( 

387 "How the invocation was started — an agent turn, a direct prompt, a " 

388 "skill run, an evaluation, a dashboard tile, a generation flow, a " 

389 "knowledge search or indexing." 

390 ) 

391 plural = "execution types" 

392 # One label per path in the LLM path registry, so a type a new path 

393 # writes has a caption the moment it exists. 

394 display_names: ClassVar[dict[str, str]] = llm_paths.EXECUTION_TYPE_LABELS 

395 

396 def group_column(self) -> ColumnElement: 

397 from app.db.postgres.models import GovernanceUsage 

398 

399 return GovernanceUsage.execution_type 

400 

401 

402@register_dimension 

403class SourceDimension(CategoricalDimension): 

404 """What the spend is attributed to — the kind of resource that caused it. 

405 

406 Not the scope: a dashboard tile runs as the agent it borrows, and its row 

407 is scoped to that agent but sourced to the dashboard. "Spend by source" 

408 answers "is it the agents, the evaluations or the dashboards?" — the first 

409 question a cost review asks. Rows written before migration 69 that could 

410 not be attributed have none, and fold into the unattributed bucket. 

411 """ 

412 

413 key = "source" 

414 label = "Source" 

415 description = ( 

416 "What caused the spend — agents, skills, evaluations, dashboards, " 

417 "generation, knowledge or simulations." 

418 ) 

419 plural = "sources" 

420 display_names: ClassVar[dict[str, str]] = llm_paths.SOURCE_LABELS 

421 

422 def group_column(self) -> ColumnElement: 

423 from app.db.postgres.models import GovernanceUsage 

424 

425 return GovernanceUsage.source_type 

426 

427 

428@register_dimension 

429class OutcomeDimension(CategoricalDimension): 

430 key = "outcome" 

431 label = "Outcome" 

432 description = "Whether the invocation came back or failed." 

433 plural = "outcomes" 

434 display_names: ClassVar[dict[str, str]] = { 

435 "ok": "Succeeded", 

436 "error": "Failed", 

437 } 

438 

439 def group_column(self) -> ColumnElement: 

440 from app.db.postgres.models import GovernanceUsage 

441 

442 return GovernanceUsage.outcome 

443 

444 def coerce(self, value: str) -> Any: 

445 try: 

446 return UsageEnum.Outcome(str(value)) 

447 except ValueError: 

448 return None 

449 

450 

451# ─── Governance dimensions ──────────────────────────────────────────────────── 

452# 

453# These slice ``governance_events`` and, because the redaction expansion 

454# carries every one of that table's columns, the redaction source too. So 

455# "what has this rule redacted, by kind?" and "how often has it blocked?" are 

456# the same two axes over two sources rather than four definitions. 

457 

458#: Both governance-shaped sources, named once so a new dimension cannot be 

459#: added to one and forgotten on the other. 

460GOVERNANCE_SOURCES = ("governance", "redactions") 

461 

462 

463class EventColumnDimension(Dimension): 

464 """A dimension bucketing on one column of ``governance_events``.""" 

465 

466 sources = GOVERNANCE_SOURCES 

467 #: Attribute name on the model. 

468 column_name: ClassVar[str] 

469 

470 def group_column(self) -> ColumnElement: 

471 from app.db.postgres.models import GovernanceEvent 

472 

473 return getattr(GovernanceEvent, self.column_name) 

474 

475 

476class EventEnumDimension(EventColumnDimension): 

477 """A governance column whose values are a fixed enum vocabulary.""" 

478 

479 resolves_names = False 

480 #: The enum the column holds, resolved lazily to keep imports one-way. 

481 enum_name: ClassVar[str] 

482 display_names: ClassVar[dict[str, str]] = {} 

483 

484 def _enum(self) -> Any: 

485 from app.db.postgres import enums 

486 

487 holder, member = self.enum_name.split(".") 

488 return getattr(getattr(enums, holder), member) 

489 

490 def coerce(self, value: str) -> Any: 

491 try: 

492 return self._enum()(str(value)) 

493 except ValueError: 

494 return None 

495 

496 def labels(self, db: Any, keys: list[str]) -> dict[str, str]: 

497 return { 

498 key: self.display_names[key] for key in keys if key in self.display_names 

499 } 

500 

501 

502@register_dimension 

503class RuleDimension(EventColumnDimension): 

504 key = "rule" 

505 label = "Rule" 

506 description = "One bucket per rule that was evaluated." 

507 plural = "rules" 

508 sources = GOVERNANCE_SOURCES 

509 column_name = "rule_id" 

510 

511 def labels(self, db: Any, keys: list[str]) -> dict[str, str]: 

512 """Names come off the events themselves, not the rules table. 

513 

514 The log denormalises ``rule_name`` precisely so a deleted rule is 

515 still readable — "a rule that was deleted after it blocked somebody is 

516 exactly the case the log is kept for". Resolving through ``rules`` 

517 would put a UUID on the chart for that case, which is the one that 

518 matters most. 

519 """ 

520 from app.db.postgres.models import GovernanceEvent 

521 

522 ids = [parsed for parsed in (self.coerce(key) for key in keys) if parsed] 

523 if not ids: 

524 return {} 

525 try: 

526 rows = ( 

527 db.query(GovernanceEvent.rule_id, GovernanceEvent.rule_name) 

528 .filter(GovernanceEvent.rule_id.in_(ids)) 

529 .distinct() 

530 .all() 

531 ) 

532 except Exception: # a missing name is not a failed page 

533 logger.exception("Could not resolve rule names for a stats breakdown") 

534 return {} 

535 return {str(rule_id): name for rule_id, name in rows if name} 

536 

537 

538@register_dimension 

539class LayerDimension(EventEnumDimension): 

540 """The layer of a request the rule acted in. Named ``rule_type`` until 

541 migration 105, which rewrote the tiles that sliced by it.""" 

542 

543 key = "layer" 

544 label = "Layer" 

545 description = "Where in a request the rule acted." 

546 plural = "layers" 

547 column_name = "layer" 

548 enum_name = "RuleEnum.Layer" 

549 

550 def labels(self, db: Any, keys: list[str]) -> dict[str, str]: 

551 from app.services.rules import layers as layer_registry 

552 

553 known = {layer.key.value: layer.label for layer in layer_registry.ordered()} 

554 return {key: known[key] for key in keys if key in known} 

555 

556 

557@register_dimension 

558class GovernanceOutcomeDimension(EventEnumDimension): 

559 key = "governance_outcome" 

560 label = "What the rule did" 

561 description = ( 

562 "Refused the invocation, changed something, matched and found nothing " 

563 "to do, or stood aside." 

564 ) 

565 plural = "outcomes" 

566 column_name = "outcome" 

567 enum_name = "GovernanceEnum.Outcome" 

568 display_names: ClassVar[dict[str, str]] = { 

569 "blocked": "Blocked", 

570 "applied": "Applied", 

571 "no_change": "Matched, nothing to do", 

572 "not_matched": "Stood aside", 

573 } 

574 

575 

576@register_dimension 

577class PhaseDimension(EventEnumDimension): 

578 key = "phase" 

579 label = "Phase" 

580 description = "Evaluated against the prompt, or against the response." 

581 plural = "phases" 

582 column_name = "phase" 

583 enum_name = "GovernanceEnum.Phase" 

584 display_names: ClassVar[dict[str, str]] = { 

585 "input": "Prompt", 

586 "output": "Response", 

587 } 

588 

589 

590@register_dimension 

591class EnforcedInDimension(EventEnumDimension): 

592 key = "enforced_in" 

593 label = "Enforced in" 

594 description = "Which service carried the rule out." 

595 plural = "services" 

596 column_name = "enforced_in" 

597 enum_name = "GovernanceEnum.EnforcedIn" 

598 display_names: ClassVar[dict[str, str]] = {"core": "svc-core", "ai": "svc-ai"} 

599 

600 

601@register_dimension 

602class GovernedAgentDimension(EventColumnDimension): 

603 key = "governed_agent" 

604 label = "Agent" 

605 description = "One bucket per agent whose invocation was governed." 

606 plural = "agents" 

607 column_name = "agent_id" 

608 

609 def labels(self, db: Any, keys: list[str]) -> dict[str, str]: 

610 return AgentDimension().labels(db, keys) 

611 

612 

613@register_dimension 

614class GovernedExecutionTypeDimension(EventColumnDimension): 

615 key = "governed_execution_type" 

616 label = "Execution type" 

617 description = "How the governed invocation was started." 

618 plural = "execution types" 

619 resolves_names = False 

620 column_name = "execution_type" 

621 display_names: ClassVar[dict[str, str]] = { 

622 "agent": "Agent turn", 

623 "model": "Direct prompt", 

624 } 

625 

626 def coerce(self, value: str) -> Any: 

627 return str(value) if value else None 

628 

629 def labels(self, db: Any, keys: list[str]) -> dict[str, str]: 

630 return { 

631 key: self.display_names[key] for key in keys if key in self.display_names 

632 } 

633 

634 

635@register_dimension 

636class RedactionKindDimension(Dimension): 

637 """What kind of value was removed — email, card number, and so on. 

638 

639 Only over the redaction source, because the key it groups on exists only 

640 in that expansion. The kinds are whatever the redactors emit, so nothing 

641 here enumerates them: a redactor added later appears on the chart by 

642 itself. 

643 """ 

644 

645 key = "redaction_kind" 

646 label = "Redaction kind" 

647 description = "The kind of value removed, as the redactor classified it." 

648 plural = "kinds" 

649 sources = ("redactions",) 

650 resolves_names = False 

651 

652 def group_column(self) -> ColumnElement: 

653 from .sources import get_source 

654 

655 return get_source("redactions").pairs().c.key 

656 

657 def coerce(self, value: str) -> Any: 

658 return str(value) if value else None 

659 

660 def labels(self, db: Any, keys: list[str]) -> dict[str, str]: 

661 """Named by the detectors' own registry — "NHS numbers", not 

662 ``nhs_number``. A kind no longer registered keeps its key.""" 

663 from app.services.rules import pii 

664 

665 named = {key: pii.get(key) for key in keys} 

666 return { 

667 key: recogniser.plural[0].upper() + recogniser.plural[1:] 

668 for key, recogniser in named.items() 

669 if recogniser is not None 

670 } 

671 

672 

673# ─── Review dimensions ──────────────────────────────────────────────────────── 

674 

675 

676class FlagColumnDimension(Dimension): 

677 """A dimension bucketing on one column of ``review_flags``.""" 

678 

679 sources = ("reviews",) 

680 column_name: ClassVar[str] 

681 

682 def group_column(self) -> ColumnElement: 

683 from app.db.postgres.models import ReviewFlag 

684 

685 return getattr(ReviewFlag, self.column_name) 

686 

687 

688@register_dimension 

689class FlaggedByRuleDimension(FlagColumnDimension): 

690 key = "flag_rule" 

691 label = "Rule" 

692 description = "One bucket per audit rule that raised flags." 

693 plural = "rules" 

694 column_name = "rule_id" 

695 

696 def labels(self, db: Any, keys: list[str]) -> dict[str, str]: 

697 """Named off the flags, for the same reason the rule axis is: the 

698 queue denormalises ``rule_name`` so a deleted rule stays readable.""" 

699 from app.db.postgres.models import ReviewFlag 

700 

701 ids = [parsed for parsed in (self.coerce(key) for key in keys) if parsed] 

702 if not ids: 

703 return {} 

704 try: 

705 rows = ( 

706 db.query(ReviewFlag.rule_id, ReviewFlag.rule_name) 

707 .filter(ReviewFlag.rule_id.in_(ids)) 

708 .distinct() 

709 .all() 

710 ) 

711 except Exception: # a missing name is not a failed page 

712 logger.exception("Could not resolve rule names for a stats breakdown") 

713 return {} 

714 return {str(rule_id): name for rule_id, name in rows if name} 

715 

716 

717@register_dimension 

718class ReviewStatusDimension(FlagColumnDimension): 

719 key = "review_status" 

720 label = "Review status" 

721 description = "Whether a person has worked the flag through yet." 

722 plural = "statuses" 

723 resolves_names = False 

724 column_name = "status" 

725 display_names: ClassVar[dict[str, str]] = { 

726 "pending": "Awaiting review", 

727 "reviewed": "Reviewed", 

728 "dismissed": "Dismissed", 

729 } 

730 

731 def coerce(self, value: str) -> Any: 

732 from app.db.postgres.enums import ReviewEnum 

733 

734 try: 

735 return ReviewEnum.Status(str(value)) 

736 except ValueError: 

737 return None 

738 

739 def labels(self, db: Any, keys: list[str]) -> dict[str, str]: 

740 return { 

741 key: self.display_names[key] for key in keys if key in self.display_names 

742 } 

743 

744 

745@register_dimension 

746class ReviewerDimension(FlagColumnDimension): 

747 key = "reviewer" 

748 label = "Reviewer" 

749 description = "Who the rule addressed the flag to." 

750 plural = "reviewers" 

751 resolves_names = False 

752 column_name = "reviewer" 

753 

754 def coerce(self, value: str) -> Any: 

755 return str(value) if value else None 

756 

757 

758@register_dimension 

759class FlaggedAgentDimension(FlagColumnDimension): 

760 key = "flagged_agent" 

761 label = "Agent" 

762 description = "One bucket per agent whose invocation was flagged." 

763 plural = "agents" 

764 column_name = "agent_id" 

765 

766 def labels(self, db: Any, keys: list[str]) -> dict[str, str]: 

767 return AgentDimension().labels(db, keys)