Coverage for app / services / stats / resource_cost.py: 94%

88 statements  

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

1""" 

2What one resource — or one kind of resource, or the whole account — has cost. 

3 

4The figure every resource page's cost card shows. It reads the usage ledger by 

5*source* (``UsageEnum.Source``): the resource the spend is attributed to, 

6which is not always the one that ran — a dashboard tile runs as the agent it 

7borrows and is still the dashboard's spend. See 

8``docs/guides/cost-monitoring.md``. 

9 

10Honest about what it cannot price: rows with no cost are counted 

11(``unpriced_invocations``), as are metered calls svc-ai could not price 

12(``unpriced_calls``), so a card can say "at least $X" instead of presenting a 

13lower bound as the total. None is never read as zero. 

14""" 

15 

16from __future__ import annotations 

17 

18from datetime import datetime, timedelta, timezone 

19from typing import Any 

20from uuid import UUID 

21 

22from sqlalchemy import Date, case, cast, func 

23from sqlalchemy.orm import Session 

24 

25from app.db.postgres.enums import UsageEnum 

26from app.db.postgres.models import GovernanceUsage 

27from app.services import llm_paths 

28from app.services.stats import periods 

29from app.util.time import aware_utcnow 

30 

31#: Days of daily series an "all time" window draws — a sparkline, not a 

32#: ledger dump. 

33MAX_SERIES_DAYS = 90 

34#: The period a ``since`` / ``until`` range is reported as. 

35CUSTOM_PERIOD = "custom" 

36 

37 

38class ResourceCostError(ValueError): 

39 pass 

40 

41 

42def _float(value: Any) -> float | None: 

43 return float(value) if value is not None else None 

44 

45 

46def _aware_utc(value: datetime | None) -> datetime | None: 

47 """A bound given with no offset is UTC, as every server time is.""" 

48 if value is None: 

49 return None 

50 if value.tzinfo is None: 

51 return value.replace(tzinfo=timezone.utc) 

52 return value.astimezone(timezone.utc) 

53 

54 

55def naive_utc(value: datetime) -> datetime: 

56 """A bound as the ledger stores time: naive UTC.""" 

57 return _aware_utc(value).replace(tzinfo=None) 

58 

59 

60def source_key(source_type: str | None) -> str | None: 

61 """A ``UsageEnum.Source`` value, or ResourceCostError for anything else.""" 

62 if source_type is None: 

63 return None 

64 try: 

65 return UsageEnum.Source(source_type).value 

66 except ValueError as exc: 

67 raise ResourceCostError(f"'{source_type}' is not a cost source.") from exc 

68 

69 

70def scope_filters( 

71 owner_user_id: UUID, 

72 *, 

73 workspace: Any = None, 

74 include_projects: bool = False, 

75 mine: bool = False, 

76 source_type: str | None = None, 

77 source_id: UUID | None = None, 

78) -> list: 

79 """The ledger rows a figure counts: the workspace's (or, with none, the 

80 caller's own), narrowed to the caller with ``mine`` and to a source.""" 

81 filters = [ 

82 workspace.stamped(GovernanceUsage, projects=include_projects) 

83 if workspace is not None 

84 else GovernanceUsage.owner_user_id == owner_user_id 

85 ] 

86 if mine and workspace is not None: 

87 filters.append(GovernanceUsage.owner_user_id == owner_user_id) 

88 if source_type is not None: 

89 filters.append(GovernanceUsage.source_type == source_type) 

90 if source_id is not None: 

91 filters.append(GovernanceUsage.source_id == source_id) 

92 return filters 

93 

94 

95def resource_cost( 

96 db: Session, 

97 owner_user_id: UUID, 

98 *, 

99 source_type: str | None = None, 

100 source_id: UUID | None = None, 

101 period: str | None = None, 

102 now: datetime | None = None, 

103 workspace: Any = None, 

104 include_projects: bool = False, 

105 mine: bool = False, 

106 since: datetime | None = None, 

107 until: datetime | None = None, 

108) -> dict[str, Any]: 

109 """Spend over ``period``, for one source, one kind of source, or all. 

110 

111 Scoped like a breakdown (``breakdown.breakdown``): given a 

112 ``workspace``, the work done in it by anyone (and, with 

113 ``include_projects``, in its projects) — so an organisation's agent's 

114 card shows the organisation's spend on it, and Personal's whole-account 

115 card never counts an organisation's. Without one, the caller's own rows. 

116 

117 ``mine`` narrows it to the caller's own work in that workspace — "your 

118 spend", where without it the figure is the workspace's. ``since`` / 

119 ``until`` replace the period with a range of the caller's choosing (the 

120 Stats page's), reported as period ``custom``. 

121 """ 

122 source_type = source_key(source_type) 

123 if source_id is not None and source_type is None: 

124 raise ResourceCostError("source_id needs a source_type.") 

125 

126 since, until = _aware_utc(since), _aware_utc(until) 

127 custom = since is not None or until is not None 

128 if since is not None and until is not None and since >= until: 

129 raise ResourceCostError("since must be before until.") 

130 window = periods.get_period(None if custom else period) 

131 now = now or aware_utcnow() 

132 if until is not None: 

133 now = min(now, until) 

134 if not custom: 

135 since = window.since(now) 

136 # A period already over (last month) ends at its boundary, and its 

137 # daily series with it. 

138 ended = window.until(now) 

139 if ended is not None: 

140 until = ended 

141 now = min(now, ended) 

142 

