Coverage for app / services / budgets / status.py: 87%

169 statements  

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

1""" 

2Where each budget governing a workspace stands (cost-control plan, A1.2). 

3 

4A budget is a ``cost_cap`` rule (``rules/actions.py``): there is no second 

5kind of thing to keep in step with the caps, and no second enforcement path. 

6This module reads every active cap that governs the request's workspace — 

7its own, and for a project what it inherits (Required, pinned to it, or 

8declared) — and says for each: the cap, what its period has spent, what is 

9left, when it resets, how it compares with the period before, and where it 

10is heading. 

11 

12**It reads exactly what the cap decides on.** Each figure comes from the 

13cap's own reading (``CostCapAction.reading``) against the usage window the 

14rule engine would hand it (``UsageWindows.for_rule``), so ``reached`` and 

15``blocks`` hold exactly when the next turn the cap governs would be refused 

16— ``tests/test_budgets.py`` pins that, as Assurance's "Passing" is pinned to 

17the evidence gate. That includes the estimate for calls no catalogue could 

18price, which a cap counts high; spend figures elsewhere show the measured 

19"at least" amount, so a budget can read a little higher than them. 

20 

21**Who sees what.** Every member sees each budget's totals. What each 

22colleague spent (``members``) is for those who govern the workspace — its 

23admins and governance editors, or the owner of a personal one — since it is 

24new information about the people beside them. A cap given to each member 

25(``share: per_member``) shows the viewer their own allowance. 

26 

27**Room to finish.** A cap keeps back what a turn usually costs (its 

28``reserve``): with less than that left, the next turn is refused, not cut off 

29part-way. The page reads each cap with the workspace's typical turn as that 

30reserve, so ``reached`` / ``blocks`` hold when new turns are refused, and the 

31note says when it is the reserve rather than the cap. 

32 

33**The platform allowance** (``budgets/allowance.py``) is served beside the 

34budgets (``allowance``), read the same way, and editable by nobody here. 

35 

36A budget whose figures cannot be read reads ``unavailable``; the listing 

37never fails because one did. 

38""" 

39 

40from __future__ import annotations 

41 

42import logging 

43from dataclasses import replace 

44from types import SimpleNamespace 

45from datetime import datetime, timedelta 

46from decimal import Decimal 

47from enum import StrEnum 

48from typing import Any 

49from uuid import UUID 

50 

51from sqlalchemy.orm import Session 

52 

53from app.db.postgres.enums import RuleEnum 

54from app.db.postgres.models import GovernanceUsage, Rule, User 

55from app.services import access as access_service 

56from app.services import inheritance 

57from app.services import membership as membership_service 

58from app.services import workspace as workspace_service 

59from app.services.budgets import allowance as allowance_service 

60from app.services.budgets import forecast as forecast_service 

61from app.services.rules import actions as action_registry 

62from app.services.rules import periods as period_registry 

63from app.services.usage import ( 

64 Span, 

65 TurnReserve, 

66 UsageWindow, 

67 UsageWindows, 

68 rule_population, 

69 typical_turn_cost, 

70) 

71from app.util.time import aware_utcnow 

72 

73logger = logging.getLogger(__name__) 

74 

75#: Share of a cap at which a budget reads "nearly used". 

76NEAR_SHARE = Decimal("0.8") 

77 

78#: How far back a forecast looks for the first spend — the history it has. 

79HISTORY_LOOKBACK_DAYS = 366 

80 

81 

82class BudgetStatus(StrEnum): 

83 """Where a budget stands, worst first (fe-core ``BUDGET_STATUS``).""" 

84 

85 #: Its period's spend has reached the cap. 

86 reached = "reached" 

87 #: At the trailing week's rate it reaches the cap before it resets. 

88 projected_over = "projected_over" 

89 #: Past ``NEAR_SHARE`` of the cap. 

90 near = "near" 

91 #: Under the cap, and heading to stay under it. 

92 ok = "ok" 

93 #: Its figures could not be read, or it has no usable amount. 

94 unavailable = "unavailable" 

95 

96 

