Coverage for app / services / swarms / budget.py: 93%

114 statements  

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

1"""A swarm run's money and time: what each task may spend, and when the run 

2stops starting work. 

3 

4**Money.** A run has a budget, and keeps part of it back for the answer 

5(``reserve_usd``): work is started only while the rest covers it, so a run 

6that runs low still writes one. Each task has a **share** — the plan's and 

7the review's a fixed part, each piece of work a part of what is left in 

8proportion to its estimate (its agent's typical turn × its effort) — and the 

9most one call may spend, its **lease**, is the share left, or what is left of 

10the run less the reserve and the leases of the tasks already running, 

11whichever is less. svc-ai stops a call past it (``targets.spend_ceiling``, 

12``X-Spend-Limit``), as it stops one past a budget rule; the rules' own limit 

13still applies, whichever is tighter. Leasing is what keeps parallel tasks 

14from each spending the whole of what is left. 

15 

16**Money follows the work.** What a task did not spend of its share goes to 

17the work still waiting beside it (``Topology.release``, shapes of units), so 

18a share only ever grows; and what is split between new pieces leaves out 

19what the open tasks still hold (:func:`held`), so nothing is promised twice. 

20A task keeps its share on record, with what it passed on and what it was 

21given (:data:`PASSED_ON_KEY`, :data:`TOPPED_UP_KEY`), so a page can say where 

22the money went. 

23 

24**Time.** A run has a deadline, and keeps part of its time back for the 

25answer (``reserve_s``): once only that is left it wraps up — no new work, and 

26the answer is written from what is done. A piece's call may run until then; 

27the answer's until a short grace after the deadline, when the run ends 

28whatever is still running. 

29""" 

30 

31from __future__ import annotations 

32 

33from collections.abc import Iterable, Sequence 

34from datetime import UTC, datetime, timedelta 

35from decimal import Decimal 

36 

37from app.db.postgres.enums import SwarmEnum 

38from app.db.postgres.models import SwarmRun, SwarmTask 

39from app.services import rule_engine 

40from app.services.swarms.schemas import EFFORT_TURNS, Effort 

41 

42TaskKind = SwarmEnum.TaskKind 

43TaskStatus = SwarmEnum.TaskStatus 

44WrapUpReason = SwarmEnum.WrapUpReason 

45 

46#: Less than this is not worth starting a task on. 

47MIN_TASK_USD = Decimal("0.01") 

48#: The answer's reserve: this share of the budget, or this many of the 

49#: lead's typical turns, whichever is more — never more than half. 

50RESERVE_SHARE = Decimal("0.10") 

51RESERVE_TURNS = Decimal("1.5") 

52#: The plan's and the review's shares of what is not reserved. 

53PLAN_SHARE = Decimal("0.15") 

54REVIEW_SHARE = Decimal("0.10") 

55#: The answer's time: this share of the cap, at least five minutes, never 

56#: more than half. 

57RESERVE_TIME_SHARE = 0.10 

58MIN_RESERVE_S = 300 

59#: How long past the deadline the answer may still be written. 

60GRACE_S = 600 

61#: How long one call may take, whatever time is left. 

62MIN_TASK_TIMEOUT_S = 60 

63MAX_TASK_TIMEOUT_S = 1800 

64 

65_CENT = Decimal("0.000001") 

66 

67#: A team's budget, kept on its plan's brief (``engine._share_out``). 

68TEAM_BUDGET_KEY = "team_budget" 

69#: What a waiting task was given of finished work's unspent shares, all told. 

70TOPPED_UP_KEY = "topped_up_usd" 

71#: What a finished task (or a closed team) passed on to waiting work. 

72PASSED_ON_KEY = "passed_on_usd" 

73 

74#: A task that may still spend: what it holds of its share is spoken for. 

75OPEN_TASK = frozenset( 

76 { 

77 TaskStatus.queued, 

78 TaskStatus.running, 

79 TaskStatus.awaiting_input, 

80 TaskStatus.interrupted, 

81 } 

82) 

83 

