Coverage for app / services / budgets / alerts.py: 81%
183 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"""
2Budget alerts — a budget tells those who govern its workspace before it
3stops them (cost-control plan A2).
5A cost cap names when to alert (``alert_at``, ``QuotaAlert``: half used, 80%,
6used up, heading over before it resets; the last three when it names none).
7The ``budget_alerts`` scheduler job reads every active cap as its budget page
8would — the cap's own reading over the ledger (``CostCapAction.reading``) and
9its forecast (``budgets/forecast.py``) — and writes an inbox notification
10(``app/services/notifications.py``) when one is crossed:
12* **To whom.** Those who govern the rule's workspace (``notifications.
13 governors``): its owner for a Personal rule; an organisation's or a
14 project's admins and governance editors. A cap given to each member
15 (``share: per_member``) tells each member about their own share instead.
16* **Once.** Each crossing is one notification per recipient per period: its
17 ``dedupe_key`` names the rule, the action, the period's start (a calendar
18 period) or the UTC day (a trailing window), and the highest level crossed —
19 so spend that jumps from 50% to 100% between two looks sends "used up",
20 not 80% after it. Within a calendar period spend only grows, so a level
21 once sent is not sent again.
22* **The platform allowance** alerts the same way at 80% and used up, to
23 those who govern the workspace it belongs to.
25The job looks every ten minutes, so an alert follows the spend within that;
26a cap that refuses a turn says so to the person at the time.
27"""
29from __future__ import annotations
31import logging
32from dataclasses import dataclass, field
33from datetime import datetime
34from decimal import Decimal
35from typing import Any
36from uuid import UUID
38from sqlalchemy.orm import Session
40from app.db.postgres.enums import RuleEnum
41from app.db.postgres.models import GovernanceUsage, Organisation, Project, Rule
42from app.services import notifications as notification_service
43from app.services import workspace as workspace_service
44from app.services.budgets import allowance as allowance_service
45from app.services.budgets import status as budget_status
46from app.services.rules import actions as action_registry
47from app.services.rules import periods as period_registry
48from app.services.usage import Span, UsageWindow, UsageWindows
49from app.services.workspace import Workspace, WorkspaceKind
50from app.util.time import aware_utcnow, utc_isoformat
52logger = logging.getLogger(__name__)
54#: Where an alert opens: the Spend tab, in the workspace it is about.
55SPEND_LINK = "/user/governance?section=spend"
57#: The levels the platform allowance alerts at.
58ALLOWANCE_LEVELS = (80, 100)
60_PERIOD_PHRASES = {"day": "today", "week": "this week", "month": "this month"}
63@dataclass
64class RunResult:
65 sent: int = 0
66 budgets: int = 0
67 errors: list[str] = field(default_factory=list)
70def alerts_of(action: dict[str, Any]) -> tuple[tuple[int, ...], bool]:
71 """A cost cap's alert levels (percent, ascending) and whether it alerts
72 when heading over. A rule that names none gets the default; an empty
73 list is no alerts."""
74 raw = action.get("alert_at")
75 if raw is None:
76 raw = list(action_registry.DEFAULT_ALERTS)
77 values = (
78 [str(v).strip() for v in raw]
79 if isinstance(raw, (list, tuple))
80 else [v.strip() for v in str(raw).split(",")]
81 )
82 known = {a.value for a in action_registry.QuotaAlert}
83 chosen = [v for v in values if v in known]
84 levels = tuple(
85 sorted(int(v) for v in chosen if v != action_registry.QuotaAlert.projected)
86 )
87 return levels, action_registry.QuotaAlert.projected.value in chosen
90def level_crossed(
91 spent: Decimal | None, cap: Decimal, levels: tuple[int, ...]
92) -> int | None:
93 """The highest of ``levels`` that ``spent`` has reached, or None."""
94 if spent is None or cap <= 0:
95 return None
96 reached = [lvl for lvl in levels if spent * 100 >= cap * lvl]
97 return max(reached) if reached else None
100def _usd(value: Any) -> str:
101 return action_registry.usd_text(Decimal(str(value or 0)))
104def _period_phrase(figures: dict[str, Any]) -> str:
105 period = str(figures.get("period") or "")
106 if period in _PERIOD_PHRASES:
107 return _PERIOD_PHRASES[period]
108 seconds = figures.get("window_seconds")
109 if seconds:
110 hours = int(seconds) / 3600
111 return (
112 f"in the last {hours:g} hour{'s' if hours != 1 else ''}"
113 if hours < 48
114 else f"in the last {hours / 24:g} days"
115 )
116 return "in its window"
119def where(db: Session, ws: Workspace | None) -> str:
120 """How an alert names the workspace it is about."""
121 if ws is None:
122 return "this workspace"
123 if ws.kind is WorkspaceKind.personal:
124 return "your Personal workspace"
125 if ws.name:
126 return ws.name
127 row = db.get(
128 Organisation if ws.kind is WorkspaceKind.organisation else Project, ws.id
129 )
130 return getattr(row, "name", None) or ws.kind.value
133def _period_key(figures: dict[str, Any], span: Any, now: datetime) -> str:
134 """What one period of a cap is called in a dedupe key: a calendar
135 period's start, or the UTC day for a trailing window."""
136 since = getattr(span, "since", None)
137 if figures.get("resets_at") and since is not None:
138 return since.date().isoformat()
139 return now.date().isoformat()
142def _reached_sentence(
143 reading: action_registry.CapReading, figures: dict[str, Any]
144) -> str:
145 if reading.warns:
146 return "It is set to warn, so work goes on and each call is recorded."
147 resets = action_registry.resets_phrase(figures)
148 return f"Work it covers is refused until it starts again. {resets}"
151def _threshold_message(
152 *,
153 rule: Rule,
154 index: int,
155 level: int,
156 reading: action_registry.CapReading,
157 spent: Decimal,
158 ws: Workspace,
159 place: str,
160 period_key: str,
161 member: UUID | None = None,
162) -> notification_service.Message:
163 figures = reading.figures
164 whose = "Your share of " if member is not None else ""
165 used_up = level >= 100
166 title = (
167 f"{whose}{rule.name} is used up"
168 if used_up
169 else f"{whose}{rule.name} is {level}% used"
170 )
171 body = (
172 f"{_usd(spent)} of {_usd(reading.cap)} {_period_phrase(figures)} "
173 f"in {place}. "
174 + (
175 _reached_sentence(reading, figures)
176 if used_up
177 else action_registry.resets_phrase(figures)
178 )
179 )
180 key = f"budget:{rule.id}:{index}:{period_key}:{level}"
181 if member is not None:
182 key += f":{member}"
183 return notification_service.Message(
184 kind=notification_service.BudgetThreshold.key,
185 title=title,
186 body=body,
187 link=SPEND_LINK,
188 workspace=ws,
189 workspace_name=place,
190 dedupe_key=key,
191 data={
192 "rule_id": str(rule.id),
193 "action_index": index,
194 "level": level,
195 "spent_usd": float(spent),
196 "cap_usd": float(reading.cap),
197 "period": figures.get("period"),
198 "resets_at": figures.get("resets_at"),
199 **({"member": True} if member is not None else {}),
200 },
201 )
204def _projected_message(
205 *,
206 rule: Rule,
207 index: int,
208 reading: action_registry.CapReading,
209 found: Any,
210 ws: Workspace,
211 place: str,
212 period_key: str,
213) -> notification_service.Message:
214 when = found.reaches_cap_at
215 on = f" on {when.day} {when:%B}" if when is not None else ""
216 return notification_service.Message(
217 kind=notification_service.BudgetProjected.key,
218 title=f"{rule.name} is heading over",
219 body=(
220 f"At the last {found.days_used} days' rate it reaches "
221 f"{_usd(reading.cap)}{on}, before it starts again. "
222 f"{_usd(reading.spent)} spent so far in {place}."
223 ),
224 link=SPEND_LINK,
225 workspace=ws,
226 workspace_name=place,
227 dedupe_key=f"budget:{rule.id}:{index}:{period_key}:projected",
228 data={
229 "rule_id": str(rule.id),
230 "action_index": index,
231 "projected_usd": float(found.projected_usd),
232 "cap_usd": float(reading.cap),
233 "reaches_cap_at": utc_isoformat(when) if when is not None else None,
234 },
235 )
238def _cost_cap_rules(db: Session) -> list[Rule]:
239 rules = (
240 db.query(Rule)
241 .filter(
242 Rule.layer == RuleEnum.Layer.access,
243 Rule.is_active.is_(True),
244 Rule.is_system.is_(False),
245 )
246 .all()
247 )
248 return [
249 rule
250 for rule in rules
251 if any(
252 isinstance(a, dict) and a.get("type") == action_registry.CostCapAction.type
253 for a in rule.actions or []
254 )
255 ]
258def _alert_cap(
259 db: Session,
260 rule: Rule,
261 index: int,
262 action: dict[str, Any],
263 window: UsageWindow,
264 *,
265 ws: Workspace,
266 place: str,
267 recipients: list[UUID],
268 now: datetime,
269) -> int:
270 levels, projected = alerts_of(action)
271 if not levels and not projected:
272 return 0
273 cap = action_registry.CostCapAction()
274 reading = cap.reading(action, window, now)
275 if reading is None:
276 return 0
277 period_key = _period_key(reading.figures, reading.span, now)
278 sent = 0
280 if str(action.get("share") or "") == action_registry.QuotaShare.per_member:
281 # Each member's own allowance: each is told about their own share.
282 split = window.spent_by_member(
283 Span(
284 since=reading.span.since,
285 seconds=reading.span.seconds,
286 execution_types=reading.span.execution_types,
287 )
288 )
289 for member, spent in (split or {}).items():
290 level = level_crossed(spent, reading.cap, levels)
291 if member is None or level is None:
292 continue
293 sent += notification_service.notify(
294 db,
295 [member],
296 _threshold_message(
297 rule=rule,
298 index=index,
299 level=level,
300 reading=reading,
301 spent=spent,
302 ws=ws,
303 place=place,
304 period_key=period_key,
305 member=member,
306 ),
307 )
308 return sent
310 if reading.spent is None:
311 return 0
312 level = level_crossed(reading.spent, reading.cap, levels)
313 if level is not None:
314 sent += notification_service.notify(
315 db,
316 recipients,
317 _threshold_message(
318 rule=rule,
319 index=index,
320 level=level,
321 reading=reading,
322 spent=reading.spent,
323 ws=ws,
324 place=place,
325 period_key=period_key,
326 ),
327 )
328 period = period_registry.get_period(reading.figures.get("period"))
329 if projected and not reading.reached and period is not None and period.calendar:
330 found = budget_status._forecast(
331 window,
332 reading.span,
333 spent=reading.spent,
334 now=now,
335 resets_at=period.resets_at(now),
336 cap=reading.cap,
337 )
338 if (
339 found.available
340 and found.projected_usd is not None
341 and found.projected_usd >= reading.cap
342 ):
343 sent += notification_service.notify(
344 db,
345 recipients,
346 _projected_message(
347 rule=rule,
348 index=index,
349 reading=reading,
350 found=found,
351 ws=ws,
352 place=place,
353 period_key=period_key,
354 ),
355 )
356 return sent
359def _holders_with_spend(db: Session, now: datetime) -> list[Workspace]:
360 """Every workspace a platform allowance could belong to that has spent
361 this month: organisations, and people's Personal workspaces."""
362 month = period_registry.get_period("month")
363 if month is None:
364 return []
365 since = month.start(now, 0)
366 rows = (
367 db.query(
368 GovernanceUsage.owner_organisation_id, GovernanceUsage.workspace_user_id
369 )
370 .filter(GovernanceUsage.occurred_at >= since)
371 .distinct()
372 .all()
373 )
374 found: dict[str, Workspace] = {}
375 for organisation_id, user_id in rows:
376 if organisation_id is not None:
377 ws = Workspace(WorkspaceKind.organisation, organisation_id)
378 found[ws.key] = ws
379 if user_id is not None:
380 ws = Workspace(WorkspaceKind.personal, user_id)
381 found[ws.key] = ws
382 return list(found.values())
385def _alert_allowance(db: Session, holder: Workspace, now: datetime) -> int:
386 found = allowance_service.for_workspace(holder)
387 if found is None:
388 return 0
389 window = UsageWindow(db, str(holder.id), population=found.population)
390 reading = action_registry.CostCapAction().reading(found.config(), window, now)
391 if reading is None or reading.spent is None:
392 return 0
393 level = level_crossed(reading.spent, reading.cap, ALLOWANCE_LEVELS)
394 if level is None:
395 return 0
396 place = where(db, holder)
397 period_key = _period_key(reading.figures, reading.span, now)
398 used_up = level >= 100
399 title = (
400 "The platform allowance is used up"
401 if used_up
402 else f"The platform allowance is {level}% used"
403 )
404 resets = action_registry.resets_phrase(reading.figures)
405 body = f"{_usd(reading.spent)} of {_usd(reading.cap)} this month in {place}. " + (
406 f"Work here is refused until it starts again. {resets}" if used_up else resets
407 )
408 return notification_service.notify(
409 db,
410 notification_service.governors(db, holder),
411 notification_service.Message(
412 kind=notification_service.AllowanceThreshold.key,
413 title=title,
414 body=body,
415 link=SPEND_LINK,
416 workspace=holder,
417 workspace_name=place,
418 dedupe_key=f"allowance:{holder.key}:{period_key}:{level}",
419 data={
420 "level": level,
421 "spent_usd": float(reading.spent),
422 "cap_usd": float(reading.cap),
423 "resets_at": reading.figures.get("resets_at"),
424 },
425 ),
426 )
429def run(db: Session, *, now: datetime | None = None) -> RunResult:
430 """Send every alert that is due and not yet sent."""
431 now = now or aware_utcnow()
432 result = RunResult()
433 for rule in _cost_cap_rules(db):
434 ws = workspace_service.home_of(db, rule, named=True)
435 if ws is None:
436 continue
437 try:
438 place = where(db, ws)
439 recipients = notification_service.governors(db, ws)
440 owner = getattr(rule, "owner_user_id", None) or ws.id
441 window = UsageWindows(db, str(owner)).for_rule(rule)
442 for index, action in enumerate(rule.actions or []):
443 if not (
444 isinstance(action, dict)
445 and action.get("type") == action_registry.CostCapAction.type
446 ):
447 continue
448 result.budgets += 1
449 result.sent += _alert_cap(
450 db,
451 rule,
452 index,
453 action,
454 window,
455 ws=ws,
456 place=place,
457 recipients=recipients,
458 now=now,
459 )
460 except Exception:
461 # One budget that cannot be read must not stop the others' alerts.
462 logger.exception("Could not check budget %s for alerts", rule.id)
463 db.rollback()
464 result.errors.append(str(rule.id))
465 for holder in _holders_with_spend(db, now):
466 try:
467 result.sent += _alert_allowance(db, holder, now)
468 except Exception:
469 logger.exception("Could not check %s's platform allowance", holder.key)
470 db.rollback()
471 result.errors.append(holder.key)
472 return result
475def configured(action: dict[str, Any]) -> list[str]:
476 """A cost cap's alerts as the budget page lists them."""
477 levels, projected = alerts_of(action)
478 return [str(level) for level in levels] + (
479 [action_registry.QuotaAlert.projected.value] if projected else []
480 )