97STATUS_ORDER = tuple(BudgetStatus) 

98 

99 

100def _money(value: Decimal | None) -> float | None: 

101 return float(value) if value is not None else None 

102 

103 

104def governs(db: Session, ws: workspace_service.Workspace, user: User) -> bool: 

105 """Whether ``user`` governs ``ws``: its owner (Personal), an admin, or 

106 an editor of the governance area — who may see what each member spent.""" 

107 if ws.kind is workspace_service.WorkspaceKind.personal: 

108 return ws.id == user.id 

109 scope = ( 

110 membership_service.ORGANISATION 

111 if ws.kind is workspace_service.WorkspaceKind.organisation 

112 else membership_service.PROJECT 

113 ) 

114 m = membership_service.effective_membership(db, scope, ws.id, user.id) 

115 if m is None: 

116 return False 

117 if membership_service.role_of(m) is membership_service.MemberRole.admin: 

118 return True 

119 return ( 

120 access_service.effective(m).get(access_service.AccessArea.governance) 

121 is access_service.AccessLevel.editor 

122 ) 

123 

124 

125def cost_cap_rules(db: Session, ws: workspace_service.Workspace) -> list[Rule]: 

126 """Every active rule with a cost cap that governs work in ``ws``, as the 

127 rule engine selects them (``workspace.governing_rules``), marked with 

128 why each is here (``origin``).""" 

129 rules = ( 

130 db.query(Rule) 

131 .filter( 

132 Rule.layer == RuleEnum.Layer.access, 

133 Rule.is_active.is_(True), 

134 Rule.is_system.is_(False), 

135 workspace_service.governing_rules(ws), 

136 ) 

137 .order_by(Rule.priority.desc(), Rule.created_at.asc()) 

138 .all() 

139 ) 

140 capped = [ 

141 rule 

142 for rule in rules 

143 if any( 

144 isinstance(a, dict) and a.get("type") == action_registry.CostCapAction.type 

145 for a in rule.actions or [] 

146 ) 

147 ] 

148 return inheritance.annotate(capped, ws) 

149 

150 

151def _population(ws: workspace_service.Workspace, viewer: User) -> tuple[str, str]: 

152 """The ledger rows a workspace's own spend is: what a rule it owned 

153 would count (``usage.rule_population``) — an organisation's with its 

154 projects', a person's with their personal projects'.""" 

155 return rule_population(SimpleNamespace(**ws.owner_columns()), str(viewer.id)) 

156 

157 

158def _forecast( 

159 window: UsageWindow, 

160 span: Span, 

161 *, 

162 spent: Decimal | None, 

163 now: datetime, 

164 resets_at: datetime | None, 

165 cap: Decimal | None = None, 

166) -> forecast_service.Forecast: 

167 if resets_at is None: 

168 return forecast_service.project( 

169 spent=spent, daily={}, first_spent_at=None, now=now, resets_at=None 

170 ) 

171 midnight = now.replace(hour=0, minute=0, second=0, microsecond=0) 

172 trailing = replace( 

173 span, 

174 seconds=None, 

175 until=None, 

176 since=midnight - timedelta(days=forecast_service.TRAILING_DAYS), 

177 ) 

178 history = replace( 

179 span, 

180 seconds=None, 

181 until=None, 

182 since=now - timedelta(days=HISTORY_LOOKBACK_DAYS), 

183 ) 

184 return forecast_service.project( 

185 spent=spent, 

186 daily=window.daily_spent(trailing), 

187 first_spent_at=_aware(window.first_spent_at(history)), 

188 now=now, 

189 resets_at=resets_at, 

190 cap=cap, 

191 ) 

192 

193 

194def _aware(value: datetime | None) -> datetime | None: 

195 """A ledger time (naive UTC) as an aware one.""" 

196 if value is None or value.tzinfo is not None: 

197 return value 

198 from datetime import timezone 

199 

200 return value.replace(tzinfo=timezone.utc) 

201 

202 

203def forecast_json(found: forecast_service.Forecast) -> dict[str, Any]: 

