Coverage for app / services / stats / breakdown.py: 95%

149 statements  

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

1""" 

2Breakdowns — one metric, over one window, sliced by one dimension. 

3 

4This is the query behind "spend by agent this month". Everything it needs is 

5already on the governance usage ledger: svc-core stamps the resource that ran, 

6the project and organisation it belongs to, tokens, cost, latency and whether 

7the call came back, on every governed invocation. The figures were there; what 

8was missing was a way to ask for them by anything other than the whole 

9account. 

10 

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

12Why not svc-ai 

13────────────────────────────────────────────────────────────────────────────── 

14 

15svc-ai owns the authoritative per-invocation record and already serves usage 

16and trace statistics — but ``llm_invocations`` carries a model and a user and 

17nothing else. There is no agent on it, no skill, no project, no organisation, 

18because those are svc-core's resources and svc-ai has never needed to know 

19them. A breakdown by agent cannot be built from that table without teaching 

20svc-ai the whole ownership hierarchy, which is the wrong service to put it in. 

21The ledger already knows, so the breakdown is computed here and svc-ai's 

22account-wide stats stay exactly what they are. 

23 

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

25Shape of the answer 

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

27 

28Buckets are ranked by value and truncated to ``limit``, with the remainder 

29folded into one ``other`` bucket rather than dropped. A chart that silently 

30omitted the tail would make its bars look like the whole of the spend, and the 

31first question anyone asks of a cost breakdown is whether it adds up. 

32 

33``total`` is computed over the whole filtered set, never by summing the page — 

34for the same reason, and because an average or a rate cannot be summed at all. 

35Metrics say which they are (``additive``), and a non-additive metric reports 

36its figure over all rows while its buckets keep their own. 

37""" 

38 

39from __future__ import annotations 

40 

41import logging 

42from dataclasses import dataclass, field 

43from datetime import datetime 

44from typing import Any 

45from uuid import UUID 

46 

47from sqlalchemy import desc 

48from sqlalchemy.exc import SQLAlchemyError 

49from sqlalchemy.orm import Session 

50 

51from . import dimensions as dimension_registry 

52from . import metrics as metric_registry 

53from . import periods as period_registry 

54from . import sources as source_registry 

55 

56logger = logging.getLogger(__name__) 

57 

58#: Ceiling on how many buckets one request may name. Above this a chart is 

59#: unreadable and the answer is a different question, not a longer axis. 

60MAX_BUCKETS = 50 

61 

62#: Key of the bucket holding everything past ``limit``. 

63OTHER_KEY = "__other__" 

64 

65#: Key of the bucket holding rows whose dimension value is absent — an 

66#: invocation with no project, an execution type nothing stamped. Distinct 

67#: from "other", which is a real tail that was truncated. 

68UNASSIGNED_KEY = "__unassigned__" 

69 

70 

71class BreakdownError(ValueError): 

72 """Raised when a breakdown was asked for in terms that do not resolve.""" 

73 

74 

75@dataclass 

76class Bucket: 

77 """One slice of the axis.""" 

78 

79 key: str 

80 label: str 

81 value: float | None 

82 #: Fraction of the additive total this bucket accounts for, 0–1. None for 

83 #: a metric that cannot be summed, where a share would be meaningless. 

84 share: float | None = None 

85 #: True when the named resource no longer exists. The figure stands — 

86 #: deleting an agent does not unspend its budget — but a reader should be 

87 #: told why it has an id for a name. 

88 missing: bool = False 

89 

90 def as_dict(self) -> dict[str, Any]: 

91 return { 

92 "key": self.key, 

93 "label": self.label, 

94 "value": self.value, 

95 "share": self.share, 

96 "missing": self.missing, 

97 } 

98 

99 

100@dataclass 

101class Breakdown: 

102 """The answer to one breakdown request.""" 

103 

104 metric: str 

105 source: str 

106 dimension: str | None 

107 period: str 

108 since: datetime | None 

109 until: datetime 

110 unit: str 

111 additive: bool 

112 zero_is_meaningful: bool 

113 total: float | None 

114 buckets: list[Bucket] = field(default_factory=list) 

115 #: How many buckets the axis actually has, before truncation. 

116 bucket_count: int = 0 

117 

118 def as_dict(self) -> dict[str, Any]: 

119 return { 

120 "metric": self.metric, 

121 "source": self.source, 

122 "dimension": self.dimension, 

123 "period": self.period, 

124 "since": self.since, 

125 "until": self.until, 

126 "unit": self.unit, 

127 "additive": self.additive, 

128 "zero_is_meaningful": self.zero_is_meaningful, 

129 "total": self.total, 

130 "bucket_count": self.bucket_count, 

131 "buckets": [bucket.as_dict() for bucket in self.buckets], 

132 } 

133 

134 

135# ─── Filters ────────────────────────────────────────────────────────────────── 

136 

137 

138def parse_filters(raw: list[str] | None) -> list[tuple[str, str]]: 

