Coverage for app / services / stats / metrics.py: 98%

249 statements  

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

1""" 

2Metrics — *what figure* a breakdown reports for each bucket. 

3 

4One class per metric, registered with :func:`register_metric`. A metric owns 

5its SQL aggregate, the unit it is measured in, and a short line saying what 

6the number means. Adding one means adding a class, not a branch in a query 

7builder and a matching branch in the frontend's formatter. 

8 

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

10Conditional aggregates, not filtered queries 

11────────────────────────────────────────────────────────────────────────────── 

12 

13Every metric aggregates the *same* rows — one owner, one window, one axis — 

14and expresses what it counts as a ``CASE`` inside the aggregate rather than as 

15a filter on the query. ``errors`` is ``count`` over failed rows, ``invocations`` 

16``count`` over successful ones, and ``error_rate`` the ratio of the two; all 

17three read one result set. 

18 

19That is what makes a breakdown honest about its denominators. If each metric 

20filtered the query instead, a bucket with only failed invocations would be 

21absent from a ``tokens`` breakdown and present in an ``errors`` one, and the 

22two charts would disagree about which agents exist. 

23 

24────────────────────────────────────────────────────────────────────────────── 

25Null is not zero 

26────────────────────────────────────────────────────────────────────────────── 

27 

28``avg_latency_ms`` over rows that were never timed, and ``estimated_cost_usd`` 

29over a model that publishes no price, are both *unmeasured* rather than zero — 

30the same distinction ``usage.estimate_cost`` draws, and for the same reason: a 

31tile reading "$0.00" for an unpriced model states something false, where "—" 

32states what is true. Metrics say which of the two they are with 

33``zero_is_meaningful``, and the tile renders accordingly. 

34""" 

35 

36from __future__ import annotations 

37 

38from abc import ABC, abstractmethod 

39from decimal import Decimal 

40from typing import Any, ClassVar 

41 

42from sqlalchemy import case, func 

43from sqlalchemy.sql.elements import ColumnElement 

44 

45from app.db.postgres.enums import UsageEnum 

46 

47 

48def _ok() -> ColumnElement: 

49 """Predicate matching a ledger row whose invocation came back.""" 

50 from app.db.postgres.models import GovernanceUsage 

51 

52 return GovernanceUsage.outcome == UsageEnum.Outcome.ok 

53 

54 

55def _failed() -> ColumnElement: 

56 from app.db.postgres.models import GovernanceUsage 

57 

58 return GovernanceUsage.outcome == UsageEnum.Outcome.error 

59 

60 

61def _when_ok(column: ColumnElement) -> ColumnElement: 

62 """``column``'s value on successful rows, NULL on failed ones. 

63 

64 Summing tokens or cost across failed attempts would inflate both: a call 

65 that errored produced no answer, and whatever partial token count came 

66 back with the failure is not work the user received. 

67 """ 

68 return case((_ok(), column), else_=None) 

69 

70 

71class Metric(ABC): 

72 """One figure a breakdown can report.""" 

73 

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

75 key: ClassVar[str] 

76 #: Which audit table this is counted from. The query is built from the 

77 #: metric alone, so a tile can never store a metric and a table that 

78 #: disagree — there is nowhere to state the table separately. 

79 source: ClassVar[str] = "usage" 

80 #: Human label for the metric picker and the tile's caption. 

81 label: ClassVar[str] 

82 #: One line saying what the number counts. 

83 description: ClassVar[str] = "" 

84 #: How to format it: count, tokens, usd, ms or percent. 

85 unit: ClassVar[str] = "count" 

86 #: Whether summing buckets gives a meaningful total. False for averages 

87 #: and rates, where a "total" would be arithmetic nonsense and the 

88 #: breakdown reports the figure over all rows instead. 

89 additive: ClassVar[bool] = True 

90 #: Whether an absent figure should read as zero. False where a null means 

91 #: "never measured" — unpriced models, untimed invocations. 

92 zero_is_meaningful: ClassVar[bool] = True 

93 

94 @abstractmethod 

95 def aggregate(self) -> ColumnElement: 

96 """The SQL aggregate producing this metric over a group of rows.""" 

97 

98 def cast(self, value: Any) -> float | None: 

99 """The aggregate's result as a plain number, or None when unmeasured.""" 

100 if value is None: 

101 return None 

102 if isinstance(value, Decimal): 

103 return float(value) 

104 try: 

105 return float(value) 

106 except (TypeError, ValueError): 

107 return None 

108 

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

110 """Catalogue entry for this metric, for the widget editor.""" 

