Coverage for app / services / spend_guard.py: 83%
157 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""
2The deployment's spending ceiling — a hard stop on what model calls may cost.
4Inference is the platform's one open-ended cost. A loop that keeps calling,
5a benchmark that runs longer than planned, or a leaked credential would bill
6without limit, and nothing the providers or AWS offer stops it in time:
7provider and AWS budgets alert hours after the money is spent. svc-ai is the
8only service that reaches a model, and it already prices every call exactly
9(``metering``), so the ceiling is enforced here, before each call:
11* **Two limits**, a UTC day and a calendar month (``LLM_DAILY_CEILING_USD``,
12 ``LLM_MONTHLY_CEILING_USD``). A call is refused once either is reached,
13 with ``SpendCeilingReached``, a fatal model error: the turn ends once, with
14 a message saying which limit and when it resets.
15* **Everything counts.** Chat, structured calls, embeddings, the platform
16 benchmark, built-in dashboard tiles and crawls all reach a model through
17 svc-ai, including the work no user's ledger records.
18* **Unpriced calls count at the dearest rate in the catalogue**, so a model
19 with no price on record cannot spend round the limit.
20* **Fail-safe defaults.** An unset ceiling is the default ($15 a day, $150 a
21 month), never "unlimited". Only an explicit ``off`` lifts it.
23What it is not: a cap on a call already in flight. A call is checked before
24it starts, so the calls running when the limit is reached finish, and the
25total can pass the ceiling by what they cost. Their size is bounded by each
26call's ``max_tokens``.
28The running totals are held in memory (one svc-ai process) and written to
29``spend_counters`` after every call, so a restart picks up where the day
30left off. They are re-read every ``SYNC_SECONDS``, taking whichever of the
31two is higher, so a second process would see the other's spend within that
32window.
33"""
35from __future__ import annotations
37import logging
38import threading
39import time
40from dataclasses import dataclass
41from datetime import datetime, timedelta, timezone
42from decimal import Decimal, InvalidOperation
43from typing import Any, Callable, Protocol
45from app.services import model_errors
47logger = logging.getLogger(__name__)
49#: The ceilings when nothing is configured. Fail-safe: a missing setting
50#: must never mean unlimited spend.
51DEFAULT_DAILY_USD = Decimal("15")
52DEFAULT_MONTHLY_USD = Decimal("150")
54#: The values that lift a ceiling. Deliberately not the empty string or
55#: ``CHANGE_ME``, which other settings read as "off": an unset ceiling is
56#: the default one.
57OFF_VALUES = frozenset({"off", "none", "disabled"})
59#: How often the in-memory totals are reconciled with ``spend_counters``.
60SYNC_SECONDS = 30.0
62DAY = "day"
63MONTH = "month"
64_ADJECTIVE = {DAY: "daily", MONTH: "monthly"}
67def parse_ceiling(raw: Any, default: Decimal) -> Decimal | None:
68 """A ceiling in USD, or None when it is lifted.
70 Unset, blank or unreadable is the default, never "no limit": a typo in a
71 deployment's settings must not remove the only hard stop on spend.
72 """
73 text = str(raw).strip().lower() if raw is not None else ""
74 if text in OFF_VALUES:
75 return None
76 if not text or text == "change_me":
77 return default
78 try:
79 value = Decimal(text)
80 except InvalidOperation:
81 logger.error(
82 "[spend] unreadable ceiling %r — using the default of $%s", raw, default
83 )
84 return default
85 if value < 0:
86 logger.error("[spend] negative ceiling %r — using the default", raw)
87 return default
88 return value
91@dataclass(frozen=True)
92class Period:
93 """One spending period: its counter key and when it next resets."""
95 kind: str
96 key: str
97 resets_at: datetime
100def periods(now: datetime) -> tuple[Period, Period]:
101 """The UTC day and the calendar month ``now`` falls in."""
102 now = now.astimezone(timezone.utc)
103 tomorrow = (now + timedelta(days=1)).replace(
104 hour=0, minute=0, second=0, microsecond=0
105 )
106 next_month = (now.replace(day=28) + timedelta(days=4)).replace(
107 day=1, hour=0, minute=0, second=0, microsecond=0
108 )
109 return (
110 Period(DAY, f"day:{now:%Y-%m-%d}", tomorrow),
111 Period(MONTH, f"month:{now:%Y-%m}", next_month),
112 )
115class Store(Protocol):
116 """Where the totals persist between restarts."""
118 def load(self, keys: list[str]) -> dict[str, Decimal]: ...
120 def add(self, key: str, amount: Decimal) -> None: ...
123class MemoryStore:
124 """Totals that last as long as the process: tests, and nothing else."""
126 def __init__(self) -> None:
127 self.totals: dict[str, Decimal] = {}
129 def load(self, keys: list[str]) -> dict[str, Decimal]:
130 return {k: self.totals[k] for k in keys if k in self.totals}
132 def add(self, key: str, amount: Decimal) -> None:
133 self.totals[key] = self.totals.get(key, Decimal(0)) + amount
136class DatabaseStore:
137 """``spend_counters`` in svc-ai's own database."""
139 def load(self, keys: list[str]) -> dict[str, Decimal]:
140 from app.db.postgres.engine import SessionLocal
141 from app.db.postgres.models import SpendCounter
143 db = SessionLocal()
144 try:
145 rows = db.query(SpendCounter).filter(SpendCounter.period.in_(keys)).all()
146 return {row.period: Decimal(str(row.cost_usd or 0)) for row in rows}
147 finally:
148 db.close()
150 def add(self, key: str, amount: Decimal) -> None:
151 from sqlalchemy.dialects.postgresql import insert
153 from app.db.postgres.engine import SessionLocal
154 from app.db.postgres.models import SpendCounter
155 from app.util.time import aware_utcnow
157 now = aware_utcnow()
158 statement = insert(SpendCounter).values(
159 period=key, cost_usd=amount, updated_at=now
160 )
161 statement = statement.on_conflict_do_update(
162 index_elements=[SpendCounter.period],
163 set_={
164 "cost_usd": SpendCounter.cost_usd + statement.excluded.cost_usd,
165 "updated_at": now,
166 },
167 )
168 db = SessionLocal()
169 try:
170 db.execute(statement)
171 db.commit()
172 finally:
173 db.close()
176class SpendCeilingReached(model_errors.ModelUnavailableError):
177 """A model call refused because the deployment's ceiling is reached."""
179 def __init__(self, period: Period, ceiling: Decimal) -> None:
180 super().__init__(model_errors.FatalKind.BUDGET, None, "")
181 self.args = (
182 f"{_ADJECTIVE[period.kind]} spending ceiling of ${ceiling} reached",
183 )
184 self.period = period
185 self.ceiling = ceiling
187 @property
188 def user_message(self) -> str:
189 when = (
190 "at midnight UTC"
191 if self.period.kind == DAY
192 else f"on {self.period.resets_at.day} {self.period.resets_at:%B} (UTC)"
193 )
194 return (
195 f"This deployment has reached its {_ADJECTIVE[self.period.kind]} AI "
196 "spending "
197 f"limit (US${self.ceiling:,.2f}). It resets {when}; an administrator "
198 "can raise it."
199 )
201 def payload(self) -> dict[str, object]:
202 return {
203 **super().payload(),
204 "period": self.period.kind,
205 "resets_at": self.period.resets_at.isoformat(),
206 }
209class SpendGuard:
210 """The running totals and the check made before every model call."""
212 def __init__(
213 self,
214 daily: Decimal | None,
215 monthly: Decimal | None,
216 store: Store | None = None,
217 clock: Callable[[], datetime] | None = None,
218 ) -> None:
219 self.ceilings = {DAY: daily, MONTH: monthly}
220 self._store = store if store is not None else DatabaseStore()
221 self._clock = clock or (lambda: datetime.now(timezone.utc))
222 self._lock = threading.Lock()
223 #: Counter key → USD spent, for the periods seen in this process.
224 self._totals: dict[str, Decimal] = {}
225 self._synced_at = 0.0
227 @property
228 def enabled(self) -> bool:
229 return any(c is not None for c in self.ceilings.values())
231 def _sync(self, keys: list[str], *, force: bool = False) -> None:
232 """Reconcile with the store: the higher of memory and the store wins
233 (a write that failed leaves memory ahead; another process leaves the
234 store ahead)."""
235 if not force and time.monotonic() - self._synced_at < SYNC_SECONDS:
236 if all(k in self._totals for k in keys):
237 return
238 try:
239 stored = self._store.load(keys)
240 except Exception: # noqa: BLE001 — keep counting in memory
241 logger.warning("[spend] could not read spend_counters", exc_info=True)
242 stored = {}
243 for key in keys:
244 self._totals[key] = max(
245 self._totals.get(key, Decimal(0)), stored.get(key, Decimal(0))
246 )
247 self._synced_at = time.monotonic()
249 def check(self) -> None:
250 """Refuse the coming call if a ceiling is reached."""
251 if not self.enabled:
252 return
253 current = periods(self._clock())
254 with self._lock:
255 self._sync([p.key for p in current])
256 for period in current:
257 ceiling = self.ceilings[period.kind]
258 if ceiling is not None and self._totals[period.key] >= ceiling:
259 logger.warning(
260 "[spend] %s ceiling of $%s reached ($%s spent) — refusing",
261 period.kind,
262 ceiling,
263 self._totals[period.key],
264 )
265 raise SpendCeilingReached(period, ceiling)
267 def account(self, cost: Decimal) -> None:
268 """Add one call's cost to the current day and month."""
269 if cost <= 0:
270 return
271 current = periods(self._clock())
272 with self._lock:
273 self._sync([p.key for p in current])
274 for period in current:
275 self._totals[period.key] = self._totals[period.key] + cost
276 for period in current:
277 try:
278 self._store.add(period.key, cost)
279 except Exception: # noqa: BLE001 — memory still counts it
280 logger.warning(
281 "[spend] could not record spend in spend_counters", exc_info=True
282 )
284 def status(self) -> dict[str, Any]:
285 """What has been spent against each ceiling, for operators."""
286 current = periods(self._clock())
287 with self._lock:
288 self._sync([p.key for p in current], force=True)
289 totals = {p.key: self._totals[p.key] for p in current}
290 out: dict[str, Any] = {"enabled": self.enabled}
291 for period in current:
292 ceiling = self.ceilings[period.kind]
293 spent = totals[period.key]
294 out[period.kind] = {
295 "spent_usd": float(spent),
296 "ceiling_usd": float(ceiling) if ceiling is not None else None,
297 "remaining_usd": (
298 float(max(ceiling - spent, Decimal(0)))
299 if ceiling is not None
300 else None
301 ),
302 "reached": ceiling is not None and spent >= ceiling,
303 "resets_at": period.resets_at.isoformat(),
304 }
305 return out
308_guard: SpendGuard | None = None
309_guard_lock = threading.Lock()
312def guard() -> SpendGuard:
313 """The process's guard, configured from settings on first use."""
314 global _guard
315 with _guard_lock:
316 if _guard is None:
317 from app.common.settings import get_settings
319 settings = get_settings()
320 _guard = SpendGuard(
321 parse_ceiling(settings.LLM_DAILY_CEILING_USD, DEFAULT_DAILY_USD),
322 parse_ceiling(settings.LLM_MONTHLY_CEILING_USD, DEFAULT_MONTHLY_USD),
323 )
324 logger.info(
325 "[spend] ceilings: day %s, month %s",
326 _guard.ceilings[DAY] if _guard.ceilings[DAY] is not None else "off",
327 _guard.ceilings[MONTH] if _guard.ceilings[MONTH] is not None else "off",
328 )
329 return _guard
332def reset_for_tests(replacement: SpendGuard | None = None) -> None:
333 """Swap the process's guard (tests only)."""
334 global _guard
335 with _guard_lock:
336 _guard = replacement
339def check() -> None:
340 """Refuse the coming model call if a ceiling is reached."""
341 guard().check()