Coverage for app / common / spend_limit.py: 100%

21 statements  

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

1"""The most a request's model calls may spend — the turn's share of a budget. 

2 

3svc-core checks every cost cap that governs a turn before it starts, and a 

4cap that lets it through has an amount left. Without more, a long run — a 

5skill graph, a tool loop, a revision — could spend past it, and the cap would 

6only notice on the next turn. So svc-core sends the tightest amount left 

7(``X-Spend-Limit``, USD as a decimal string) on every call the turn makes, 

8and the meter refuses the request's next model call once the request has 

9spent it (``metering.check_limits``), with ``TurnSpendLimitReached``. 

10 

11A request with no header has no limit of its own: ungoverned work (the 

12platform benchmark, built-in tiles, crawls) is held only by the deployment's 

13spending ceiling (``spend_guard``). 

14""" 

15 

16from __future__ import annotations 

17 

18from contextvars import ContextVar, Token 

19from decimal import Decimal, InvalidOperation 

20 

21HEADER = "X-Spend-Limit" 

22 

23_CURRENT: ContextVar[Decimal | None] = ContextVar("svc_core_spend_limit", default=None) 

24 

25 

26def parse(raw: str | None) -> Decimal | None: 

27 """The limit svc-core sent, or None for anything that is not a finite 

28 amount of at least zero — no limit rather than a guessed one. Zero is a 

29 limit: nothing may be spent.""" 

30 if not raw: 

31 return None 

32 try: 

33 value = Decimal(raw.strip()) 

34 except (InvalidOperation, ValueError): 

35 return None 

36 if not value.is_finite() or value < 0: 

37 return None 

38 return value 

39 

40 

41def current() -> Decimal | None: 

42 """The current request's limit, if svc-core sent one.""" 

43 return _CURRENT.get() 

44 

45 

46def set_current(raw: str | None) -> Token: 

47 return _CURRENT.set(parse(raw)) 

48 

49 

50def reset(token: Token) -> None: 

51 _CURRENT.reset(token)