111 return { 

112 "key": self.key, 

113 "label": self.label, 

114 "description": self.description, 

115 "unit": self.unit, 

116 "additive": self.additive, 

117 "zero_is_meaningful": self.zero_is_meaningful, 

118 "source": self.source, 

119 } 

120 

121 

122# ─── Registry ───────────────────────────────────────────────────────────────── 

123 

124_REGISTRY: dict[str, Metric] = {} 

125_ORDER: list[str] = [] 

126 

127 

128def register_metric(cls: type[Metric]) -> type[Metric]: 

129 """Class decorator adding one metric to the registry.""" 

130 instance = cls() 

131 if instance.key in _REGISTRY: 

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

133 _REGISTRY[instance.key] = instance 

134 _ORDER.append(instance.key) 

135 return cls 

136 

137 

138def get_metric(key: str | None) -> Metric | None: 

139 """The metric registered under ``key``, or None if there is none.""" 

140 if not key: 

141 return None 

142 return _REGISTRY.get(str(key)) 

143 

144 

145def metric_keys() -> frozenset[str]: 

146 """Every registered metric key.""" 

147 return frozenset(_REGISTRY) 

148 

149 

150def metrics_for_source(source: str) -> list[Metric]: 

151 """Every metric counted from ``source``, in picker order.""" 

152 return [_REGISTRY[key] for key in _ORDER if _REGISTRY[key].source == source] 

153 

154 

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

156 """Registered metrics, in picker order.""" 

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

158 

159 

160# ─── Volume ─────────────────────────────────────────────────────────────────── 

161 

162 

163@register_metric 

164class InvocationsMetric(Metric): 

165 key = "invocations" 

166 label = "Invocations" 

167 description = "How many invocations came back." 

168 unit = "count" 

169 

170 def aggregate(self) -> ColumnElement: 

171 from app.db.postgres.models import GovernanceUsage 

172 

173 return func.count(case((_ok(), GovernanceUsage.id), else_=None)) 

174 

175 

176@register_metric 

177class InputTokensMetric(Metric): 

178 key = "input_tokens" 

179 label = "Input tokens" 

180 description = "Tokens sent to the model." 

181 unit = "tokens" 

182 

183 def aggregate(self) -> ColumnElement: 

184 from app.db.postgres.models import GovernanceUsage 

185 

186 return func.sum(_when_ok(GovernanceUsage.input_tokens)) 

187 

188 

189@register_metric 

190class OutputTokensMetric(Metric): 

191 key = "output_tokens" 

192 label = "Output tokens" 

193 description = "Tokens the model produced." 

194 unit = "tokens" 

195 

196 def aggregate(self) -> ColumnElement: 

197 from app.db.postgres.models import GovernanceUsage 

198 

199 return func.sum(_when_ok(GovernanceUsage.output_tokens)) 

200 

201 

202@register_metric 

203class TotalTokensMetric(Metric): 

204 key = "total_tokens" 

205 label = "Total tokens" 

206 description = "Tokens sent and produced together." 

207 unit = "tokens" 

208 

209 def aggregate(self) -> ColumnElement: 

210 from app.db.postgres.models import GovernanceUsage 

211 

212 return func.sum( 

213 _when_ok(GovernanceUsage.input_tokens + GovernanceUsage.output_tokens) 

214 ) 

215 

216 

217# ─── Cost ───────────────────────────────────────────────────────────────────── 

218 

219 

220@register_metric 

221class CostMetric(Metric): 

222 key = "estimated_cost_usd" 

223 label = "Estimated spend" 

224 description = ( 

225 "What the invocations are estimated to have cost, from the invoked " 

226 "model's published price. A lower bound: an unpriced model " 

227 "contributes nothing rather than a guess." 

228 ) 

229 unit = "usd" 

230 zero_is_meaningful = False 

231 

232 def aggregate(self) -> ColumnElement: 

233 from app.db.postgres.models import GovernanceUsage 

234 

235 return func.sum(_when_ok(GovernanceUsage.estimated_cost_usd)) 

236 

237 

238# ─── Latency ────────────────────────────────────────────────────────────────── 

239 

240 

241@register_metric 

242class AverageLatencyMetric(Metric): 

243 key = "avg_latency_ms" 

244 label = "Average latency" 

245 description = "Mean wall-clock duration of the invocations that were timed." 

246 unit = "ms" 

247 additive = False 

248 zero_is_meaningful = False 

249 

250 def aggregate(self) -> ColumnElement: 

