Coverage for app / services / spend_limits.py: 79%

39 statements  

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

1""" 

2A turn's spend limit — svc-core's half (cost-control plan, A1.4). 

3 

4A cost cap is judged before a turn starts. One that lets the turn through has 

5an amount left, and so does the platform allowance; the rule engine returns 

6the tightest as ``RulePass.spend_limit``. Every path that governs a turn sets 

7it around the turn's svc-ai calls (``ai_client.in_spend_limit`` / 

8``use_spend_limit``), svc-ai stops the turn's next model call once the turn 

9has spent it, and the refusal comes back as ``ai_client.SpendLimitReached``, 

10whose message names the budget. The path then stores the turn with that 

11message and what it spent, like any refused turn, and records the stop 

12(:func:`record_stop`). 

13 

14A turn in several parts — a run that paused for a person — re-checks its 

15policy rules on the answer, but its ledger row is written only when it ends, 

16so the ledger does not yet hold what its earlier parts spent: a later part's 

17limit is that much less (:func:`for_resume`). Nothing left, and the resume is 

18refused (:func:`exhausted`). 

19 

20A turn's web sources travel beside its limit (``ai_client.in_turn_governance``): 

21the Tools rules' policy, tightened the same way on a resume 

22(:func:`web_for_resume`). 

23 

24``tests/test_turn_spend_limit.py`` pins that every path calling 

25``rule_engine.evaluate_input`` passes on what it returns. 

26""" 

27 

28from __future__ import annotations 

29 

30import logging 

31from decimal import Decimal 

32from typing import Any 

33 

34from sqlalchemy.orm import Session 

35 

36from app.services import ai_client 

37from app.services import governance_activity as activity_service 

38from app.services import rule_engine 

39from app.util import web_domains 

40 

41logger = logging.getLogger(__name__) 

42 

43 

44def for_resume( 

45 first: rule_engine.SpendLimit | None, 

46 rechecked: rule_engine.SpendLimit | None, 

47 spent: ai_client.UsageCapture | Decimal | None, 

48) -> rule_engine.SpendLimit | None: 

49 """The limit for a later part of a turn: the one its rules gave on the 

50 re-check (fresher), else the turn's first, less what the turn has spent 

51 so far.""" 

52 limit = rechecked or first 

53 if limit is None: 

54 return None 

55 if isinstance(spent, ai_client.UsageCapture): 

56 spent = spent.enforcement_usd() 

57 return limit.after(spent) 

58 

59 

60def web_for_resume( 

61 first: web_domains.WebPolicy | None, 

62 rechecked: web_domains.WebPolicy | None, 

63) -> web_domains.WebPolicy | None: 

64 """The web sources for a later part of a turn: what both the turn's 

65 first part and the re-check allow. A source a rule trusted only while the 

66 turn waited is not opened to it, and one a new rule blocks is closed — 

67 the tightest of the two, never the looser.""" 

68 if first is None: 

69 return rechecked 

70 return first.merge(rechecked) 

71 

72 

73def exhausted(limit: rule_engine.SpendLimit | None) -> bool: 

74 """Whether ``limit`` leaves the turn nothing to spend.""" 

75 return limit is not None and limit.usd <= 0 

76 

77 

78def exhausted_error(limit: rule_engine.SpendLimit) -> ai_client.SpendLimitReached: 

79 """The refusal of a resume the turn has no budget left for — the same 

80 error, and so the same handling, as svc-ai stopping it.""" 

81 return ai_client.SpendLimitReached(limit.stop_message(), limit=limit) 

82 

83 

84def record_stop( 

85 exc: BaseException, 

86 context: dict[str, Any], 

87 owner_user_id: str, 

88 *, 

89 db: Session | None = None, 

90) -> None: 

91 """Record that a budget stopped a turn part-way (``SpendLimitReached``): 

92 one activity row, beside the input row that let the turn start. With 

93 ``db``, added to the caller's transaction; without, written and committed 

94 in a session of its own. Never raises; does nothing for another error.""" 

95 if not isinstance(exc, ai_client.SpendLimitReached) or exc.limit is None: 

96 return 

97 if db is not None: 

98 rule_engine.record_turn_stop( 

99 db, exc.limit, context, owner_user_id, spent_usd=exc.spent_usd 

100 ) 

101 return 

102 from app.db.postgres.engine import SessionLocal 

103 

104 session = SessionLocal() 

105 try: 

106 rule_engine.record_turn_stop( 

107 session, exc.limit, context, owner_user_id, spent_usd=exc.spent_usd 

108 ) 

109 activity_service.commit(session) 

110 except Exception: 

111 logger.exception("Could not record a turn stopped at its spend limit") 

112 finally: 

113 session.close()