204 return { 

205 "available": found.available, 

206 "unavailable": found.unavailable.value if found.unavailable else None, 

207 "note": ( 

208 forecast_service.UNAVAILABLE_NOTES[found.unavailable] 

209 if found.unavailable 

210 else None 

211 ), 

212 "projected_usd": _money(found.projected_usd), 

213 "low_usd": _money(found.low_usd), 

214 "high_usd": _money(found.high_usd), 

215 "daily_rate_usd": _money(found.daily_rate_usd), 

216 "days_used": found.days_used, 

217 "reaches_cap_at": found.reaches_cap_at, 

218 } 

219 

220 

221def status_of( 

222 reading: action_registry.CapReading | None, 

223 found: forecast_service.Forecast | None, 

224) -> BudgetStatus: 

225 """Where a cap stands. ``reached`` exactly when the cap refuses new turns 

226 — the reading it refuses on: used up, or (refusing rather than warning) 

227 with less left than a turn usually costs.""" 

228 if reading is None or reading.spent is None: 

229 return BudgetStatus.unavailable 

230 if reading.reached or (reading.short and not reading.warns): 

231 return BudgetStatus.reached 

232 if ( 

233 found is not None 

234 and found.projected_usd is not None 

235 and found.projected_usd >= reading.cap 

236 ): 

237 return BudgetStatus.projected_over 

238 if reading.cap > 0 and reading.spent >= reading.cap * NEAR_SHARE: 

239 return BudgetStatus.near 

240 return BudgetStatus.ok 

241 

242 

243def _names(db: Session, ids: list[UUID]) -> dict[UUID, str]: 

244 if not ids: 

245 return {} 

246 return { 

247 row.id: (row.name or row.email or "A member") 

248 for row in db.query(User.id, User.name, User.email) 

249 .filter(User.id.in_(ids)) 

250 .all() 

251 } 

252 

253 

254def _standing( 

255 window: UsageWindow, 

256 reading: action_registry.CapReading, 

257 period: period_registry.Period, 

258 now: datetime, 

259) -> dict[str, Any]: 

260 """A readable cap's figures: spent, left, its period, the one before, a 

261 forecast and where it stands — for a budget and the allowance alike.""" 

262 resets = period.resets_at(now) if period.calendar else None 

263 found = _forecast( 

264 window, 

265 reading.span, 

266 spent=reading.spent, 

267 now=now, 

268 resets_at=resets, 

269 cap=reading.cap, 

270 ) 

271 previous = None 

272 if period.calendar: 

273 start = reading.span.since 

274 before = period.previous_start(now, 0) 

275 if start is not None and before is not None: 

276 previous = window.spent(replace(reading.span, since=before, until=start)) 

277 status = status_of(reading, found) 

278 standing: dict[str, Any] = { 

279 "spent_usd": _money(reading.spent), 

280 "remaining_usd": _money(reading.remaining), 

281 "used_share": float(reading.spent / reading.cap) if reading.cap > 0 else None, 

282 "period_start": reading.span.since if period.calendar else None, 

283 "resets_at": resets, 

284 "previous_spent_usd": _money(previous), 

285 "forecast": forecast_json(found), 

286 "status": status.value, 

287 "blocks": reading.blocks, 

288 "reserve_usd": _money(reading.reserve), 

289 } 

290 if reading.short and not reading.warns: 

291 standing["note"] = ( 

292 f"Less than a typical turn here " 

293 f"({action_registry.usd_text(reading.reserve or Decimal(0))}) is " 

294 "left, so new turns are refused rather than cut off part-way." 

295 ) 

296 return standing 

297 

298 

299def _alerts(action: dict[str, Any]) -> list[str]: 

300 from app.services.budgets import alerts 

301 

302 return alerts.configured(action) 

303 

304 

305def _budget( 

306 db: Session, 

307 rule: Rule, 

308 index: int, 

309 action: dict[str, Any], 

310 window: UsageWindow, 

311 *, 

312 now: datetime, 

313 governor: bool, 

314 reserve: TurnReserve | None = None, 

315) -> dict[str, Any]: 

316 cap_action = action_registry.CostCapAction() 