251 from app.db.postgres.models import GovernanceUsage 

252 

253 # Untimed rows are already NULL and excluded by ``avg``; the CASE is 

254 # what keeps a failed invocation's duration — usually a timeout — out 

255 # of a figure that is read as "how fast is this model". 

256 return func.avg(_when_ok(GovernanceUsage.latency_ms)) 

257 

258 

259# ─── Errors ─────────────────────────────────────────────────────────────────── 

260 

261 

262@register_metric 

263class ErrorsMetric(Metric): 

264 key = "errors" 

265 label = "Errors" 

266 description = "How many invocations were attempted and failed." 

267 unit = "count" 

268 

269 def aggregate(self) -> ColumnElement: 

270 from app.db.postgres.models import GovernanceUsage 

271 

272 return func.count(case((_failed(), GovernanceUsage.id), else_=None)) 

273 

274 

275@register_metric 

276class ErrorRateMetric(Metric): 

277 key = "error_rate" 

278 label = "Error rate" 

279 description = "Failed invocations as a percentage of those attempted." 

280 unit = "percent" 

281 additive = False 

282 

283 def aggregate(self) -> ColumnElement: 

284 # Computed in SQL rather than by dividing two metrics afterwards, so 

285 # a bucket's rate is over its own attempts. Dividing page totals would 

286 # give every bucket the account's rate. 

287 # 

288 # The summed literals are floats, which is what keeps this off 

289 # Postgres' integer division — 1/3 as integers is 0, and an error rate 

290 # that reported 0% for one failure in three would be worse than no 

291 # error rate at all. 

292 attempts = func.count(1) 

293 failures = func.sum(case((_failed(), 1.0), else_=0.0)) 

294 return 100.0 * failures / func.nullif(attempts, 0) 

295 

296 

297# ─── Governance ─────────────────────────────────────────────────────────────── 

298# 

299# Counted from ``governance_events`` — one row per rule evaluated, whether or 

300# not it matched. The outcomes are the whole point of that table: a rule that 

301# ran and found nothing to do is working, and before the table existed it was 

302# indistinguishable from one that had never been evaluated. So each outcome is 

303# its own metric rather than a filter somebody has to remember to apply. 

304 

305 

306def _outcome(value: str) -> ColumnElement: 

307 from app.db.postgres.enums import GovernanceEnum 

308 from app.db.postgres.models import GovernanceEvent 

309 

310 return GovernanceEvent.outcome == GovernanceEnum.Outcome[value] 

311 

312 

313class GovernanceMetric(Metric): 

314 """A metric counted from the governance activity log.""" 

315 

316 source = "governance" 

317 unit = "count" 

318 

319 def _count_where(self, predicate: ColumnElement) -> ColumnElement: 

320 from app.db.postgres.models import GovernanceEvent 

321 

322 return func.count(case((predicate, GovernanceEvent.id), else_=None)) 

323 

324 

325@register_metric 

326class EvaluationsMetric(GovernanceMetric): 

327 key = "evaluations" 

328 label = "Rule evaluations" 

329 description = "How many times a rule was evaluated against an invocation." 

330 

331 def aggregate(self) -> ColumnElement: 

332 return func.count(1) 

333 

334 

335@register_metric 

336class BlockedMetric(GovernanceMetric): 

337 key = "blocked" 

338 label = "Blocks" 

339 description = "Evaluations where the rule refused the invocation." 

340 

341 def aggregate(self) -> ColumnElement: 

342 return self._count_where(_outcome("blocked")) 

343 

344 

345@register_metric 

346class AppliedMetric(GovernanceMetric): 

347 key = "applied" 

348 label = "Rules applied" 

349 description = "Evaluations where the rule matched and changed something." 

350 

351 def aggregate(self) -> ColumnElement: 

352 return self._count_where(_outcome("applied")) 

353 

354 

355@register_metric 

356class NoChangeMetric(GovernanceMetric): 

357 key = "no_change" 

358 label = "Matched, nothing to do" 

359 description = ( 

360 "Evaluations where the rule matched, its actions ran, and there was " 

361 "nothing to change. A redaction rule over a clean prompt is working." 

362 ) 

363 

364 def aggregate(self) -> ColumnElement: 

365 return self._count_where(_outcome("no_change")) 

366 

367 

368@register_metric 

369class NotMatchedMetric(GovernanceMetric): 

370 key = "not_matched" 

371 label = "Stood aside" 

372 description = "Evaluations where the rule's conditions did not hold." 

373 

374 def aggregate(self) -> ColumnElement: 

