Coverage for app / services / budgets / allowance.py: 97%

66 statements  

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

1""" 

2Platform allowances — CHAIN-R's own monthly cap on each workspace's spend 

3(cost-control plan, A1.4). 

4 

5A workspace's budgets are its own: cost caps its people write, raise or 

6remove. An allowance is the platform's — what the deployment lets each 

7workspace spend on models in a calendar month (UTC), whatever its budgets 

8say — so a workspace cannot spend the company's money without limit. There 

9is one amount for each kind of workspace, set in the deployment's settings: 

10 

11``PLATFORM_ALLOWANCE_PERSONAL_USD`` 

12 Each person's Personal workspace, with their personal projects. 

13``PLATFORM_ALLOWANCE_ORGANISATION_USD`` 

14 Each organisation, with every project in it: one allowance for the lot. 

15 

16**Unset is off.** Unlike svc-ai's spending ceiling, whose missing setting is 

17a fail-safe default, an allowance is a commercial term, and none applies 

18until an amount is chosen (the user's decision, October 2026). ``off`` / 

19``none`` also mean none, since SSM cannot store an empty string. 

20 

21An allowance is enforced exactly as a cost cap is: the same reading 

22(``CostCapAction.reading`` over the ledger), the same room to finish a turn 

23(``reserve``), and the same limit on what a turn may spend (``X-Spend-Limit``). 

24The rule engine checks it first, records it in the activity log as "Platform 

25allowance" (no rule id: nobody wrote it), and the Spend tab shows it beside 

26the workspace's budgets, where nobody can edit it. 

27""" 

28 

29from __future__ import annotations 

30 

31import logging 

32from dataclasses import dataclass 

33from decimal import Decimal, InvalidOperation 

34from typing import Any 

35 

36from app.common.settings import get_settings 

37from app.services import workspace as workspace_service 

38from app.services.rules import actions as action_registry 

39 

40logger = logging.getLogger(__name__) 

41 

42#: How the activity log, the Spend tab and a refusal name it. 

43NAME = "Platform allowance" 

44 

45#: The values that mean "no allowance", besides an empty one. 

46OFF_VALUES = frozenset({"off", "none", "disabled", "change_me"}) 

47 

48 

49def parse_amount(raw: Any) -> Decimal | None: 

50 """An allowance in USD, or None for none: unset, ``off``, or anything 

51 that is not an amount of at least zero (logged).""" 

52 text = str(raw or "").strip() 

53 if not text or text.lower() in OFF_VALUES: 

54 return None 

55 try: 

56 amount = Decimal(text) 

57 except (InvalidOperation, ValueError): 

58 logger.error("[allowance] unreadable amount %r — no allowance applies", raw) 

59 return None 

60 if not amount.is_finite() or amount < 0: 

61 logger.error("[allowance] invalid amount %r — no allowance applies", raw) 

62 return None 

63 return amount 

64 

65 

66@dataclass(frozen=True) 

67class Allowance: 

68 """One workspace's platform allowance.""" 

69 

70 amount: Decimal 

71 #: The workspace it belongs to: a Personal workspace or an organisation. 

72 #: A project's is its parent's. 

73 holder: workspace_service.Workspace 

74 

75 @property 

76 def population(self) -> tuple[str, str]: 

77 """The ledger rows it counts (``usage.UsageWindow``): the holder's 

78 own and its projects'.""" 

79 if self.holder.kind is workspace_service.WorkspaceKind.organisation: 

80 return ("organisation", str(self.holder.id)) 

81 return ("workspace_user", str(self.holder.id)) 

82 

83 @property 

84 def scope(self) -> tuple[str | None, str | None]: 

85 """How the activity log scopes it: the organisation, or nothing for 

86 a person's own.""" 

87 if self.holder.kind is workspace_service.WorkspaceKind.organisation: 

88 return ("organisation", str(self.holder.id)) 

89 return (None, None) 

90 

91 def config(self) -> dict[str, Any]: 

92 """The cost cap it is enforced as.""" 

93 return { 

94 "type": action_registry.CostCapAction.type, 

95 "max_usd": str(self.amount), 

96 "period": "month", 

97 "share": action_registry.QuotaShare.shared.value, 

98 "on_reach": action_registry.QuotaResponse.block.value, 

99 "reserve": action_registry.QuotaReserve.typical.value, 

100 } 

101 

102 def ref(self) -> dict[str, Any]: 

103 """Its identity on an activity row: named, with no rule behind it.""" 

104 scope_type, scope_id = self.scope 

105 return { 

106 "rule": NAME, 

107 "rule_id": None, 

108 "rule_version": None, 

109 "scope_type": scope_type, 

110 "scope_id": scope_id, 

111 } 

112 

113 

114def holder_of( 

115 ws: workspace_service.Workspace | None, 

116) -> workspace_service.Workspace | None: 

117 """Whose allowance work in ``ws`` counts against: its own, or for a 

118 project its parent's.""" 

119 if ws is None: 

120 return None 

121 if ws.kind is workspace_service.WorkspaceKind.project: 

122 return ws.parent 

123 return ws 

124 

125 

126def for_workspace(ws: workspace_service.Workspace | None) -> Allowance | None: 

127 """The allowance work in ``ws`` counts against, or None when the 

128 deployment sets none for its kind.""" 

129 holder = holder_of(ws) 

130 if holder is None: 

131 return None 

132 settings = get_settings() 

133 raw = ( 

134 settings.PLATFORM_ALLOWANCE_ORGANISATION_USD 

135 if holder.kind is workspace_service.WorkspaceKind.organisation 

136 else settings.PLATFORM_ALLOWANCE_PERSONAL_USD 

137 ) 

138 amount = parse_amount(raw) 

139 return Allowance(amount=amount, holder=holder) if amount is not None else None 

140 

141 

142def refusal(figures: dict[str, Any]) -> str: 

143 """What a person is told when the allowance refuses a turn, from its cost 

144 cap event: used up, or too little left to finish one.""" 

145 resets = action_registry.resets_phrase(figures) 

146 if figures.get("reserve_usd") is not None: 

147 left = Decimal(str(figures.get("remaining_usd") or 0)) 

148 reserve = Decimal(str(figures["reserve_usd"])) 

149 return ( 

150 "Not enough of this workspace's monthly platform allowance is left " 

151 f"to finish an answer: {action_registry.usd_text(left)} left, and a " 

152 f"turn here usually costs about {action_registry.usd_text(reserve)}. " 

153 f"{resets}" 

154 ) 

155 cap = figures.get("cap_usd") 

156 amount = f" ({action_registry.usd_text(Decimal(str(cap)))})" if cap else "" 

157 return f"This workspace has used its monthly platform allowance{amount}. {resets}"