84 

85def _usd(value: object) -> Decimal: 

86 if value is None: 

87 return Decimal(0) 

88 return value if isinstance(value, Decimal) else Decimal(str(value)) 

89 

90 

91#: A stored sum as a ``Decimal`` (0 for none). 

92usd = _usd 

93 

94 

95def brief_usd(task: SwarmTask, key: str) -> Decimal | None: 

96 """A sum kept on ``task``'s brief (a team's budget, what it was given or 

97 passed on), or None when it holds none.""" 

98 value = (task.brief or {}).get(key) if isinstance(task.brief, dict) else None 

99 if value is None: 

100 return None 

101 try: 

102 return Decimal(str(value)) 

103 except ArithmeticError: 

104 return None 

105 

106 

107def share_left(task: SwarmTask) -> Decimal: 

108 """What ``task`` has not spent of its share (none without one).""" 

109 if task.budget_usd is None: 

110 return Decimal(0) 

111 return max(_usd(task.budget_usd) - _usd(task.spent_usd), Decimal(0)) 

112 

113 

114def held(tasks: Iterable[SwarmTask]) -> Decimal: 

115 """What the open tasks hold between them: each one's share less what it 

116 has spent — a team not yet planned, its whole team's budget. The answer 

117 holds nothing here: the reserve is apart.""" 

118 total = Decimal(0) 

119 for task in tasks: 

120 if task.status not in OPEN_TASK: 

121 continue 

122 whole = brief_usd(task, TEAM_BUDGET_KEY) 

123 share = whole if whole is not None else task.budget_usd 

124 if share is None: 

125 continue 

126 total += max(_usd(share) - _usd(task.spent_usd), Decimal(0)) 

127 return total 

128 

129 

130def reserves( 

131 budget_usd: Decimal, time_cap_s: int, lead_turn_usd: Decimal 

132) -> tuple[Decimal, int]: 

133 """``(reserve_usd, reserve_s)`` for a run: what is kept back for the 

134 answer.""" 

135 money = max(budget_usd * RESERVE_SHARE, lead_turn_usd * RESERVE_TURNS) 

136 money = min(money, budget_usd / 2).quantize(_CENT) 

137 time = max(int(time_cap_s * RESERVE_TIME_SHARE), MIN_RESERVE_S) 