375 return self._count_where(_outcome("not_matched")) 

376 

377 

378@register_metric 

379class BlockRateMetric(GovernanceMetric): 

380 key = "block_rate" 

381 label = "Block rate" 

382 description = "Blocks as a percentage of the evaluations in this slice." 

383 unit = "percent" 

384 additive = False 

385 

386 def aggregate(self) -> ColumnElement: 

387 # Float literals for the same reason ``error_rate`` uses them: one 

388 # block in three is 33%, and Postgres divides integers as integers. 

389 evaluations = func.count(1) 

390 blocks = func.sum(case((_outcome("blocked"), 1.0), else_=0.0)) 

391 return 100.0 * blocks / func.nullif(evaluations, 0) 

392 

393 

394# ─── Redactions ─────────────────────────────────────────────────────────────── 

395# 

396# Counted from the expansion, where one row is one *kind* redacted on one 

397# event. Both figures below are real questions with different answers: three 

398# emails removed from one response is three values across one event. 

399 

400 

401def _pairs(): 

402 from .sources import get_source 

403 

404 return get_source("redactions").pairs() 

405 

406 

407class RedactionMetric(Metric): 

408 """A metric counted from the redaction expansion.""" 

409 

410 source = "redactions" 

411 unit = "count" 

412 

413 

414@register_metric 

415class RedactedValuesMetric(RedactionMetric): 

416 key = "redacted_values" 

417 label = "Values redacted" 

418 description = "How many individual values redaction rules removed." 

419 

420 def aggregate(self) -> ColumnElement: 

421 from sqlalchemy import Numeric 

422 from sqlalchemy import cast as sa_cast 

423 

424 # The counts are JSON text, so they are cast rather than summed as 

425 # strings — which Postgres refuses outright rather than doing 

426 # something surprising. 

427 return func.coalesce(func.sum(sa_cast(_pairs().c.value, Numeric)), 0) 

428 

429 

430@register_metric 

431class RedactionEventsMetric(RedactionMetric): 

432 key = "redaction_events" 

433 label = "Prompts and answers redacted" 

434 description = ( 

435 "How many invocations had something removed — however many values " 

436 "were removed from each." 

437 ) 

438 

439 def aggregate(self) -> ColumnElement: 

440 from app.db.postgres.models import GovernanceEvent 

441 

442 # DISTINCT because the expansion repeats an event once per kind: an 

443 # event that redacted an email and a card is two rows and one 

444 # response. 

445 return func.count(func.distinct(GovernanceEvent.id)) 

446 

447 

448# ─── Reviews ────────────────────────────────────────────────────────────────── 

449 

450 

451def _status(value: str) -> ColumnElement: 

452 from app.db.postgres.enums import ReviewEnum 

453 from app.db.postgres.models import ReviewFlag 

454 

455 return ReviewFlag.status == ReviewEnum.Status[value] 

456 

457 

458class ReviewMetric(Metric): 

459 """A metric counted from the audit reviewer queue.""" 

460 

461 source = "reviews" 

462 unit = "count" 

463 

464 def _count_where(self, predicate: ColumnElement) -> ColumnElement: 

465 from app.db.postgres.models import ReviewFlag 

466 

467 return func.count(case((predicate, ReviewFlag.id), else_=None)) 

468 

469 

470@register_metric 

471class FlagsMetric(ReviewMetric): 

472 key = "flags" 

473 label = "Review flags" 

474 description = "How many invocations an audit rule asked a person to look at." 

475 

476 def aggregate(self) -> ColumnElement: 

477 return func.count(1) 

478 

479 

480@register_metric 

481class PendingFlagsMetric(ReviewMetric): 

482 key = "pending_flags" 

483 label = "Awaiting review" 

484 description = "Flags nobody has looked at yet." 

485 

486 def aggregate(self) -> ColumnElement: 

487 return self._count_where(_status("pending")) 

488 

489 

490@register_metric 

491class ReviewedFlagsMetric(ReviewMetric): 

492 key = "reviewed_flags" 

493 label = "Reviewed" 

494 description = "Flags a person looked at and judged acceptable." 

495 

496 def aggregate(self) -> ColumnElement: 

497 return self._count_where(_status("reviewed")) 

498 

499 

500@register_metric 

501class DismissedFlagsMetric(ReviewMetric): 

502 key = "dismissed_flags" 

503 label = "Dismissed" 

504 description = "Flags a person judged unwarranted." 

505 

506 def aggregate(self) -> ColumnElement: 

507 return self._count_where(_status("dismissed"))