Coverage for app / services / stats / sources.py: 86%
102 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"""
2Sources — *which record* a metric is counted from.
4svc-core keeps three audit tables, and each answers a different question about
5the same invocation:
7``governance_usage`` what it consumed — tokens, spend, latency, outcome
8``governance_events`` what governance did to it — one row per rule evaluated
9``review_flags`` what a rule asked a person to look at
11A breakdown is the same shape over all three — filter to an owner and a
12window, group by something, aggregate — so rather than three query builders
13each source declares the two columns that differ (who owns the row, and when
14it happened) and the rest of the package is written once.
16Metrics and dimensions each name their source. That is what lets the query be
17built from the *metric* alone: asking for "blocked" is asking about
18``governance_events``, and there is no way to store a tile whose metric and
19table disagree, because nothing ever states the table separately.
20"""
22from __future__ import annotations
24from abc import ABC
25from typing import Any, ClassVar
27from sqlalchemy.sql.elements import ColumnElement
30class Source(ABC):
31 """One audit table a breakdown can be computed over."""
33 #: Stable key, named by every metric and dimension that reads this table.
34 key: ClassVar[str]
35 #: Human label, used to group the metric picker.
36 label: ClassVar[str]
37 #: One line saying what a row of this table is.
38 description: ClassVar[str] = ""
40 def model(self) -> Any:
41 """The SQLAlchemy model. Imported lazily — ``models`` imports
42 ``enums``, and a module-level import here would close the loop."""
43 raise NotImplementedError
45 def owner_column(self) -> ColumnElement:
46 """The column a breakdown is scoped by.
48 Every one of these tables records whose invocation it describes, which
49 is the only scope any of them can answer on its own — the same reason
50 the activity log and the reviewer queue are owner-scoped.
51 """
52 return self.model().owner_user_id
54 def workspace_clause(self, ws: Any, *, projects: bool) -> ColumnElement:
55 """The rows of work done in workspace ``ws`` — and, with
56 ``projects``, in its projects. The ledger and the activity log carry
57 the workspace stamp (``workspace.ledger_stamp``)."""
58 return ws.stamped(self.model(), projects=projects)
60 def time_column(self) -> ColumnElement:
61 """The column a period filters on."""
62 raise NotImplementedError
64 def id_column(self) -> ColumnElement:
65 """The column a row count counts."""
66 return self.model().id
68 def select_from(self) -> Any:
69 """The FROM clause a breakdown over this source reads.
71 Usually just the model. A source whose *row* is finer-grained than a
72 table row says so here — see :class:`RedactionSource` — which is what
73 keeps the expansion out of the metrics and dimensions that read it.
74 """
75 return self.model()
77 def spec(self) -> dict[str, Any]:
78 return {
79 "key": self.key,
80 "label": self.label,
81 "description": self.description,
82 }
85_REGISTRY: dict[str, Source] = {}
86_ORDER: list[str] = []
89def register_source(cls: type[Source]) -> type[Source]:
90 """Class decorator adding one source to the registry."""
91 instance = cls()
92 if instance.key in _REGISTRY:
93 raise RuntimeError(f"Stat source '{instance.key}' is already registered.")
94 _REGISTRY[instance.key] = instance
95 _ORDER.append(instance.key)
96 return cls
99def get_source(key: str | None) -> Source | None:
100 """The source registered under ``key``, or None if there is none."""
101 if not key:
102 return None
103 return _REGISTRY.get(str(key))
106def source_keys() -> frozenset[str]:
107 """Every registered source key."""
108 return frozenset(_REGISTRY)
111def catalogue() -> list[dict[str, Any]]:
112 """Registered sources, in picker order."""
113 return [_REGISTRY[key].spec() for key in _ORDER]
116@register_source
117class UsageSource(Source):
118 key = "usage"
119 label = "Usage"
120 description = "One row per invocation that reached a model."
122 def model(self) -> Any:
123 from app.db.postgres.models import GovernanceUsage
125 return GovernanceUsage
127 def time_column(self) -> ColumnElement:
128 return self.model().occurred_at
131@register_source
132class GovernanceSource(Source):
133 key = "governance"
134 label = "Governance"
135 description = (
136 "One row per rule evaluated against an invocation — including the "
137 "rules that matched and found nothing to do."
138 )
140 def model(self) -> Any:
141 from app.db.postgres.models import GovernanceEvent
143 return GovernanceEvent
145 def time_column(self) -> ColumnElement:
146 return self.model().created_at
149#: The action keys a redaction is recorded under in an event's ``detail``:
150#: both layers' ``redact_pii``, and Input's ``filter_pii`` from before
151#: migration 105. A rule carries one redaction, so an event holds one of them.
152REDACTION_ACTIONS: tuple[str, ...] = ("redact_pii", "filter_pii")
155@register_source
156class RedactionSource(Source):
157 """One row per *value* a redaction rule removed.
159 Finer-grained than a governance event: an event that redacted two emails
160 and a card number is three rows here, one per kind, carrying that kind's
161 count. ``detail`` is keyed by the action that ran
162 (``governance_activity.detail_of``):
163 ``{"redact_pii": {"redacted": {"email": 2, "card": 1}}}`` — kinds and
164 counts, never the values themselves, because the log of a redaction must
165 not be a copy of what was redacted.
167 Until October 2026 this read ``detail -> 'redacted'``, a level no event
168 has, so every redaction breakdown counted nothing. An Input rule's
169 redaction was keyed ``filter_pii`` before migration 105, and events keep
170 the key they were written with, so both are read.
172 A source rather than a dimension on the governance one. The expansion
173 changes what a row *is*, so bolting it onto an axis would silently change
174 what every other metric counted — "blocks by redaction kind" would report
175 each block once per kind it never had. Making it a source means the
176 metrics that make sense over the expansion are the only ones offered.
177 """
179 key = "redactions"
180 label = "Redactions"
181 description = "One row per kind of value a redaction rule removed."
183 #: Built once and reused. The FROM clause and every metric reading
184 #: ``value`` off it must be the *same* object, or SQLAlchemy emits two
185 #: laterals and the aggregate refers to one the query never joined.
186 _pairs: Any = None
188 def model(self) -> Any:
189 from app.db.postgres.models import GovernanceEvent
191 return GovernanceEvent
193 def time_column(self) -> ColumnElement:
194 return self.model().created_at
196 def pairs(self) -> Any:
197 """The lateral expansion of an event's redaction map.
199 ``coalesce(..., '{}')`` matters: most events carry no ``redacted``
200 key at all — a rule that blocked, or matched and found nothing — and
201 ``json_each_text(NULL)`` would drop those rows on an inner join while
202 also making the expression undefined. An empty object expands to
203 nothing, which is the honest answer for an event that redacted
204 nothing.
205 """
206 from sqlalchemy import Text, cast, func
207 from sqlalchemy.dialects.postgresql import JSON
209 from app.db.postgres.models import GovernanceEvent
211 if self._pairs is None:
212 source = func.coalesce(
213 *(
214 cast(GovernanceEvent.detail[action]["redacted"], Text)
215 for action in REDACTION_ACTIONS
216 ),
217 "{}",
218 )
219 type(self)._pairs = (
220 func.json_each_text(cast(source, JSON))
221 .table_valued("key", "value")
222 .lateral()
223 )
224 return self._pairs
226 def select_from(self) -> Any:
227 from sqlalchemy import true
229 from app.db.postgres.models import GovernanceEvent
231 return GovernanceEvent.__table__.join(self.pairs(), true())
234@register_source
235class ReviewSource(Source):
236 key = "reviews"
237 label = "Reviews"
238 description = "One row per invocation an audit rule asked a person to look at."
240 def model(self) -> Any:
241 from app.db.postgres.models import ReviewFlag
243 return ReviewFlag
245 def workspace_clause(self, ws: Any, *, projects: bool) -> ColumnElement:
246 # A flag is filed under the workspace whose queue holds it, by its
247 # owner columns rather than a ledger stamp.
248 from sqlalchemy import and_
250 from app.services.workspace import WorkspaceKind
252 F = self.model()
253 if ws.kind is WorkspaceKind.project:
254 return F.owner_project_id == ws.id
255 if ws.kind is WorkspaceKind.organisation:
256 return F.owner_organisation_id == ws.id
257 return and_(
258 F.owner_user_id == ws.id,
259 F.owner_organisation_id.is_(None),
260 F.owner_project_id.is_(None),
261 )
263 def time_column(self) -> ColumnElement:
264 return self.model().created_at