317 reading = cap_action.reading( 

318 action, window, now, reserve=reserve.usd if reserve is not None else None 

319 ) 

320 period = period_registry.get_period( 

321 (reading.figures.get("period") if reading else None) or action.get("period") 

322 ) or period_registry.get_period(period_registry.DEFAULT) 

323 member = str(action.get("share") or "") == action_registry.QuotaShare.per_member 

324 types = [str(t) for t in action.get("execution_types") or [] if str(t).strip()] 

325 entry: dict[str, Any] = { 

326 "rule_id": rule.id, 

327 "rule_name": rule.name, 

328 "action_index": index, 

329 "origin": getattr(rule, "origin", None), 

330 "home_workspace": getattr(rule, "home_workspace", None), 

331 "scope_type": getattr(rule.scope_type, "value", rule.scope_type), 

332 "scope_id": str(rule.scope_id) if rule.scope_id else None, 

333 "required_for_projects": bool(getattr(rule, "required_for_projects", False)), 

334 "conditions": len(rule.conditions or []), 

335 "period": period.key, 

336 "period_label": period.label, 

337 "window_seconds": (reading.figures.get("window_seconds") if reading else None), 

338 "share": action_registry.QuotaShare.per_member.value 

339 if member 

340 else action_registry.QuotaShare.shared.value, 

341 "counts": "yours" if member else "workspace", 

342 "execution_types": types, 

343 "on_reach": action_registry.QuotaResponse.warn.value 

344 if str(action.get("on_reach") or "") == action_registry.QuotaResponse.warn 

345 else action_registry.QuotaResponse.block.value, 

346 # When it tells those who govern the workspace (``budgets/alerts.py``). 

347 "alert_at": _alerts(action), 

348 "cap_usd": _money(reading.cap) if reading else None, 

349 "spent_usd": None, 

350 "remaining_usd": None, 

351 "used_share": None, 

352 "period_start": None, 

353 "resets_at": None, 

354 "previous_spent_usd": None, 

355 "forecast": None, 

356 "status": BudgetStatus.unavailable.value, 

357 "blocks": False, 

358 "reserve_usd": None, 

359 "members": None, 

360 "note": None, 

361 } 

362 if reading is None: 

363 entry["note"] = "It names no usable amount, so it caps nothing." 

364 return entry 

365 if reading.spent is None: 

366 entry["note"] = "Its spend could not be read just now." 

367 return entry 

368 

369 entry.update(_standing(window, reading, period, now)) 

370 if governor: 

371 split = window.spent_by_member(replace(reading.span, member=False)) 

372 if split is not None: 

373 names = _names(db, list(split)) 

374 entry["members"] = sorted( 

375 ( 

376 { 

377 "user_id": user_id, 

378 "name": names.get(user_id, "A member"), 

379 "spent_usd": float(total), 

380 } 

381 for user_id, total in split.items() 

382 if user_id is not None 

383 ), 

384 key=lambda m: -m["spent_usd"], 

385 ) 

386 return entry 

387 

388 

389def overview( 

390 db: Session, viewer: User, ws: workspace_service.Workspace, now: datetime 

391) -> dict[str, Any]: 

392 """The workspace's spend this calendar month, last month and where this 

393 one is heading — counted as a budget for the whole workspace would be.""" 

394 month = period_registry.get_period("month") 

395 window = UsageWindow(db, str(viewer.id), population=_population(ws, viewer)) 

396 start = month.start(now, 0) 

397 span = Span(since=start) 

398 spent = window.spent(span) 

399 before = month.previous_start(now, 0) 

400 last = window.spent(Span(since=before, until=start)) if before else None 

401 found = _forecast( 

402 window, span, spent=spent, now=now, resets_at=month.resets_at(now) 

403 ) 

404 return { 

405 "period_start": start, 

406 "resets_at": month.resets_at(now), 

407 "spent_usd": _money(spent), 

408 "last_month_usd": _money(last), 

409 "forecast": forecast_json(found), 

410 } 

411 

412 

413def typical_turn(db: Session, ws: workspace_service.Workspace) -> TurnReserve: 

