Coverage for app / services / statements / sections.py: 62%
285 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""The parts of a statement — one registered class each.
3Every section reads one month of one workspace (``build.Context``) and
4returns plain JSON: what a closed statement stores. Each also says how it
5reads as CSV rows. Adding a figure to every statement is one class here.
7Money is what the ledger measured (``spend_usd``), beside what budgets count
8(``counted_usd``: measured, plus the high estimate for calls no catalogue
9could price). ``spend_usd`` is None only when nothing in it could be priced —
10unknown, never $0.
11"""
13from __future__ import annotations
15import logging
16from abc import ABC, abstractmethod
17from collections import Counter
18from datetime import datetime
19from decimal import Decimal
20from statistics import median
21from typing import Any, ClassVar, Iterator
22from uuid import UUID
24from sqlalchemy import Date, cast, func
26from app.db.postgres.enums import (
27 DecisionEnum,
28 GovernanceEnum,
29 ReviewEnum,
30 RuleEnum,
31 RunnableEnum,
32 UsageEnum,
33)
34from app.db.postgres.models import (
35 DecisionOutcome,
36 Experiment,
37 ExperimentBatch,
38 GovernanceEvent,
39 GovernanceUsage,
40 Project,
41 ReviewFlag,
42 Rule,
43 TestCase,
44 TestSuite,
45)
47from .build import Context, Month
49logger = logging.getLogger(__name__)
51#: Rows a breakdown keeps; the rest are folded into one.
52BREAKDOWN_ROWS = 20
55def _money(value: Any) -> float | None:
56 if value is None:
57 return None
58 return round(float(value), 6)
61def _in(column: Any, month: Month) -> list[Any]:
62 return [column >= month.begin, column < month.end]
65class Section(ABC):
66 """One part of a statement."""
68 key: ClassVar[str]
69 title: ClassVar[str]
71 @abstractmethod
72 def compute(self, ctx: Context) -> Any: ...
74 def csv_rows(self, value: Any) -> Iterator[list[Any]]:
75 """``section, item, label, figure, value`` rows: a flat section's
76 figures, one row each."""
77 if not isinstance(value, dict):
78 return
79 for figure, amount in value.items():
80 if isinstance(amount, dict):
81 for sub, sub_amount in amount.items():
82 yield [self.key, figure, "", sub, sub_amount]
83 elif not isinstance(amount, list):
84 yield [self.key, "", "", figure, amount]
87_REGISTRY: list[Section] = []
90def register_section(cls: type[Section]) -> type[Section]:
91 if any(s.key == cls.key for s in _REGISTRY):
92 raise RuntimeError(f"Statement section '{cls.key}' is already registered.")
93 _REGISTRY.append(cls())
94 return cls
97def all_sections() -> list[Section]:
98 return list(_REGISTRY)
101# ── Spend ────────────────────────────────────────────────────────────────────
104def _ledger_sums() -> tuple[Any, ...]:
105 return (
106 func.sum(GovernanceUsage.estimated_cost_usd),
107 func.sum(func.coalesce(GovernanceUsage.unpriced_estimate_usd, 0)),
108 func.coalesce(func.sum(GovernanceUsage.unpriced_calls), 0),
109 func.count(func.distinct(GovernanceUsage.invocation_id)),
110 func.coalesce(func.sum(GovernanceUsage.llm_calls), 0),
111 func.coalesce(func.sum(GovernanceUsage.input_tokens), 0),
112 func.coalesce(func.sum(GovernanceUsage.output_tokens), 0),
113 )
116def _figures(row: Any) -> dict[str, Any]:
117 """A group's sums as a statement states them."""
118 measured, estimate, unpriced, decisions, calls, tokens_in, tokens_out = row
119 unpriced = int(unpriced or 0)
120 spend = Decimal(str(measured)) if measured is not None else None
121 if spend is None and not unpriced:
122 spend = Decimal(0)
123 counted = (spend or Decimal(0)) + Decimal(str(estimate or 0))
124 return {
125 "spend_usd": _money(spend),
126 "counted_usd": _money(counted),
127 "unpriced_calls": unpriced,
128 "decisions": int(decisions or 0),
129 "calls": int(calls or 0),
130 "input_tokens": int(tokens_in or 0),
131 "output_tokens": int(tokens_out or 0),
132 }
135def _ledger(ctx: Context, month: Month | None = None) -> list[Any]:
136 month = month or ctx.month
137 return [ctx.here.stamped(GovernanceUsage), *_in(GovernanceUsage.occurred_at, month)]
140@register_section
141class SpendSection(Section):
142 key = "spend"
143 title = "Spend"
145 def compute(self, ctx: Context) -> dict[str, Any]:
146 db = ctx.db
147 totals = _figures(db.query(*_ledger_sums()).filter(*_ledger(ctx)).one())
148 failed = (
149 db.query(func.sum(GovernanceUsage.estimated_cost_usd))
150 .filter(*_ledger(ctx), GovernanceUsage.outcome != UsageEnum.Outcome.ok)
151 .scalar()
152 )
153 previous = _figures(
154 db.query(*_ledger_sums()).filter(*_ledger(ctx, ctx.month.previous())).one()
155 )
156 return {
157 **totals,
158 # Turns that failed or were stopped after their first calls: paid
159 # for all the same.
160 "failed_spend_usd": _money(failed) or 0.0,
161 "previous_month": {
162 "key": ctx.month.previous().key,
163 "spend_usd": previous["spend_usd"],
164 "counted_usd": previous["counted_usd"],
165 },
166 }
169@register_section
170class ChargesSection(Section):
171 """What the month comes to under the workspace's plan (``services/plans.py``,
172 A3): the platform fee, and the measured usage past what it includes at
173 cost plus the markup. Only for an organisation or a Personal workspace
174 with a plan — a project pays through its parent. An estimate to invoice
175 by hand, not an invoice; frozen with the statement when its month closes,
176 so a later price change never rewrites a month already billed."""
178 key = "charges"
179 title = "Charges"
180 #: What a person reads beside the figures.
181 NOTE = (
182 "An estimate to invoice by hand, not an invoice: the plan's fee, and "
183 "the month's measured model usage past what it includes, at cost plus "
184 "the markup. Calls no catalogue could price are not charged."
185 )
187 def compute(self, ctx: Context) -> dict[str, Any] | None:
188 from app.services import plans
190 plan = plans.for_workspace(ctx.ws)
191 if plan is None:
192 return None
193 measured, unpriced = (
194 ctx.db.query(
195 func.sum(GovernanceUsage.estimated_cost_usd),
196 func.coalesce(func.sum(GovernanceUsage.unpriced_calls), 0),
197 )
198 .filter(*_ledger(ctx))
199 .one()
200 )
201 charges = plan.charges(
202 Decimal(str(measured)) if measured is not None else Decimal(0),
203 int(unpriced or 0),
204 )
205 return {
206 "title": self.title,
207 "plan": plan.as_json(),
208 **charges.as_json(),
209 "note": self.NOTE,
210 }
212 def csv_rows(self, value: Any) -> Iterator[list[Any]]:
213 if not isinstance(value, dict):
214 return
215 for figure, amount in value.items():
216 if figure in ("title", "note"):
217 continue
218 if isinstance(amount, dict):
219 for sub, sub_amount in amount.items():
220 yield [self.key, figure, "", sub, sub_amount]
221 else:
222 yield [self.key, "", "", figure, amount]
225class _Breakdown(Section):
226 """Spend by one stats dimension (``app/services/stats/dimensions.py``),
227 named as the dimension names its buckets — at the time of writing, so a
228 closed statement keeps a deleted agent's name."""
230 dimension: ClassVar[str]
231 #: What the rows with no value on the axis are called.
232 unassigned_label: ClassVar[str] = "Unassigned"
234 def applies(self, ctx: Context) -> bool:
235 return True
237 def compute(self, ctx: Context) -> dict[str, Any] | None:
238 from app.services.stats import breakdown as stats_breakdown
239 from app.services.stats import dimensions as dimension_registry
241 if not self.applies(ctx):
242 return None
243 axis = dimension_registry.get_dimension(self.dimension)
244 if axis is None:
245 raise RuntimeError(f"No stats dimension '{self.dimension}'")
246 column = axis.group_column()
247 rows = (
248 ctx.db.query(column, *_ledger_sums())
249 .filter(*_ledger(ctx), *axis.row_filters())
250 .group_by(column)
251 .all()
252 )
253 ranked = sorted(
254 ((row[0], _figures(row[1:])) for row in rows),
255 key=lambda pair: -(pair[1]["counted_usd"] or 0),
256 )
257 head, tail = ranked[:BREAKDOWN_ROWS], ranked[BREAKDOWN_ROWS:]
258 names = axis.labels(ctx.db, [str(k) for k, _ in head if k is not None])
259 out = []
260 for key, figures in head:
261 if key is None:
262 out.append(
263 {"key": "unassigned", "label": self.unassigned_label, **figures}
264 )
265 continue
266 text = str(key)
267 out.append(
268 {
269 "key": text,
270 "label": names.get(text)
271 or stats_breakdown._fallback_label(axis, text),
272 **figures,
273 }
274 )
275 if tail:
276 folded = {
277 figure: sum((f[figure] or 0) for _, f in tail) for figure in tail[0][1]
278 }
279 out.append({"key": "other", "label": f"Other ({len(tail)})", **folded})
280 return {"title": self.title, "rows": out}
282 def csv_rows(self, value: Any) -> Iterator[list[Any]]:
283 if not isinstance(value, dict):
284 return
285 for row in value.get("rows") or []:
286 for figure in ("spend_usd", "counted_usd", "unpriced_calls", "decisions"):
287 yield [self.key, row["key"], row["label"], figure, row.get(figure)]
290@register_section
291class BySource(_Breakdown):
292 key = "by_source"
293 title = "By what it was spent on"
294 dimension = "source"
297@register_section
298class ByAgent(_Breakdown):
299 key = "by_agent"
300 title = "By agent"
301 dimension = "agent"
302 unassigned_label = "Not an agent's turn"
305@register_section
306class ByModel(_Breakdown):
307 key = "by_model"
308 title = "By model"
309 dimension = "model"
312@register_section
313class ByKind(_Breakdown):
314 key = "by_kind"
315 title = "By kind of work"
316 dimension = "execution_type"
319@register_section
320class ByProject(_Breakdown):
321 key = "by_project"
322 title = "By project"
323 dimension = "project"
324 unassigned_label = "Not in a project"
326 def applies(self, ctx: Context) -> bool:
327 return bool(ctx.here.projects)
329 def compute(self, ctx: Context) -> dict[str, Any] | None:
330 """As every breakdown, with the cost centre each project's spend is
331 filed under (A4.2) — frozen with the statement, like its name."""
332 table = super().compute(ctx)
333 if not table:
334 return table
335 ids = []
336 for row in table["rows"]:
337 try:
338 ids.append(UUID(row["key"]))
339 except (TypeError, ValueError):
340 continue
341 codes = (
342 dict(
343 ctx.db.query(Project.id, Project.cost_centre)
344 .filter(Project.id.in_(ids))
345 .all()
346 )
347 if ids
348 else {}
349 )
350 for row in table["rows"]:
351 try:
352 row["cost_centre"] = codes.get(UUID(row["key"]))
353 except (TypeError, ValueError):
354 row["cost_centre"] = None
355 return table
357 def csv_rows(self, value: Any) -> Iterator[list[Any]]:
358 yield from super().csv_rows(value)
359 if not isinstance(value, dict):
360 return
361 for row in value.get("rows") or []:
362 if row.get("cost_centre"):
363 yield [
364 self.key,
365 row["key"],
366 row["label"],
367 "cost_centre",
368 row["cost_centre"],
369 ]
372@register_section
373class DailySection(Section):
374 key = "daily"
375 title = "By day"
377 def compute(self, ctx: Context) -> list[dict[str, Any]]:
378 day = cast(GovernanceUsage.occurred_at, Date)
379 rows = (
380 ctx.db.query(day, *_ledger_sums()).filter(*_ledger(ctx)).group_by(day).all()
381 )
382 found = {str(row[0])[:10]: _figures(row[1:]) for row in rows}
383 nothing = _figures((0, 0, 0, 0, 0, 0, 0))
384 # A draft month runs to today; a closed one to its last day.
385 return [
386 {"date": d.isoformat(), **found.get(d.isoformat(), nothing)}
387 for d in ctx.month.days()
388 if d <= ctx.now.date()
389 ]
391 def csv_rows(self, value: Any) -> Iterator[list[Any]]:
392 for row in value or []:
393 yield [self.key, row["date"], "", "spend_usd", row.get("spend_usd")]
396# ── Budgets ──────────────────────────────────────────────────────────────────
399def _cap_counts(ctx: Context, rule_ids: list[Any]) -> dict[Any, Counter]:
400 """For each cost cap rule (or None, the platform allowance): how many
401 turns it refused, stopped part-way or let through past it this month."""
402 counts: dict[Any, Counter] = {}
403 if not rule_ids:
404 return counts
405 rows = (
406 ctx.db.query(
407 GovernanceEvent.rule_id,
408 GovernanceEvent.rule_name,
409 GovernanceEvent.phase,
410 GovernanceEvent.outcome,
411 )
412 .filter(
413 ctx.here.stamped(GovernanceEvent),
414 *_in(GovernanceEvent.created_at, ctx.month),
415 GovernanceEvent.outcome.in_(
416 [GovernanceEnum.Outcome.blocked, GovernanceEnum.Outcome.applied]
417 ),
418 )
419 .all()
420 )
421 from app.services.budgets import allowance as allowance_service
423 wanted = {str(r) for r in rule_ids if r is not None}
424 for rule_id, rule_name, phase, outcome in rows:
425 if rule_id is None:
426 # Only the platform allowance is recorded with no rule behind it.
427 if rule_name != allowance_service.NAME or None not in rule_ids:
428 continue
429 key = None
430 else:
431 key = str(rule_id)
432 if key not in wanted:
433 continue
434 bucket = counts.setdefault(key, Counter())
435 if outcome is GovernanceEnum.Outcome.applied:
436 bucket["let_through"] += 1
437 elif phase is GovernanceEnum.Phase.output:
438 bucket["stopped"] += 1
439 else:
440 bucket["refused"] += 1
441 return counts
444@register_section
445class BudgetsSection(Section):
446 """Each cost cap governing the workspace when the month was written, and
447 the platform allowance: what the month spent against each, and what each
448 did to turns."""
450 key = "budgets"
451 title = "Budgets"
453 def compute(self, ctx: Context) -> list[dict[str, Any]]:
454 from app.services.budgets import allowance as allowance_service
455 from app.services.budgets import status as budget_service
456 from app.services.rules import actions as action_registry
457 from app.services.rules import periods as period_registry
458 from app.services.usage import Span, UsageWindow, UsageWindows
460 rules = budget_service.cost_cap_rules(ctx.db, ctx.ws)
461 found = allowance_service.for_workspace(ctx.ws)
462 counts = _cap_counts(
463 ctx, [r.id for r in rules] + ([None] if found is not None else [])
464 )
465 windows = UsageWindows(ctx.db, str(ctx.ws.id))
466 out: list[dict[str, Any]] = []
467 for rule in rules:
468 for action in rule.actions or []:
469 if not (
470 isinstance(action, dict)
471 and action.get("type") == action_registry.CostCapAction.type
472 ):
473 continue
474 period = period_registry.get_period(action.get("period")) or (
475 period_registry.get_period(period_registry.DEFAULT)
476 )
477 types = tuple(
478 str(t) for t in action.get("execution_types") or [] if str(t)
479 )
480 spent = windows.for_rule(rule).spent(
481 Span(
482 since=ctx.month.begin,
483 until=ctx.month.end,
484 execution_types=types,
485 )
486 )
487 tally = counts.get(str(rule.id), Counter())
488 out.append(
489 {
490 "key": str(rule.id),
491 "label": rule.name,
492 "kind": "rule",
493 "cap_usd": _money(action.get("max_usd")),
494 "period": period.key if period else None,
495 "period_label": period.label if period else None,
496 "spent_usd": _money(spent),
497 "refused": tally["refused"],
498 "stopped": tally["stopped"],
499 "let_through": tally["let_through"],
500 }
501 )
502 if found is not None:
503 window = UsageWindow(ctx.db, str(ctx.ws.id), population=found.population)
504 spent = window.spent(Span(since=ctx.month.begin, until=ctx.month.end))
505 tally = counts.get(None, Counter())
506 out.append(
507 {
508 "key": "platform_allowance",
509 "label": allowance_service.NAME,
510 "kind": "platform",
511 "cap_usd": _money(found.amount),
512 "period": "month",
513 "period_label": "Each calendar month (UTC)",
514 "spent_usd": _money(spent),
515 "refused": tally["refused"],
516 "stopped": tally["stopped"],
517 "let_through": tally["let_through"],
518 }
519 )
520 return out
522 def csv_rows(self, value: Any) -> Iterator[list[Any]]:
523 for row in value or []:
524 for figure in ("cap_usd", "spent_usd", "refused", "stopped", "let_through"):
525 yield [self.key, row["key"], row["label"], figure, row.get(figure)]
528# ── Governance, reviews, evaluations, decisions ─────────────────────────────
531@register_section
532class GovernanceSection(Section):
533 """The rules in force when the month was written, and what every rule
534 evaluated this month came to (``governance_events``)."""
536 key = "governance"
537 title = "Governance"
539 def compute(self, ctx: Context) -> dict[str, Any]:
540 from app.services import workspace as workspace_service
542 in_force = Counter(
543 getattr(layer, "value", layer)
544 for (layer,) in ctx.db.query(Rule.layer)
545 .filter(
546 Rule.is_active.is_(True),
547 Rule.is_system.is_(False),
548 workspace_service.governing_rules(ctx.ws),
549 )
550 .all()
551 )
552 outcomes = dict(
553 ctx.db.query(GovernanceEvent.outcome, func.count(GovernanceEvent.id))
554 .filter(
555 ctx.here.stamped(GovernanceEvent),
556 *_in(GovernanceEvent.created_at, ctx.month),
557 )
558 .group_by(GovernanceEvent.outcome)
559 .all()
560 )
561 return {
562 # By layer since migration 105; a statement closed before it
563 # counts by type (policy / routing / audit) and is frozen so.
564 "rules_in_force": {
565 layer.value: in_force.get(layer.value, 0) for layer in RuleEnum.Layer
566 },
567 "rule_outcomes": {
568 o.value: int(outcomes.get(o, 0)) for o in GovernanceEnum.Outcome
569 },
570 }
573def _hours(start: datetime, end: datetime) -> float:
574 return (end - start).total_seconds() / 3600
577@register_section
578class ReviewsSection(Section):
579 key = "reviews"
580 title = "Reviews"
582 def compute(self, ctx: Context) -> dict[str, Any]:
583 here = ctx.here.filed(ReviewFlag)
584 raised = (
585 ctx.db.query(func.count(ReviewFlag.id))
586 .filter(here, *_in(ReviewFlag.created_at, ctx.month))
587 .scalar()
588 )
589 decided = (
590 ctx.db.query(
591 ReviewFlag.status, ReviewFlag.created_at, ReviewFlag.reviewed_at
592 )
593 .filter(
594 here,
595 ReviewFlag.reviewed_at.isnot(None),
596 *_in(ReviewFlag.reviewed_at, ctx.month),
597 )
598 .all()
599 )
600 open_at_end = (
601 ctx.db.query(func.count(ReviewFlag.id))
602 .filter(
603 here,
604 ReviewFlag.created_at
605 < min(ctx.month.end, ctx.now.replace(tzinfo=None)),
606 (ReviewFlag.reviewed_at.is_(None))
607 | (ReviewFlag.reviewed_at >= ctx.month.end),
608 )
609 .scalar()
610 )
611 by_status = Counter(getattr(s, "value", s) for s, _, _ in decided)
612 waits = [_hours(c, r) for _, c, r in decided if c is not None and r is not None]
613 return {
614 "raised": int(raised or 0),
615 "decided": len(decided),
616 "decided_by_status": {
617 s.value: by_status.get(s.value, 0)
618 for s in ReviewEnum.Status
619 if s is not ReviewEnum.Status.pending
620 },
621 "open_at_end": int(open_at_end or 0),
622 "median_hours_to_decision": round(median(waits), 2) if waits else None,
623 }
626@register_section
627class EvaluationsSection(Section):
628 key = "evaluations"
629 title = "Evaluations"
631 def compute(self, ctx: Context) -> dict[str, Any]:
632 rows = (
633 ctx.db.query(ExperimentBatch.regression_verdict)
634 .join(Experiment, Experiment.id == ExperimentBatch.experiment_id)
635 .filter(
636 ctx.here.owned(Experiment),
637 ExperimentBatch.status == RunnableEnum.Status.completed,
638 *_in(ExperimentBatch.finished_at, ctx.month),
639 )
640 .all()
641 )
642 return {
643 "runs_completed": len(rows),
644 "regressions_caught": sum(1 for (v,) in rows if v == "regressed"),
645 }
648@register_section
649class DecisionsSection(Section):
650 """Governed decisions — answers and skill runs, each with a decision
651 record — the ones a person verified, and the corrections captured."""
653 key = "decisions"
654 title = "Decisions"
656 def compute(self, ctx: Context) -> dict[str, Any]:
657 governed = (
658 ctx.db.query(func.count(func.distinct(GovernanceUsage.invocation_id)))
659 .filter(*_ledger(ctx), GovernanceUsage.invocation_id.isnot(None))
660 .scalar()
661 )
662 verdicts = (
663 ctx.db.query(
664 DecisionOutcome.invocation_id,
665 DecisionOutcome.verdict,
666 )
667 .filter(
668 ctx.here.made(DecisionOutcome),
669 *_in(DecisionOutcome.created_at, ctx.month),
670 )
671 .order_by(DecisionOutcome.created_at.asc())
672 .all()
673 )
674 # The newest verdict on each decision is its verdict.
675 latest = {invocation: verdict for invocation, verdict in verdicts}
676 tally = Counter(latest.values())
677 corrections = (
678 ctx.db.query(func.count(TestCase.id))
679 .join(TestSuite, TestSuite.id == TestCase.test_suite_id)
680 .filter(
681 ctx.here.owned(TestSuite),
682 TestCase.source_invocation_id.isnot(None),
683 *_in(TestCase.created_at, ctx.month),
684 )
685 .scalar()
686 )
687 return {
688 "governed": int(governed or 0),
689 "verified": len(latest),
690 "verdicts": {v.value: tally.get(v.value, 0) for v in DecisionEnum.Verdict},
691 "corrections_captured": int(corrections or 0),
692 }