143 filters = scope_filters( 

144 owner_user_id, 

145 workspace=workspace, 

146 include_projects=include_projects, 

147 mine=mine, 

148 source_type=source_type, 

149 source_id=source_id, 

150 ) 

151 if until is not None: 

152 filters.append(GovernanceUsage.occurred_at < naive_utc(until)) 

153 windowed = [*filters] 

154 if since is not None: 

155 windowed.append(GovernanceUsage.occurred_at >= naive_utc(since)) 

156 

157 failed = case((GovernanceUsage.outcome == UsageEnum.Outcome.error, 1), else_=0) 

158 # Unpriced means it spent tokens nobody could price — not a failed call 

159 # that never reached a model, which cost nothing and says so. 

160 unpriced_row = case( 

161 ( 

162 GovernanceUsage.estimated_cost_usd.is_(None) 

163 & ( 

164 (GovernanceUsage.input_tokens + GovernanceUsage.output_tokens > 0) 

165 | (GovernanceUsage.llm_calls > 0) 

166 ), 

167 1, 

168 ), 

169 else_=0, 

170 ) 

171 

172 totals = ( 

173 db.query( 

174 func.count(GovernanceUsage.id), 

175 func.sum(GovernanceUsage.estimated_cost_usd), 

176 func.sum(failed), 

177 func.sum(unpriced_row), 

178 func.sum(GovernanceUsage.llm_calls), 

179 func.sum(GovernanceUsage.unpriced_calls), 

180 func.sum(GovernanceUsage.input_tokens), 

181 func.sum(GovernanceUsage.output_tokens), 

182 func.max(GovernanceUsage.occurred_at), 

183 ) 

184 .filter(*windowed) 

185 .one() 

186 ) 

187 ( 

188 invocations, 

189 cost, 

190 failures, 

191 unpriced_rows, 

192 llm_calls, 

193 unpriced_calls, 

194 input_tokens, 

195 output_tokens, 

196 last_at, 

197 ) = totals 

198 

199 def _grouped(column) -> list[dict[str, Any]]: 

200 rows = ( 

201 db.query( 

202 column, 

203 func.count(GovernanceUsage.id), 

204 func.sum(GovernanceUsage.estimated_cost_usd), 

205 ) 

206 .filter(*windowed) 

207 .group_by(column) 

208 .all() 

209 ) 

210 return sorted( 

211 ( 

212 { 

213 "key": key, 

214 "invocations": int(count or 0), 

215 "cost_usd": _float(total), 

216 } 

217 for key, count, total in rows 

218 ), 

219 key=lambda r: (r["cost_usd"] is None, -(r["cost_usd"] or 0)), 

220 ) 

221 

222 by_execution_type = [ 

223 {**row, "label": llm_paths.EXECUTION_TYPE_LABELS.get(row["key"], row["key"])} 

224 for row in _grouped(GovernanceUsage.execution_type) 

225 ] 

226 by_source = [ 

227 { 

228 **row, 

229 "label": llm_paths.SOURCE_LABELS.get(row["key"], "Unattributed") 

230 if row["key"] 

231 else "Unattributed", 

232 } 

233 for row in _grouped(GovernanceUsage.source_type) 

234 ] 

235 

236 series_since = since or (now - timedelta(days=MAX_SERIES_DAYS)) 

237 series_since = max(series_since, now - timedelta(days=MAX_SERIES_DAYS)) 

238 day = cast(GovernanceUsage.occurred_at, Date) 

239 daily_rows = ( 

240 db.query( 

241 day, 

242 func.count(GovernanceUsage.id), 

243 func.sum(GovernanceUsage.estimated_cost_usd), 

244 ) 

245 .filter(*filters, GovernanceUsage.occurred_at >= naive_utc(series_since)) 

246 .group_by(day) 

247 .order_by(day) 

248 .all() 

249 ) 

250 by_day = {str(d): (int(c or 0), _float(t)) for d, c, t in daily_rows} 

251 daily = [] 

252 cursor = series_since.date() 

253 # ``until`` is exclusive: a range ending at midnight ends the day before. 

254 last_day = (until - timedelta(microseconds=1)).date() if until else now.date() 

255 while cursor <= min(last_day, now.date()): 

256 count, total = by_day.get(str(cursor), (0, None)) 

257 daily.append({"date": str(cursor), "invocations": count, "cost_usd": total}) 

258 cursor += timedelta(days=1) 

259 

260 invocations = int(invocations or 0) 

261 return { 

262 "source_type": source_type, 

263 "source_id": str(source_id) if source_id else None, 

264 "period": CUSTOM_PERIOD if custom else window.key, 

265 "period_label": "Selected range" if custom else window.label, 

266 # Whose work it counts: the caller's own, or everyone's in the 

267 # workspace — what a figure's caption has to say. 

268 "mine": bool(mine) or workspace is None, 

269 "since": since, 

270 "until": now, 

271 "invocations": invocations, 

272 "failed_invocations": int(failures or 0), 

273 # None only when there was spend and none of it could be priced. 

274 "cost_usd": ( 

275 None if cost is None and int(unpriced_rows or 0) else float(cost or 0) 

276 ), 

277 "unpriced_invocations": int(unpriced_rows or 0), 

278 "llm_calls": int(llm_calls or 0), 

279 "unpriced_calls": int(unpriced_calls or 0), 

280 "input_tokens": int(input_tokens or 0), 

281 "output_tokens": int(output_tokens or 0), 

282 "last_invocation_at": last_at, 

283 "by_execution_type": by_execution_type, 

284 "by_source": by_source, 

285 "daily": daily, 

286 }