138 return money, min(time, time_cap_s // 2) 

139 

140 

141def unreserved(run: SwarmRun) -> Decimal: 

142 """What the run may spend on everything but its answer.""" 

143 return max(_usd(run.budget_usd) - _usd(run.reserve_usd), Decimal(0)) 

144 

145 

146def plan_share(run: SwarmRun) -> Decimal: 

147 return (unreserved(run) * PLAN_SHARE).quantize(_CENT) 

148 

149 

150def review_share(run: SwarmRun) -> Decimal: 

151 return (unreserved(run) * REVIEW_SHARE).quantize(_CENT) 

152 

153 

154def estimate(turn_usd: Decimal, effort: str | None) -> Decimal: 

155 """What a piece of ``effort`` is expected to cost, from its agent's 

156 typical turn.""" 

157 try: 

158 turns = EFFORT_TURNS[Effort(effort or Effort.medium)] 

159 except ValueError: 

160 turns = EFFORT_TURNS[Effort.medium] 

161 return (turn_usd * turns).quantize(_CENT) 

162 

163 

164def shares(estimates: Sequence[Decimal], pool: Decimal) -> list[Decimal]: 

165 """``pool`` split in proportion to ``estimates`` — each piece's share of 

166 what is left for the work.""" 

167 if not estimates: 

168 return [] 

169 pool = max(pool, Decimal(0)) 

170 total = sum(estimates, Decimal(0)) 

171 if total <= 0: 

172 even = (pool / len(estimates)).quantize(_CENT) 

173 return [even for _ in estimates] 

174 return [(pool * e / total).quantize(_CENT) for e in estimates] 

175 

176 

177def work_pool( 

178 run: SwarmRun, held: Decimal = Decimal(0), *, review: bool = True 

179) -> Decimal: 

180 """What is left for new pieces of work: the budget less the reserve, 

181 what has been spent, what the open tasks still hold (:func:`held`) and — 

182 when a review comes with them — the review's share.""" 

183 taken = _usd(run.spent_usd) + _usd(held) 

184 if review: 

185 taken += review_share(run) 

186 return max(unreserved(run) - taken, Decimal(0)) 

187 

188 

189def leased(tasks: Iterable[SwarmTask]) -> Decimal: 

190 """What the running tasks may still spend between them.""" 

191 return sum( 

192 ( 

193 max(_usd(t.limit_usd) - _usd(t.spent_usd), Decimal(0)) 

194 for t in tasks 

195 if t.status == TaskStatus.running 

196 ), 

197 Decimal(0), 

198 ) 

199 

200 

201def run_left(run: SwarmRun, task: SwarmTask) -> Decimal: 

202 """What the run has left that ``task`` may spend, whatever its share: 

203 the budget less what is spent and what the running tasks may still 

204 spend — less the reserve, but for the run's answer.""" 

205 left = _usd(run.budget_usd) - _usd(run.spent_usd) - leased(run.tasks or []) 

206 if not (task.kind == TaskKind.synthesise and int(task.depth or 0) == 0): 

207 # Only the run's answer may use its reserve, not a team's report. 

208 left -= _usd(run.reserve_usd) 

209 return left.quantize(_CENT) 

210 

211 

212def lease(run: SwarmRun, task: SwarmTask) -> Decimal | None: 

213 """The most ``task``'s next call may spend, or None when there is not 

214 enough left to start it. The answer may use the reserve; nothing else 

215 may.""" 

216 left = run_left(run, task) 

217 if task.budget_usd is not None: 

218 left = min(left, share_left(task)).quantize(_CENT) 

219 return left if left >= MIN_TASK_USD else None 

220 

221 

222def limit(task: SwarmTask) -> rule_engine.SpendLimit: 

223 """``task``'s lease as svc-ai is told it, with what its share had left 

224 when the call started — so a stop can say whether the share or the run 

225 ran out.""" 

226 return rule_engine.SpendLimit( 

227 usd=_usd(task.limit_usd), 

228 rule_id=None, 

229 rule_name="Swarm budget", 

230 rule_version=None, 

231 cap_usd=share_left(task) if task.budget_usd is not None else None, 

232 resets_at=None, 

233 kind=rule_engine.SWARM_LIMIT, 

234 ) 

235 

236 

237def _deadline(run: SwarmRun) -> datetime: 

238 deadline = run.deadline_at 

239 return deadline.replace(tzinfo=UTC) if deadline.tzinfo is None else deadline 

240 

241 

242def wrap_up_due(run: SwarmRun, now: datetime) -> WrapUpReason | None: 

243 """Why the run should stop starting work now, if it should: someone 

244 pressed Stop, or only the answer's time is left. (Money is judged task 

245 by task, at :func:`lease`.)""" 

246 if run.cancel_requested: 

247 return WrapUpReason.stopped 

248 if now >= _deadline(run) - timedelta(seconds=run.reserve_s): 

249 return WrapUpReason.time 

250 return None 

251 

252 

253def past_hard_stop(run: SwarmRun, now: datetime) -> bool: 

254 """Whether the answer's grace is over: the run ends with what it has.""" 

255 return now >= _deadline(run) + timedelta(seconds=GRACE_S) 

256 

257 

258def timeout(run: SwarmRun, task: SwarmTask, now: datetime) -> float: 

259 """How long ``task``'s call may take.""" 

260 end = ( 

261 _deadline(run) + timedelta(seconds=GRACE_S) 

262 if task.kind == TaskKind.synthesise 

263 else _deadline(run) - timedelta(seconds=run.reserve_s) 

264 ) 

265 left = (end - now).total_seconds() 

266 return float(max(MIN_TASK_TIMEOUT_S, min(left, MAX_TASK_TIMEOUT_S)))