Coverage for app / services / stats / step_usage.py: 93%

61 statements  

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

1""" 

2Where a resource's tokens go: its recent turns' model calls, summed by the 

3step of the pipeline that made them (cost-control plan, B0.2). 

4 

5The ledger knows which turns were a resource's and what each cost; only 

6svc-ai knows what each call in them was for (``llm_invocation_calls.node`` / 

7``step`` / ``pass_index``, svc-ai migration 27). So the turns are chosen 

8here — the resource's newest, in the request's workspace, as its cost card 

9counts them — and svc-ai is asked for exactly those (``POST /stats/steps``). 

10 

11Summed by *where* in the pipeline, never by model: svc-ai's call rows name 

12the provider and route that served each call, and no user's page names the 

13cloud a model runs on (see ``docs/business/sub-processors.md``). Which model 

14answered is the resource's configuration, shown on its own page. 

15 

16A gap reads as a gap: svc-ai unreachable is ``unavailable``, not an empty 

17breakdown. See ``docs/guides/cost-monitoring.md#where-the-tokens-go``. 

18""" 

19 

20from __future__ import annotations 

21 

22import logging 

23from datetime import datetime 

24from decimal import Decimal, InvalidOperation 

25from typing import Any 

26from uuid import UUID 

27 

28from sqlalchemy import func 

29from sqlalchemy.orm import Session 

30 

31from app.db.postgres.models import GovernanceUsage 

32from app.services import ai_client 

33from app.services.stats import periods 

34from app.services.stats import resource_cost 

35from app.util.time import aware_utcnow 

36 

37logger = logging.getLogger(__name__) 

38 

39#: The most turns one breakdown reads — the newest, so a busy agent's panel 

40#: describes how it answers now. Half svc-ai's own bound 

41#: (``ai_client.MAX_STEP_TURNS``). 

42MAX_TURNS = 1000 

43 

44#: The period a breakdown reads when none is named. 

45DEFAULT_PERIOD = "last_30_days" 

46 

47#: What each step sums. Every figure svc-ai serves per step but the latency, 

48#: which is the calls' own time added up and says nothing summed across 

49#: graph nodes that ran side by side. 

50_SUMMED = ( 

51 "calls", 

52 "failed_calls", 

53 "unpriced_calls", 

54 "prompt_tokens", 

55 "completion_tokens", 

56 "cache_read_tokens", 

57 "cache_write_tokens", 

58 "reasoning_tokens", 

59) 

60_MONEY = ("cost_usd", "cache_savings_usd") 

61 

62 

63def _decimal(value: Any) -> Decimal: 

64 try: 

65 return Decimal(str(value)) if value is not None else Decimal(0) 

66 except (InvalidOperation, ValueError): 

67 return Decimal(0) 

68 

69 

70def recent_turns( 

71 db: Session, 

72 owner_user_id: UUID, 

73 *, 

74 source_type: str, 

75 source_id: UUID | None, 

76 since: datetime | None, 

77 workspace: Any = None, 

78 include_projects: bool = False, 

79 limit: int = MAX_TURNS, 

80) -> tuple[list[UUID], int]: 

81 """The newest ``limit`` turns the ledger attributes to the source since 

82 ``since``, and how many there were in all. A turn with several ledger 

83 rows (a resumed pause) is one turn.""" 

84 filters = resource_cost.scope_filters( 

85 owner_user_id, 

86 workspace=workspace, 

87 include_projects=include_projects, 

88 source_type=source_type, 

89 source_id=source_id, 

90 ) 

91 filters.append(GovernanceUsage.invocation_id.isnot(None)) 

92 if since is not None: 

93 filters.append(GovernanceUsage.occurred_at >= resource_cost.naive_utc(since)) 

94 total = ( 

95 db.query(func.count(func.distinct(GovernanceUsage.invocation_id))) 

96 .filter(*filters) 

97 .scalar() 

98 ) 

99 rows = ( 

100 db.query(GovernanceUsage.invocation_id) 

101 .filter(*filters) 

102 .group_by(GovernanceUsage.invocation_id) 

103 .order_by(func.max(GovernanceUsage.occurred_at).desc()) 

104 .limit(limit) 

105 .all() 

106 ) 

107 return [row[0] for row in rows], int(total or 0) 

108 

109 

110def by_step(steps: list[dict[str, Any]]) -> list[dict[str, Any]]: 

111 """svc-ai's rows (one per node, step, pass, kind and model) summed over 

112 the models, dearest first.""" 

113 merged: dict[tuple, dict[str, Any]] = {} 

114 for row in steps: 

115 if not isinstance(row, dict): 

116 continue 

117 key = (row.get("node"), row.get("step"), row.get("pass_index"), row.get("kind")) 

118 into = merged.setdefault( 

119 key, 

120 { 

121 "node": key[0], 

122 "step": key[1], 

123 "pass_index": key[2], 

124 "kind": key[3] or "chat", 

125 **{name: 0 for name in _SUMMED}, 

126 **{name: Decimal(0) for name in _MONEY}, 

127 }, 

128 ) 

129 for name in _SUMMED: 

130 into[name] += int(row.get(name) or 0) 

131 for name in _MONEY: 

132 into[name] += _decimal(row.get(name)) 

133 out = [ 

134 {**row, **{name: float(row[name]) for name in _MONEY}} 

135 for row in merged.values() 

136 ] 

137 return sorted( 

138 out, 

139 key=lambda r: (-r["cost_usd"], -(r["prompt_tokens"] + r["completion_tokens"])), 

140 ) 

141 

142 

143def step_usage( 

144 db: Session, 

145 owner_user_id: UUID, 

146 *, 

147 source_type: str, 

148 source_id: UUID | None = None, 

149 period: str | None = None, 

150 now: datetime | None = None, 

151 workspace: Any = None, 

152 include_projects: bool = False, 

153) -> dict[str, Any]: 

154 """Where the source's recent turns' tokens went, step by step.""" 

155 source_type = resource_cost.source_key(source_type) 

156 if source_type is None: 

157 raise resource_cost.ResourceCostError( 

158 "A breakdown by step needs a source_type." 

159 ) 

160 window = periods.get_period(period or DEFAULT_PERIOD) 

161 now = now or aware_utcnow() 

162 since = window.since(now) 

163 turns, total = recent_turns( 

164 db, 

165 owner_user_id, 

166 source_type=source_type, 

167 source_id=source_id, 

168 since=since, 

169 workspace=workspace, 

170 include_projects=include_projects, 

171 ) 

172 result: dict[str, Any] = { 

173 "source_type": source_type, 

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

175 "period": window.key, 

176 "period_label": window.label, 

177 "since": since, 

178 "until": now, 

179 "turns_asked": len(turns), 

180 "turns_in_period": total, 

181 "turns": 0, 

182 "status": "recorded", 

183 "steps": [], 

184 } 

185 if not turns: 

186 return result 

187 try: 

188 answer = ai_client.get_step_usage(turns) 

189 except ai_client.AIServiceError: 

190 logger.warning("Could not read step usage from svc-ai", exc_info=True) 

191 return {**result, "status": "unavailable"} 

192 return { 

193 **result, 

194 "turns": int(answer.get("turns") or 0), 

195 "steps": by_step(answer.get("steps") or []), 

196 }