Coverage for app / services / usage.py: 92%
295 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"""
2The governance usage ledger — what rate limits and cost caps count.
4Three things live here:
6``estimate_cost`` Tokens plus the invoked model's per-token price, in USD.
7``record_usage`` Append one row for an invocation that was attempted.
8``UsageWindow`` Read back "how many" and "how much" over a window — what
9 the ``rate_limit`` and ``cost_cap`` actions ask.
11The ledger has a second reader now. ``app.services.stats`` slices the same
12rows by agent, model, project or organisation for the dashboards, which is
13why failed invocations are recorded here at all: an error rate per agent has
14to be counted somewhere, and svc-ai's per-invocation record carries no agent,
15project or organisation to count it against. The two readers want different
16populations and say so — quotas filter to ``ok``, a breakdown does not — so
17what a rate limit counts is unchanged by any of it.
19Why svc-core keeps its own counter at all: svc-ai owns the authoritative
20per-invocation record, but a cap has to be judged *before* svc-ai is called.
21Reading it across the service boundary would put a synchronous hop in front
22of every governed request and make a svc-ai outage a governance failure —
23fail-open and fail-closed both being bad answers. A local append-only ledger
24avoids the question.
26Cost needs no plumbing from svc-ai: ``Model.Read`` already carries
27``input_cost_per_token`` / ``output_cost_per_token``, and the invocation paths
28have already fetched the model record by the time they have a token count.
29"""
31from __future__ import annotations
33import logging
34from dataclasses import dataclass
35from datetime import date, datetime, timedelta
36from decimal import Decimal, InvalidOperation
37from typing import Any
38from uuid import UUID
40from sqlalchemy import Date, cast, func
41from sqlalchemy.exc import SQLAlchemyError
42from sqlalchemy.orm import Session
44from app.db.postgres.enums import RuleEnum, UsageEnum
45from app.db.postgres.models import GovernanceUsage
46from app.services.rules import scopes as scope_registry
47from app.util.time import aware_utcnow
49logger = logging.getLogger(__name__)
52def _decimal(value: Any) -> Decimal | None:
53 """Exact decimal form of ``value``, or None when it is not a number.
55 Prices arrive as JSON — strings from svc-ai's ``Decimal`` fields — so this
56 goes through ``Decimal(str(...))`` rather than float, which would
57 reintroduce the rounding error the column's ``Numeric`` type exists to
58 avoid.
59 """
60 if value is None or isinstance(value, bool):
61 return None
62 try:
63 return Decimal(str(value))
64 except (InvalidOperation, ValueError, TypeError):
65 return None
68def estimate_cost(
69 input_tokens: int,
70 output_tokens: int,
71 model_info: dict[str, Any] | None,
72) -> Decimal | None:
73 """USD this invocation cost, or None when the model publishes no price.
75 None is not zero, and the difference matters: a cost cap that read an
76 unpriced model as free would never fire, which is the silent
77 non-enforcement this whole feature exists to prevent. ``cost_cap`` treats
78 a null differently from a zero for exactly that reason.
80 A model priced on only one side (input but not output) still yields an
81 estimate from the side that is priced — a partial figure is closer to the
82 truth than nothing, and it can only under-estimate, never over-charge.
83 """
84 if not model_info:
85 return None
87 input_price = _decimal(model_info.get("input_cost_per_token"))
88 output_price = _decimal(model_info.get("output_cost_per_token"))
89 if input_price is None and output_price is None:
90 return None
92 total = Decimal(0)
93 if input_price is not None:
94 total += input_price * Decimal(int(input_tokens or 0))
95 if output_price is not None:
96 total += output_price * Decimal(int(output_tokens or 0))
97 return total
100def turn_cost(
101 measured: Any,
102 input_tokens: int = 0,
103 output_tokens: int = 0,
104 model_info: dict[str, Any] | None = None,
105) -> Decimal | None:
106 """What one invocation cost — the figure its ledger row records.
108 What svc-ai metered wins: priced per call on the model that answered,
109 across every model the run used. When it priced nothing, the metered
110 tokens (or, with nothing metered, the caller's) are priced at the one
111 model named — :func:`estimate_cost`. None when no price is known.
112 """
113 if measured is not None and getattr(measured, "measured", False):
114 if measured.cost_usd is not None:
115 return measured.cost_usd
116 input_tokens, output_tokens = measured.input_tokens, measured.output_tokens
117 return estimate_cost(input_tokens, output_tokens, model_info)
120def audit_figures(
121 *,
122 latency_ms: float | None,
123 measured: Any = None,
124 input_tokens: int = 0,
125 output_tokens: int = 0,
126 model_info: dict[str, Any] | None = None,
127) -> dict[str, Any]:
128 """What an audit rule may ask of an invocation that has returned: how long
129 the model took (``latency_ms``) and what it cost (``estimated_cost_usd``).
131 The same figures, computed the same way, as the ledger row the call site
132 writes — so a rule flagging "over $0.50" and the spend dashboard never
133 disagree about one invocation. A figure that is not known is left out,
134 and a condition on it does not match: an unpriced model is not free.
135 """
136 figures: dict[str, Any] = {}
137 if latency_ms is not None:
138 figures["latency_ms"] = round(float(latency_ms), 1)
139 cost = turn_cost(measured, input_tokens, output_tokens, model_info)
140 if cost is not None:
141 figures["estimated_cost_usd"] = float(cost)
142 return figures
145def record_usage(
146 db: Session,
147 *,
148 owner_user_id: str | UUID,
149 execution_type: str | None = None,
150 scope_type: RuleEnum.Scope | str | None = None,
151 scope_id: str | UUID | None = None,
152 owner_project_id: str | UUID | None = None,
153 owner_organisation_id: str | UUID | None = None,
154 ai_model_id: str | UUID | None = None,
155 input_tokens: int = 0,
156 output_tokens: int = 0,
157 model_info: dict[str, Any] | None = None,
158 estimated_cost_usd: Decimal | None = None,
159 latency_ms: float | None = None,
160 outcome: UsageEnum.Outcome | str | None = None,
161 source_type: UsageEnum.Source | str | None = None,
162 source_id: str | UUID | None = None,
163 measured: Any = None,
164 workspace: Any = None,
165 invocation_id: str | UUID | None = None,
166) -> GovernanceUsage | None:
167 """Append one ledger row for an invocation that reached the model.
169 ``invocation_id`` is the governed turn the spend belongs to
170 (``rule_engine.new_invocation_id``) — what joins this row to the turn's
171 messages, rules, flags and svc-ai's traces in its decision record. Every
172 answer, skill run and evaluation cell passes one.
174 ``workspace`` is where it happened (``app/services/workspace.py``); its
175 stamp says whose quotas count the row. Without one, the stamp follows
176 the owner columns given — a project's row is completed with its
177 organisation, or for a personal project its owner, and a row with
178 neither belongs to the invoker's personal workspace.
180 ``source_type`` / ``source_id`` attribute the spend to the resource that
181 caused it (``UsageEnum.Source``) — what a resource's cost card and the
182 ``source`` breakdown dimension count. Every LLM path passes one; the
183 registry of paths is ``services/llm_paths.py``.
185 ``measured`` is the ``ai_client.UsageCapture`` around the svc-ai call.
186 When svc-ai metered anything, its figures win: tokens summed over every
187 model call and cost priced per call on the model that answered. The
188 ``input_tokens`` / ``model_info`` estimate is the fallback for a call
189 svc-ai did not meter — it prices every token at the one model named,
190 which is wrong for any run with more than one model in it.
192 ``outcome`` says whether it came back. It defaults to ``ok``, so every
193 existing call site records exactly what it recorded before, and a failed
194 attempt is written by passing ``UsageEnum.Outcome.error``. Failures are on
195 the ledger for the dashboards — an error rate per agent or per model has
196 to be counted somewhere, and svc-ai's record carries neither. A rate
197 limit does not count them (:class:`UsageWindow` counts only work that
198 came back), but a cost cap counts what they cost: a call made before the
199 failure was paid for.
201 Does not commit — the caller appends it to the same transaction as the
202 message it documents, so the ledger cannot count a turn that was rolled
203 back.
205 Never raises. A counter is worth less than the invocation it describes:
206 failing a user's request because the ledger write failed would be the
207 wrong trade, and the failure is logged loudly instead. The consequence is
208 understood and bounded — an unrecorded invocation slightly *under*-counts
209 a limit, so the error is toward letting work through, never toward
210 refusing it on a number that was never real.
211 """
212 try:
213 scope = _coerce_scope(scope_type)
214 llm_calls = unpriced_calls = 0
215 unpriced_estimate: Decimal | None = None
216 cost = (
217 estimated_cost_usd
218 if estimated_cost_usd is not None
219 else turn_cost(measured, input_tokens, output_tokens, model_info)
220 )
221 if measured is not None and getattr(measured, "measured", False):
222 input_tokens = measured.input_tokens
223 output_tokens = measured.output_tokens
224 llm_calls = measured.calls
225 unpriced_calls = measured.unpriced_calls
226 # What a cap counts the unpriced calls as (see the column).
227 unpriced_estimate = _decimal(
228 getattr(measured, "unpriced_estimate_usd", None)
229 )
230 stamp = workspace_stamp(
231 db,
232 workspace=workspace,
233 owner_user_id=owner_user_id,
234 owner_project_id=owner_project_id,
235 owner_organisation_id=owner_organisation_id,
236 )
237 row = GovernanceUsage(
238 owner_user_id=_uuid(owner_user_id),
239 scope_type=scope,
240 scope_id=_uuid(scope_id),
241 # Stamped so a workspace's quota has an axis to count on:
242 # ``scope_type`` records what ran, never where it happened.
243 **stamp,
244 execution_type=execution_type,
245 ai_model_id=_uuid(ai_model_id),
246 input_tokens=int(input_tokens or 0),
247 output_tokens=int(output_tokens or 0),
248 estimated_cost_usd=cost,
249 latency_ms=_positive_int(latency_ms),
250 outcome=_coerce_outcome(outcome),
251 source_type=str(source_type) if source_type else None,
252 source_id=_uuid(source_id),
253 llm_calls=llm_calls,
254 unpriced_calls=unpriced_calls,
255 unpriced_estimate_usd=unpriced_estimate,
256 invocation_id=_uuid(invocation_id),
257 occurred_at=aware_utcnow(),
258 )
259 db.add(row)
260 return row
261 except Exception:
262 logger.exception(
263 "Could not record governance usage for user %s — rate limits and "
264 "cost caps will under-count this invocation",
265 owner_user_id,
266 )
267 return None
270def workspace_stamp(
271 db: Session,
272 *,
273 workspace: Any = None,
274 owner_user_id: Any = None,
275 owner_project_id: Any = None,
276 owner_organisation_id: Any = None,
277) -> dict[str, UUID | None]:
278 """The workspace columns for a ledger or activity row: ``workspace``'s
279 stamp, or one completed from the owner columns a caller passed."""
280 if workspace is not None:
281 return workspace.ledger_stamp()
282 project_id = _uuid(owner_project_id)
283 organisation_id = _uuid(owner_organisation_id)
284 workspace_user_id = None
285 if project_id is not None:
286 from app.db.postgres.models import Project
288 project = db.get(Project, project_id)
289 parent_org = getattr(project, "owner_organisation_id", None)
290 parent_user = getattr(project, "owner_user_id", None)
291 if isinstance(parent_org, UUID):
292 organisation_id = parent_org
293 if isinstance(parent_user, UUID):
294 workspace_user_id = parent_user
295 elif organisation_id is None:
296 workspace_user_id = _uuid(owner_user_id)
297 return {
298 "owner_project_id": project_id,
299 "owner_organisation_id": organisation_id,
300 "workspace_user_id": workspace_user_id,
301 }
304def _positive_int(value: Any) -> int | None:
305 """Whole milliseconds, or None when the figure is missing or nonsensical.
307 A negative or non-numeric duration is dropped rather than stored: the
308 statistics average these, and one bad sample would drag a model's
309 measured latency somewhere no observation supports.
310 """
311 if value is None or isinstance(value, bool):
312 return None
313 try:
314 rounded = round(float(value))
315 except (TypeError, ValueError):
316 return None
317 return rounded if rounded >= 0 else None
320def _uuid(value: str | UUID | None) -> UUID | None:
321 """UUID form of ``value``, or None when it is absent or malformed."""
322 if value is None:
323 return None
324 if isinstance(value, UUID):
325 return value
326 try:
327 return UUID(str(value))
328 except (ValueError, AttributeError, TypeError):
329 return None
332def _coerce_scope(scope_type: RuleEnum.Scope | str | None) -> RuleEnum.Scope:
333 """Map a scope-type string to the enum, defaulting to global."""
334 if isinstance(scope_type, RuleEnum.Scope):
335 return scope_type
336 return scope_registry.coerce_scope(scope_type) or RuleEnum.Scope.global_
339def _coerce_outcome(value: UsageEnum.Outcome | str | None) -> UsageEnum.Outcome:
340 """Map an outcome string to the enum, defaulting to ``ok``.
342 Defaulting to success rather than failure is the conservative direction
343 here: an unrecognised value landing on ``error`` would quietly remove the
344 row from every quota window, which is the one thing a caller that wrote
345 garbage should not be able to do.
346 """
347 if isinstance(value, UsageEnum.Outcome):
348 return value
349 if value is None:
350 return UsageEnum.Outcome.ok
351 try:
352 return UsageEnum.Outcome(str(value))
353 except ValueError:
354 logger.warning("Unknown usage outcome %r; recording it as ok", value)
355 return UsageEnum.Outcome.ok
358@dataclass(frozen=True)
359class Span:
360 """Which ledger rows a quota counts.
362 ``seconds`` is a trailing window (``rolling``); ``since`` a calendar
363 period's start, for a budget (``rules/periods.py``). ``member`` narrows a
364 shared allowance to the invoker's own rows — a budget for each member of
365 an organisation rather than one between them. ``execution_types``
366 narrows it to some kinds of work (``UsageEnum.ExecutionType``) — a
367 budget for evaluations alone. Frozen, so a window can memoise by it.
368 """
370 seconds: int | None = None
371 since: datetime | None = None
372 member: bool = False
373 execution_types: tuple[str, ...] = ()
374 #: Rows before this only — a period already over (last month), for a
375 #: budget's previous period. None counts up to now.
376 until: datetime | None = None
378 def start(self) -> datetime:
379 """The earliest row counted."""
380 if self.since is not None:
381 return self.since
382 return aware_utcnow() - timedelta(seconds=max(1, int(self.seconds or 1)))
385class UsageWindow:
386 """Ledger totals for one owner, optionally narrowed to a scope.
388 Constructed once per rule evaluation and handed to the actions through the
389 evaluation context. Results are memoised per :class:`Span` because several
390 rules commonly share one — three rules capping the same hour should cost
391 one query, not three — and because the totals must not move between two
392 actions evaluating within the same request.
394 Both readers return None when the ledger cannot be queried. Actions treat
395 that as "cannot judge" and stand aside rather than blocking: refusing a
396 request on a number the engine failed to obtain is a worse failure than
397 letting it through and logging.
398 """
400 def __init__(
401 self,
402 db: Session,
403 owner_user_id: str,
404 scope_type: RuleEnum.Scope | None = None,
405 scope_id: str | None = None,
406 *,
407 population: tuple[str, str] | None = None,
408 ) -> None:
409 self._db = db
410 self._owner_user_id = owner_user_id
411 #: Whose traffic counts: ``("user", id)`` by default, or the
412 #: organisation or project that owns the rule being judged.
413 self._population = population or ("user", owner_user_id)
414 self._scope_type = scope_type
415 self._scope_id = scope_id
416 self._invocations: dict[Span, int | None] = {}
417 self._cost: dict[Span, Decimal | None] = {}
419 # -- internals -------------------------------------------------------
421 def _base_query(self, column: Any, span: Span, *, paid: bool = False):
422 """``span``'s query for ``column``, which may be a tuple of aggregates
423 when a caller needs more than one figure in one round trip.
425 ``paid`` widens it from the work that came back to everything that
426 was paid for — what a cost reader counts.
427 """
428 kind, owner_id = self._population
429 columns = column if isinstance(column, tuple) else (column,)
430 clauses = [
431 # A personal rule counts its owner's own traffic; an
432 # organisation's or project's rule counts every member's traffic
433 # on what it owns, so its quota is the team's, not each person's.
434 _POPULATION_COLUMN[kind] == _uuid(owner_id),
435 GovernanceUsage.occurred_at >= span.start(),
436 ]
437 if span.until is not None:
438 clauses.append(GovernanceUsage.occurred_at < span.until)
439 if not paid:
440 # A count or a latency is of work the user actually received. The
441 # ledger also records failed attempts — a dashboard needs them to
442 # produce an error rate — but letting a provider outage consume
443 # somebody's hourly allowance would be refusing a request on a
444 # number that was never real. Spend is different: a turn that
445 # failed after its first calls was billed for them, and a cost
446 # reader asks for ``paid`` to count it.
447 clauses.append(GovernanceUsage.outcome == UsageEnum.Outcome.ok)
448 if span.member:
449 # A budget for each member: the invoker's own rows within the
450 # rule's population.
451 clauses.append(GovernanceUsage.owner_user_id == _uuid(self._owner_user_id))
452 if span.execution_types:
453 clauses.append(GovernanceUsage.execution_type.in_(span.execution_types))
454 query = self._db.query(*columns).filter(*clauses)
455 # A scoped rule counts only its own scope's invocations: a per-agent
456 # limit must not be consumed by a different agent's traffic. A global
457 # rule counts everything, which is what makes it global. *How* each
458 # scope narrows is the scope's own business — an organisation counts
459 # by owner attribution, an agent by the resource that ran — so this
460 # asks the registry rather than branching on the type it was handed.
461 scope = scope_registry.get_scope(self._scope_type)
462 if scope is not None:
463 for clause in scope.usage_filter(_uuid(self._scope_id)):
464 query = query.filter(clause)
465 return query
467 # -- readers ---------------------------------------------------------
469 def invocations(self, seconds: int) -> int | None:
470 """How many invocations were recorded in the trailing window."""
471 return self.count(Span(seconds=max(1, int(seconds))))
473 def count(self, span: Span) -> int | None:
474 """How many invocations ``span`` holds that came back."""
475 if span not in self._invocations:
476 try:
477 self._invocations[span] = (
478 self._base_query(func.count(GovernanceUsage.id), span).scalar() or 0
479 )
480 except SQLAlchemyError:
481 logger.exception(
482 "Rate-limit lookup failed — the rule will not be enforced "
483 "for this invocation"
484 )
485 self._invocations[span] = None
486 return self._invocations[span]
488 def cost_usd(self, seconds: int) -> Decimal | None:
489 """What the invocations in the trailing window cost, as a limit
490 counts it: every row that was paid for — failed attempts included,
491 since a call made before the failure was billed — at its measured
492 cost, plus the high estimate for its unpriced calls
493 (``unpriced_estimate_usd``), so a model nobody has priced cannot
494 spend round a cap. Rows from before that column count their unpriced
495 calls as nothing."""
496 return self.spent(Span(seconds=max(1, int(seconds))))
498 def spent(self, span: Span) -> Decimal | None:
499 """What ``span``'s invocations cost, as :meth:`cost_usd` counts it."""
500 if span not in self._cost:
501 try:
502 total = self._base_query(
503 func.sum(
504 func.coalesce(GovernanceUsage.estimated_cost_usd, 0)
505 + func.coalesce(GovernanceUsage.unpriced_estimate_usd, 0)
506 ),
507 span,
508 paid=True,
509 ).scalar()
510 self._cost[span] = _decimal(total) or Decimal(0)
511 except SQLAlchemyError:
512 logger.exception(
513 "Cost-cap lookup failed — the rule will not be enforced "
514 "for this invocation"
515 )
516 self._cost[span] = None
517 return self._cost[span]
519 # -- what a budget's reader is shown ---------------------------------
520 #
521 # Each reads the rows :meth:`spent` counts — the same population, scope,
522 # span and paid rows — so a budget's page and the cap deciding the next
523 # turn can never be reading two different numbers.
525 def _spend_sum(self):
526 return func.sum(
527 func.coalesce(GovernanceUsage.estimated_cost_usd, 0)
528 + func.coalesce(GovernanceUsage.unpriced_estimate_usd, 0)
529 )
531 def daily_spent(self, span: Span) -> dict[date, Decimal] | None:
532 """``span``'s spend by UTC day, as :meth:`spent` counts it: days with
533 no row are absent. None when the ledger cannot be read."""
534 day = cast(GovernanceUsage.occurred_at, Date)
535 try:
536 rows = (
537 self._base_query((day, self._spend_sum()), span, paid=True)
538 .group_by(day)
539 .all()
540 )
541 except SQLAlchemyError:
542 logger.exception("Daily spend lookup failed")
543 return None
544 return {d: _decimal(total) or Decimal(0) for d, total in rows}
546 def spent_by_member(self, span: Span) -> dict[UUID, Decimal] | None:
547 """``span``'s spend split by who caused it. For a reviewer's eyes
548 only: it is what each colleague spent."""
549 try:
550 rows = (
551 self._base_query(
552 (GovernanceUsage.owner_user_id, self._spend_sum()), span, paid=True
553 )
554 .group_by(GovernanceUsage.owner_user_id)
555 .all()
556 )
557 except SQLAlchemyError:
558 logger.exception("Spend-by-member lookup failed")
559 return None
560 return {user: _decimal(total) or Decimal(0) for user, total in rows}
562 def first_spent_at(self, span: Span) -> datetime | None:
563 """When ``span``'s population first spent anything — how much
564 history a forecast has to go on. None with none, or unreadable."""
565 try:
566 return self._base_query(
567 func.min(GovernanceUsage.occurred_at), span, paid=True
568 ).scalar()
569 except SQLAlchemyError:
570 logger.exception("First-spend lookup failed")
571 return None
574@dataclass(frozen=True)
575class TurnCost:
576 """What one governed turn cost: its ledger rows summed."""
578 #: None when nothing in it could be priced — never 0 for "unknown".
579 cost_usd: Decimal | None
580 #: Calls in it svc-ai could not price: ``cost_usd`` is then a floor.
581 unpriced_calls: int
584def turn_costs(db: Session, invocation_ids: Any) -> dict[UUID, TurnCost]:
585 """What each of ``invocation_ids``' turns cost, by the id its ledger
586 rows carry — a failed or stopped turn's paid calls included, since they
587 were billed. One grouped query; a turn with no row (a block, or one from
588 before turns were named) is simply absent."""
589 ids = [i for i in dict.fromkeys(_uuid(i) for i in invocation_ids or []) if i]
590 if not ids:
591 return {}
592 rows = (
593 db.query(
594 GovernanceUsage.invocation_id,
595 func.sum(GovernanceUsage.estimated_cost_usd),
596 func.coalesce(func.sum(GovernanceUsage.unpriced_calls), 0),
597 )
598 .filter(GovernanceUsage.invocation_id.in_(ids))
599 .group_by(GovernanceUsage.invocation_id)
600 .all()
601 )
602 return {
603 row[0]: TurnCost(cost_usd=_decimal(row[1]), unpriced_calls=int(row[2] or 0))
604 for row in rows
605 }
608def turn_cost_fields(db: Session, invocation_id: Any) -> dict[str, Any]:
609 """``cost_usd`` / ``unpriced_calls`` for one turn, as an answer is served
610 with them — read back from the ledger once its rows are committed, so a
611 live answer shows the figure a reload will. Never raises: a figure is
612 worth less than the answer it rides on."""
613 try:
614 cost = turn_costs(db, [invocation_id]).get(_uuid(invocation_id))
615 except SQLAlchemyError:
616 logger.warning("Could not read turn %s's cost", invocation_id, exc_info=True)
617 cost = None
618 if cost is None:
619 return {"cost_usd": None, "unpriced_calls": 0}
620 return {
621 "cost_usd": float(cost.cost_usd) if cost.cost_usd is not None else None,
622 "unpriced_calls": cost.unpriced_calls,
623 }
626# ── What a turn here usually costs ───────────────────────────────────────────
627#
628# A cost cap with room left lets a turn start, and svc-ai stops the turn once
629# it has spent what was left (``X-Spend-Limit``). A turn that starts with a
630# few cents left is then cut off mid-answer: paid for, and of no use. So a cap
631# keeps room to finish (its ``reserve``): a turn starts only when what is left
632# covers what a turn like it usually costs — read from the ledger, as the
633# recent turns of the same resource and kind of work in the same workspace.
635#: A turn's reserve when its resource has too little history to say: about
636#: an agent turn (triage, the answer, the quality check) on a mid-priced model.
637DEFAULT_TURN_RESERVE_USD = Decimal("0.05")
638#: The most recent turns a reserve reads, and the fewest it trusts.
639RESERVE_TURNS = 50
640RESERVE_MIN_TURNS = 5
641#: The share of those turns a reserve covers: most, not the outliers.
642RESERVE_PERCENTILE = 0.9
645@dataclass(frozen=True)
646class TurnReserve:
647 """What a turn is expected to cost, and how that was decided."""
649 usd: Decimal
650 #: ``typical`` — read from this resource's recent turns — or ``default``
651 #: (``DEFAULT_TURN_RESERVE_USD``) when it has too few.
652 basis: str
653 #: How many turns ``typical`` read.
654 turns: int = 0
657def _percentile(values: list[Decimal], share: float) -> Decimal:
658 """Nearest-rank percentile of ``values`` (non-empty)."""
659 ordered = sorted(values)
660 rank = max(1, -(-int(share * 100) * len(ordered) // 100))
661 return ordered[min(rank, len(ordered)) - 1]
664def typical_turn_cost(
665 db: Session,
666 *,
667 scope_type: RuleEnum.Scope | str | None,
668 scope_id: str | UUID | None,
669 execution_type: str | None = None,
670 where: Any = None,
671) -> TurnReserve:
672 """What a turn of ``scope_type`` / ``scope_id`` (an agent, a model, a
673 skill) usually costs: the ``RESERVE_PERCENTILE`` of its newest
674 ``RESERVE_TURNS`` paid turns, each its ledger rows summed by turn as a
675 cap counts them (measured, plus the high estimate for unpriced calls).
676 No ``scope_type`` reads any resource's turns — a workspace's typical
677 turn, for a budget's page.
679 ``execution_type`` narrows to one kind of work (an agent's chat turns
680 are not its evaluation cells) and ``where`` to the rows of one workspace
681 (``Workspace.stamped``). With fewer than ``RESERVE_MIN_TURNS`` turns, or
682 when the ledger cannot be read, the default. Computed in Python, so the
683 percentile is the same on every database.
684 """
685 default = TurnReserve(usd=DEFAULT_TURN_RESERVE_USD, basis="default")
686 clauses = [GovernanceUsage.invocation_id.isnot(None)]
687 if scope_type is not None:
688 scope = scope_registry.coerce_scope(scope_type, default=None)
689 ident = _uuid(scope_id)
690 if scope is None or ident is None:
691 return default
692 clauses += [
693 GovernanceUsage.scope_type == scope,
694 GovernanceUsage.scope_id == ident,
695 ]
696 total = func.sum(
697 func.coalesce(GovernanceUsage.estimated_cost_usd, 0)
698 + func.coalesce(GovernanceUsage.unpriced_estimate_usd, 0)
699 )
700 if execution_type:
701 clauses.append(GovernanceUsage.execution_type == str(execution_type))
702 if where is not None:
703 clauses.append(where)
704 try:
705 rows = (
706 db.query(GovernanceUsage.invocation_id, total)
707 .filter(*clauses)
708 .group_by(GovernanceUsage.invocation_id)
709 .order_by(func.max(GovernanceUsage.occurred_at).desc())
710 .limit(RESERVE_TURNS)
711 .all()
712 )
713 except SQLAlchemyError:
714 logger.warning("Typical turn cost lookup failed", exc_info=True)
715 return default
716 costs = [_decimal(cost) or Decimal(0) for _, cost in rows]
717 if len(costs) < RESERVE_MIN_TURNS:
718 return default
719 return TurnReserve(
720 usd=_percentile(costs, RESERVE_PERCENTILE), basis="typical", turns=len(costs)
721 )
724class TurnReserveLookup:
725 """The rule engine's lazy, cached :func:`typical_turn_cost` for the
726 invocation it is evaluating — read once, and only if a cost cap with
727 room left asks."""
729 def __init__(
730 self,
731 db: Session,
732 *,
733 scope_type: Any,
734 scope_id: Any,
735 execution_type: str | None,
736 where: Any = None,
737 ) -> None:
738 self._args = {
739 "scope_type": scope_type,
740 "scope_id": scope_id,
741 "execution_type": execution_type,
742 "where": where,
743 }
744 self._db = db
745 self._found: TurnReserve | None = None
747 def reserve(self) -> TurnReserve:
748 if self._found is None:
749 self._found = typical_turn_cost(self._db, **self._args)
750 return self._found
753_POPULATION_COLUMN = {
754 "user": GovernanceUsage.owner_user_id,
755 "organisation": GovernanceUsage.owner_organisation_id,
756 "project": GovernanceUsage.owner_project_id,
757 "workspace_user": GovernanceUsage.workspace_user_id,
758}
761def rule_population(rule: Any, owner_user_id: str) -> tuple[str, str]:
762 """Whose traffic a rule's quota counts: the workspace that owns the rule,
763 with its projects (``workspace.ledger_stamp``) — so an organisation's
764 cost cap is one budget for the organisation and every project in it, a
765 project's counts the project, and a person's counts their personal
766 workspace and personal projects, whoever is invoking there. Not the
767 invoker's own traffic everywhere: a rule governs where it lives."""
768 if getattr(rule, "owner_organisation_id", None):
769 return ("organisation", str(rule.owner_organisation_id))
770 if getattr(rule, "owner_project_id", None):
771 return ("project", str(rule.owner_project_id))
772 if getattr(rule, "owner_user_id", None):
773 return ("workspace_user", str(rule.owner_user_id))
774 return ("user", owner_user_id)
777class UsageWindows:
778 """A per-rule-scope cache of :class:`UsageWindow`.
780 One evaluation now considers rules at several scopes at once — a global
781 cap, the project's, and one pinned to a single agent can all match the
782 same invocation — and each counts a different population. Handing every
783 rule the invocation's own scope would have let an agent's traffic be
784 judged against a window that counted the whole account, or the reverse.
786 A window is created per distinct rule scope and reused, so three rules
787 capping the same agent still cost one set of queries, and two actions
788 evaluating within one request cannot see different totals.
789 """
791 def __init__(self, db: Session, owner_user_id: str) -> None:
792 self._db = db
793 self._owner_user_id = owner_user_id
794 self._windows: dict[tuple, UsageWindow] = {}
796 def for_rule(self, rule: Any) -> UsageWindow:
797 """The window counting what ``rule``'s own scope covers, across the
798 population its owner governs."""
799 scope = scope_registry.coerce_scope(getattr(rule, "scope_type", None))
800 scope_id = getattr(rule, "scope_id", None)
801 return self.for_scope(
802 scope,
803 str(scope_id) if scope_id else None,
804 population=rule_population(rule, self._owner_user_id),
805 )
807 def for_scope(
808 self,
809 scope_type: RuleEnum.Scope | str | None,
810 scope_id: str | None = None,
811 *,
812 population: tuple[str, str] | None = None,
813 ) -> UsageWindow:
814 resolved = scope_registry.coerce_scope(scope_type) or RuleEnum.Scope.global_
815 population = population or ("user", self._owner_user_id)
816 key = (resolved, scope_id, population)
817 if key not in self._windows:
818 self._windows[key] = UsageWindow(
819 self._db,
820 self._owner_user_id,
821 resolved,
822 scope_id,
823 population=population,
824 )
825 return self._windows[key]
828def record_measured(
829 db: Session,
830 *,
831 owner_user_id: str | UUID | None,
832 execution_type: str,
833 source_type: UsageEnum.Source | str,
834 source_id: str | UUID | None,
835 measured: Any,
836 owner_project_id: str | UUID | None = None,
837 owner_organisation_id: str | UUID | None = None,
838 failed: bool = False,
839 latency_ms: float | None = None,
840 workspace: Any = None,
841) -> GovernanceUsage | None:
842 """Ledger what svc-ai measured for a call with no governed scope.
844 The paths that are not a governed invocation of one agent or model —
845 generation flows, retrieval, embeddings, simulations, the optimiser —
846 still spend money, and a cost cap written at global scope has to count
847 it. Writes nothing when svc-ai metered nothing: no model was called, so
848 there is nothing to count. Does not commit, and never raises.
850 ``owner_user_id`` is the person who caused it. Work no person started —
851 a scheduled crawl of an organisation's or a project's source — has none,
852 and is written with its workspace's stamp alone (migration 99): its
853 workspace's budgets count it, and it is no member's own spend. With
854 neither a person nor a workspace it is the platform's own work (the
855 CHAINR Bot guide, the built-in News repository), which no workspace pays
856 for, and nothing is written.
857 """
858 if not getattr(measured, "measured", False):
859 return None
860 if not owner_user_id and workspace is None:
861 if not (owner_project_id or owner_organisation_id):
862 return None
863 return record_usage(
864 db,
865 owner_user_id=owner_user_id,
866 execution_type=execution_type,
867 owner_project_id=owner_project_id,
868 owner_organisation_id=owner_organisation_id,
869 workspace=workspace,
870 latency_ms=latency_ms,
871 outcome=UsageEnum.Outcome.error if failed else UsageEnum.Outcome.ok,
872 source_type=source_type,
873 source_id=source_id,
874 measured=measured,
875 )