139 """``["agent:<uuid>", …]`` as pairs, refusing anything malformed. 

140 

141 Refusing rather than ignoring is the point. A filter that silently fell 

142 off would widen the tile from "this project" to "the whole account" while 

143 the tile's own caption still said "this project" — a dashboard stating 

144 something false, which is the failure the provenance marker on every 

145 widget exists to prevent. 

146 """ 

147 parsed: list[tuple[str, str]] = [] 

148 for entry in raw or []: 

149 key, separator, value = str(entry).partition(":") 

150 if not separator or not key.strip() or not value.strip(): 

151 raise BreakdownError( 

152 f"Filter '{entry}' must be written as '<dimension>:<value>'." 

153 ) 

154 parsed.append((key.strip(), value.strip())) 

155 return parsed 

156 

157 

158def _filter_clauses(filters: list[tuple[str, str]], source: Any = None) -> list[Any]: 

159 clauses: list[Any] = [] 

160 for key, value in filters: 

161 dimension = dimension_registry.get_dimension(key) 

162 if dimension is None: 

163 raise BreakdownError(f"'{key}' is not a dimension this platform records.") 

164 if source is not None and source.key not in dimension.sources: 

165 raise BreakdownError( 

166 f"'{key}' cannot narrow a {source.label.lower()} figure — " 

167 "it is not recorded on those rows." 

168 ) 

169 try: 

170 clauses.extend(dimension.value_filters(value)) 

171 except ValueError as exc: 

172 raise BreakdownError(str(exc)) from exc 

173 return clauses 

174 

175 

176# ─── Computation ────────────────────────────────────────────────────────────── 

177 

178 

179def compute( 

180 db: Session, 

181 owner_user_id: str | UUID, 

182 *, 

183 metric: str, 

184 dimension: str | None = None, 

185 period: str | None = None, 

186 filters: list[tuple[str, str]] | None = None, 

187 limit: int = 10, 

188 now: datetime | None = None, 

189 workspace: Any = None, 

190 include_projects: bool = False, 

191) -> Breakdown: 

192 """One metric over one window, optionally sliced and optionally filtered. 

193 

194 Counted over the caller's own rows, or — given a ``workspace`` — over 

195 the work done in that workspace by anyone (and, with 

196 ``include_projects``, in its projects), which is what a workspace's 

197 dashboard shows. 

198 

199 With no ``dimension`` this is a single figure — what a stat tile shows. 

200 With one it is a ranked axis. The two are the same query; the difference 

201 is a ``GROUP BY``, which is why a tile and the chart beside it can never 

202 disagree about what "this month" means. 

203 """ 

204 chosen_metric = metric_registry.get_metric(metric) 

205 if chosen_metric is None: 

206 raise BreakdownError(f"'{metric}' is not a metric this platform records.") 

207 # The table comes from the metric, never from the request. Asking for 

208 # "blocks" is asking about the governance log, so a tile cannot store a 

209 # metric and a source that disagree — there is nowhere to state the source 

210 # separately. 

211 source = source_registry.get_source(chosen_metric.source) 

212 if source is None: 

213 raise BreakdownError( 

214 f"'{metric}' is counted from a source this platform does not have." 

215 ) 

216 

217 axis = None 

218 if dimension: 

219 axis = dimension_registry.get_dimension(dimension) 

220 if axis is None: 

221 raise BreakdownError( 

222 f"'{dimension}' is not a dimension this platform records." 

223 ) 

224 if source.key not in axis.sources: 

225 # Refused rather than ignored: silently dropping the axis would 

226 # turn "blocks by redaction kind" into an unlabelled total, which 

227 # still reads as an answer to the question that was asked. 

228 raise BreakdownError( 

229 f"'{dimension}' cannot slice '{metric}' — {axis.label} is not " 

230 f"recorded on {source.label.lower()} rows." 

231 ) 

232 

233 window = period_registry.get_period(period) 

234 now = now or _now() 

235 since = window.since(now) 

236 # A period already over (last month) ends at its boundary. 

237 until = window.until(now) or now 

238 clauses = _filter_clauses(filters or [], source) 

239 if axis is not None: 

240 clauses.extend(axis.row_filters()) 

241 

242 base = [ 

243 source.workspace_clause(workspace, projects=include_projects) 

244 if workspace is not None 

245 else source.owner_column() == _uuid(owner_user_id) 

246 ] 

247 if since is not None: 

248 base.append(source.time_column() >= since) 

249 if window.until(now) is not None: 

250 base.append(source.time_column() < until) 

251 base.extend(clauses) 

252 

253 aggregate = chosen_metric.aggregate() 

254 result = Breakdown( 

255 metric=chosen_metric.key, 

256 source=source.key, 

257 dimension=axis.key if axis else None, 

258 period=window.key, 

259 since=since, 

260 until=until, 

261 unit=chosen_metric.unit, 

262 additive=chosen_metric.additive, 

263 zero_is_meaningful=chosen_metric.zero_is_meaningful, 

264 total=None, 

265 ) 