414 """What a turn in ``ws`` usually costs — the reserve its page reads each 

415 cap with (the engine reads the turn's own resource's).""" 

416 return typical_turn_cost( 

417 db, 

418 scope_type=None, 

419 scope_id=None, 

420 where=ws.stamped(GovernanceUsage, projects=False), 

421 ) 

422 

423 

424def allowance( 

425 db: Session, 

426 viewer: User, 

427 ws: workspace_service.Workspace, 

428 *, 

429 now: datetime, 

430 reserve: TurnReserve | None = None, 

431) -> dict[str, Any] | None: 

432 """The platform allowance work in ``ws`` counts against, where it 

433 stands — or None when the deployment sets none for it.""" 

434 found = allowance_service.for_workspace(ws) 

435 if found is None: 

436 return None 

437 month = period_registry.get_period("month") 

438 if month is None: 

439 raise RuntimeError("The calendar month period is not registered") 

440 window = UsageWindow(db, str(viewer.id), population=found.population) 

441 reading = action_registry.CostCapAction().reading( 

442 found.config(), 

443 window, 

444 now, 

445 reserve=reserve.usd if reserve is not None else None, 

446 ) 

447 entry: dict[str, Any] = { 

448 "name": allowance_service.NAME, 

449 "holder": found.holder.kind.value, 

450 "holder_workspace": found.holder.key, 

451 "cap_usd": _money(found.amount), 

452 "period": month.key, 

453 "period_label": month.label, 

454 "status": BudgetStatus.unavailable.value, 

455 "blocks": False, 

456 "note": None, 

457 } 

458 if reading is None or reading.spent is None: 

459 entry["note"] = "Its spend could not be read just now." 

460 return entry 

461 entry.update(_standing(window, reading, month, now)) 

462 return entry 

463 

464 

465def budgets( 

466 db: Session, 

467 viewer: User, 

468 ws: workspace_service.Workspace, 

469 *, 

470 now: datetime | None = None, 

471) -> dict[str, Any]: 

472 """Every budget governing ``ws``, worst first, the platform allowance, 

473 and the workspace's month — as ``viewer`` may see them.""" 

474 now = now or aware_utcnow() 

475 governor = governs(db, ws, viewer) 

476 windows = UsageWindows(db, str(viewer.id)) 

477 reserve = typical_turn(db, ws) 

478 listed: list[dict[str, Any]] = [] 

479 for rule in cost_cap_rules(db, ws): 

480 for index, action in enumerate(rule.actions or []): 

481 if not ( 

482 isinstance(action, dict) 

483 and action.get("type") == action_registry.CostCapAction.type 

484 ): 

485 continue 

486 try: 

487 listed.append( 

488 _budget( 

489 db, 

490 rule, 

491 index, 

492 action, 

493 windows.for_rule(rule), 

494 now=now, 

495 governor=governor, 

496 reserve=reserve, 

497 ) 

498 ) 

499 except Exception: 

500 # One budget that cannot be read must not take the page down. 

501 logger.exception("Could not read budget %s[%d]", rule.id, index) 

502 listed.append( 

503 { 

504 "rule_id": rule.id, 

505 "rule_name": rule.name, 

506 "action_index": index, 

507 "status": BudgetStatus.unavailable.value, 

508 "note": "Its figures could not be read just now.", 

509 } 

510 ) 

511 listed.sort(key=lambda b: STATUS_ORDER.index(BudgetStatus(b["status"]))) 

512 try: 

513 month = overview(db, viewer, ws, now) 

514 except Exception: 

515 logger.exception("Could not read workspace %s's month", ws.key) 

516 month = None 

517 try: 

518 platform = allowance(db, viewer, ws, now=now, reserve=reserve) 

519 except Exception: 

520 logger.exception("Could not read workspace %s's platform allowance", ws.key) 

521 platform = None 

522 return { 

523 "workspace": ws.key, 

524 "governs": governor, 

525 "overview": month, 

526 "budgets": listed, 

527 "allowance": platform, 

528 "typical_turn_usd": _money(reserve.usd), 

529 }