Coverage for app / services / budgets / gate.py: 93%
46 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"""
2Budgets for work that is not a turn (cost-control plan A1.5).
4A turn — a chat answer, a skill run, an evaluation cell, a dashboard tile —
5meets its workspace's policy rules before it starts, a used-up budget among
6them, and what is left of the tightest becomes the turn's spend limit (A1.4).
7Everything else that reaches a model was counted by every budget and stopped
8by none (Known gap 20): a generation flow, a search of a knowledge base, the
9indexing of an upload, a website crawl, a simulation. :func:`check` is their
10gate, and every one of those paths calls it before its svc-ai call
11(``services/llm_paths.py`` ``gated_in``, held by ``tests/test_llm_paths.py``).
13It asks one question — is a budget governing this workspace used up for this
14kind of work? — of the same cost caps and the same platform allowance a turn
15meets (``rule_engine.evaluate_budgets``). A budget that is used up refuses
16with :class:`BudgetReached`, which every route answers as a 403 naming the
17budget and when it starts again (``code: "budget"``, ``main.py``); one with
18something left returns it, for the call's ``ai_client.in_spend_limit``, so
19svc-ai stops the work there.
21A budget whose ledger cannot be read is not judged — the rule engine's quota
22actions fail open the same way, since refusing work on a number that was
23never read would be the wrong trade.
24"""
26from __future__ import annotations
28import logging
29from typing import Any
30from uuid import UUID
32from sqlalchemy.orm import Session
34from app.services import rule_engine
35from app.services.workspace import Workspace
37logger = logging.getLogger(__name__)
40class BudgetReached(Exception):
41 """A budget governing the work's workspace is used up."""
43 code = "budget"
45 def __init__(
46 self,
47 rule_name: str,
48 message: str,
49 *,
50 resets_at: str | None = None,
51 rule_id: str | None = None,
52 ) -> None:
53 super().__init__(message)
54 self.rule_name = rule_name
55 self.message = message
56 self.resets_at = resets_at
57 self.rule_id = rule_id
59 @classmethod
60 def from_block(cls, block: rule_engine.BudgetBlock) -> "BudgetReached":
61 return cls(
62 block.rule_name,
63 block.message,
64 resets_at=block.resets_at,
65 rule_id=block.rule_id,
66 )
68 @classmethod
69 def from_stop(cls, exc: Any) -> "BudgetReached":
70 """svc-ai stopping the work at the limit it was given
71 (``ai_client.SpendLimitReached``): what was left was spent."""
72 from app.services.rules import actions as action_registry
74 limit = getattr(exc, "limit", None)
75 if limit is None:
76 return cls("A budget", getattr(exc, "user_message", None) or str(exc))
77 what = (
78 "this workspace's monthly platform allowance"
79 if limit.kind == "platform"
80 else f"the budget “{limit.rule_name}”"
81 )
82 figures = {"resets_at": limit.resets_at} if limit.resets_at else {}
83 return cls(
84 limit.rule_name,
85 f"Stopped at what was left of {what} "
86 f"({action_registry.usd_text(limit.usd)}). "
87 f"{action_registry.resets_phrase(figures)}",
88 resets_at=limit.resets_at,
89 rule_id=limit.rule_id,
90 )
92 def detail(self) -> dict[str, Any]:
93 """The 403's body: the same shape as a blocked prompt's, with the
94 code a client tells it apart by and when the budget starts again."""
95 return {
96 "rule": self.rule_name,
97 "message": self.message,
98 "code": self.code,
99 "resets_at": self.resets_at,
100 }
103def check(
104 db: Session,
105 *,
106 ws: Workspace,
107 actor_user_id: UUID | str | None,
108 execution_type: str,
109 scope_type: str | None = None,
110 scope_id: UUID | str | None = None,
111) -> rule_engine.SpendLimit | None:
112 """Whether ``ws``'s budgets let ``execution_type`` work start, and how
113 much it may spend. ``actor_user_id`` is the person whose work it is, or
114 None for work no person started (a scheduled crawl).
116 Returns the tightest amount left, or None when no budget governs it.
117 Raises :class:`BudgetReached` when one is used up, after committing the
118 refusal's activity row (a person's work only): a refusal is the event
119 the log least tolerates losing, so call it before writing anything the
120 refusal should roll back.
121 """
122 actor = str(actor_user_id) if actor_user_id else None
123 context: dict[str, Any] = {
124 "execution_type": execution_type,
125 "user_id": actor,
126 "scope_type": scope_type,
127 "scope_id": str(scope_id) if scope_id else None,
128 rule_engine.WORKSPACE_CONTEXT_KEY: ws.key,
129 rule_engine.INVOCATION_CONTEXT_KEY: rule_engine.new_invocation_id(),
130 }
131 try:
132 return rule_engine.evaluate_budgets(db, context, actor)
133 except rule_engine.BudgetBlock as block:
134 if actor is not None:
135 try:
136 db.commit()
137 except Exception: # noqa: BLE001 — the refusal still stands
138 db.rollback()
139 logger.exception("Could not record a budget refusal")
140 raise BudgetReached.from_block(block) from block
141 except Exception: # noqa: BLE001 — an unreadable budget is not judged
142 logger.exception(
143 "Budget check failed for %s work in %s — letting it through",
144 execution_type,
145 ws.key,
146 )
147 return None