266 

267 try: 

268 result.total = chosen_metric.cast( 

269 db.query(aggregate).select_from(source.select_from()).filter(*base).scalar() 

270 ) 

271 if axis is None: 

272 return result 

273 

274 column = axis.group_column() 

275 rows = ( 

276 db.query(column, aggregate) 

277 .select_from(source.select_from()) 

278 .filter(*base) 

279 .group_by(column) 

280 .order_by(desc(aggregate)) 

281 .all() 

282 ) 

283 except SQLAlchemyError: 

284 logger.exception( 

285 "Stats breakdown failed for metric %s by %s", metric, dimension 

286 ) 

287 raise 

288 

289 result.bucket_count = len(rows) 

290 result.buckets = _shape( 

291 db, axis, chosen_metric, rows, limit=_clamp(limit), total=result.total 

292 ) 

293 return result 

294 

295 

296def _shape( 

297 db: Session, 

298 axis: Any, 

299 metric: Any, 

300 rows: list[Any], 

301 *, 

302 limit: int, 

303 total: float | None, 

304) -> list[Bucket]: 

305 """Rank, truncate, name and apportion the grouped rows.""" 

306 values = [(row[0], metric.cast(row[1])) for row in rows] 

307 # A bucket that aggregated to nothing measurable is dropped rather than 

308 # charted as zero: "this agent spent nothing" and "this agent's models 

309 # publish no price" are different statements, and a bar cannot tell them 

310 # apart. 

311 values = [(key, value) for key, value in values if value is not None] 

312 

313 head, tail = values[:limit], values[limit:] 

314 keys = [str(key) for key, _ in head if key is not None] 

315 # Asked of every axis, not only the id-shaped ones: a categorical 

316 # dimension answers from a static map and never touches the database, but 

317 # "Failed" still reads better on a chart than "error". 

318 names = axis.labels(db, keys) 

319 

320 buckets: list[Bucket] = [] 

321 for key, value in head: 

322 if key is None: 

323 buckets.append( 

324 Bucket( 

325 key=UNASSIGNED_KEY, 

326 label="Unassigned", 

327 value=value, 

328 share=_share(value, total, metric), 

329 ) 

330 ) 

331 continue 

332 text = str(key) 

333 resolved = names.get(text) 

334 buckets.append( 

335 Bucket( 

336 key=text, 

337 label=resolved or _fallback_label(axis, text), 

338 value=value, 

339 share=_share(value, total, metric), 

340 missing=axis.resolves_names and resolved is None, 

341 ) 

342 ) 

343 

344 if tail and metric.additive: 

345 # Only for an additive metric: an "other" bucket averaging the tail's 

346 # latencies would be a number no invocation ever took. 

347 remainder = sum(value for _, value in tail) 

348 buckets.append( 

349 Bucket( 

350 key=OTHER_KEY, 

351 label=f"Other ({len(tail)})", 

352 value=remainder, 

353 share=_share(remainder, total, metric), 

354 ) 

355 ) 

356 return buckets 

357 

358 

359def _share(value: float | None, total: float | None, metric: Any) -> float | None: 

360 if not metric.additive or value is None or not total: 

361 return None 

362 return round(value / total, 6) 

363 

364 

365def _fallback_label(axis: Any, key: str) -> str: 

366 """What a bucket is called when its resource no longer resolves. 

367 

368 A shortened id rather than "Deleted": the ledger row is evidence, and the 

369 id is the only handle a reader has for chasing it through the history 

370 trail, which outlives the resource by design. 

371 """ 

372 if not axis.resolves_names: 

373 return key 

374 return f"{axis.label} {key[:8]}" 

375 

376 

377def _clamp(limit: int) -> int: 

378 try: 

379 parsed = int(limit) 

380 except (TypeError, ValueError): 

381 return 10 

382 return max(1, min(parsed, MAX_BUCKETS)) 

383 

384 

385def _uuid(value: str | UUID) -> UUID | None: 

386 if isinstance(value, UUID): 

387 return value 

388 try: 

389 return UUID(str(value)) 

390 except (ValueError, AttributeError, TypeError): 

391 return None 

392 

393 

394def _now() -> datetime: 

395 from app.util.time import aware_utcnow 

396 

397 return aware_utcnow() 

398 

399 

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

401 """Everything a client needs to build a breakdown request. 

402 

403 Served whole rather than as three endpoints because the widget editor 

404 needs all three to draw one form, and because a client that only ever 

405 reads the catalogue cannot go stale against the registries — which is the 

406 same reason the rule builder is served its vocabulary this way. 

407 """ 

408 return { 

409 "sources": source_registry.catalogue(), 

410 "metrics": metric_registry.catalogue(), 

411 "dimensions": dimension_registry.catalogue(), 

412 "periods": period_registry.catalogue(), 

413 "max_buckets": MAX_BUCKETS, 

414 }