Coverage for app / services / generation.py: 95%

154 statements  

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

1""" 

2Generative-invocation capture — the provenance write path. 

3 

4``app.services.history`` answers *what changed*. This answers *why it 

5exists*: one :class:`GenerationRun` row per invocation of a generative flow, 

6holding the arguments the user supplied and the model that answered. 

7 

8Written at invocation time, before the user has accepted anything, for two 

9reasons. A proposal the user rejected is still an event worth being able to 

10show, and the id has to exist before the resources that will reference it — 

11the resource rows carry ``generation_id``, not the other way round. 

12 

13Lifecycle 

14───────── 

15 

16 start() status=proposed the flow was invoked 

17 │ 

18 ├─ fail() status=failed the model was unreachable or useless 

19 │ 

20 └─ apply() status=applied resources were created; target recorded 

21 

22A flow too long for one request (knowledge setup, which searches the web 

23first) starts ``running`` instead, reports where it is with 

24:func:`record_progress`, and lands its proposal on the row with 

25:func:`propose`; the person polls the run until it is ``proposed``. 

26 

27``apply`` is a separate call because several flows return a proposal from one 

28endpoint and persist it from another (``/generate`` then 

29``/create-from-config``, or ``/dashboards/generate`` then the ordinary 

30``POST /dashboards``). The client hands the generation id back, which is what 

31lets a board created through the normal create path still be traceable. 

32 

33Redaction 

34───────── 

35 

36``arguments`` is the request body, so it is passed through 

37:func:`redact_arguments` first. The flows here take a free-text description 

38and a model id — no credentials — but a stored argument blob is exactly the 

39kind of thing that silently starts carrying secrets later, so the filter is 

40applied unconditionally rather than trusting each caller. 

41""" 

42 

43import logging 

44from contextlib import contextmanager 

45from datetime import datetime, timedelta 

46from typing import Any, Iterable, Iterator, Optional 

47from uuid import UUID, uuid4 

48 

49from sqlalchemy.orm import Session 

50 

51from app.db.postgres.enums import GenerationEnum, HistoryEnum, UsageEnum 

52from app.db.postgres.models import GenerationRun, User 

53from app.util.time import aware_utcnow, utc_isoformat 

54 

55logger = logging.getLogger(__name__) 

56 

57#: Substrings that mark an argument key as unsafe to persist. Matched 

58#: case-insensitively against the key, at any nesting depth. 

59_REDACTED_KEY_PARTS: tuple[str, ...] = ( 

60 "password", 

61 "secret", 

62 "token", 

63 "api_key", 

64 "apikey", 

65 "credential", 

66 "authorization", 

67 "auth_header", 

68 "private_key", 

69) 

70 

71_REDACTED = "[redacted]" 

72 

73#: Cap on any single stored string. Generation arguments are descriptions, 

74#: not documents; an unbounded blob in an audit row helps nobody. 

75MAX_ARGUMENT_CHARS = 8_000 

76 

77#: How a generation flow's spend is recorded on the usage ledger. 

78GENERATION_EXECUTION_TYPE = "generation" 

79 

80#: How long a background run may go without reporting progress before it is 

81#: taken to have died with its process (a restart, a deploy). 

82STALE_AFTER = timedelta(minutes=8) 

83 

84 

85def _is_sensitive(key: str) -> bool: 

86 lowered = key.lower() 

87 return any(part in lowered for part in _REDACTED_KEY_PARTS) 

88 

89 

90def redact_arguments(value: Any, _depth: int = 0) -> Any: 

91 """Recursively redact sensitive keys and truncate oversized strings. 

92 

93 Depth-limited because the input is client-supplied JSON: a deeply nested 

94 body should degrade to a marker rather than blow the stack. 

95 """ 

96 if _depth > 12: 

97 return "[truncated: too deeply nested]" 

98 if isinstance(value, dict): 

99 return { 

100 key: ( 

101 _REDACTED 

102 if _is_sensitive(str(key)) 

103 else redact_arguments(item, _depth + 1) 

104 ) 

105 for key, item in value.items() 

106 } 

107 if isinstance(value, (list, tuple)): 

108 return [redact_arguments(item, _depth + 1) for item in value] 

109 if isinstance(value, str) and len(value) > MAX_ARGUMENT_CHARS: 

110 return value[:MAX_ARGUMENT_CHARS] + "…[truncated]" 

111 if isinstance(value, UUID): 

112 return str(value) 

113 return value 

114 

115 

116def start( 

117 db: Session, 

118 *, 

119 flow: GenerationEnum.Flow, 

120 actor: Optional[User], 

121 arguments: Any, 

122 model_info: Optional[dict] = None, 

123 status: GenerationEnum.Status = GenerationEnum.Status.proposed, 

124 progress: Optional[dict] = None, 

125) -> GenerationRun: 

126 """Open a generation run in ``proposed`` state — or ``running``, for a 

127 flow that works in the background — and flush it. 

128 

129 Flushed (not committed) so the row is visible to the rest of the 

130 transaction — a flow that goes on to fail rolls it back with everything 

131 else and records the failure separately via :func:`fail`. 

132 

133 The id is assigned here rather than left to the column default, for the 

134 same reason agent create-from-config assigns its ids up front: callers 

135 hand it straight back to the client and stamp it onto resource rows, so 

136 it has to be readable without depending on when a flush happens. 

137 """ 

138 run = GenerationRun( 

139 id=uuid4(), 

140 flow=flow, 

141 status=status, 

142 arguments=redact_arguments(arguments) if arguments is not None else {}, 

143 progress=progress, 

144 actor_user_id=actor.id if actor else None, 

145 **_workspace_columns(), 

146 **_model_columns(model_info), 

147 ) 

148 db.add(run) 

149 db.flush() 

150 return run 

151 

152 

153def _workspace_columns() -> dict[str, Any]: 

154 """The workspace the request invoking the flow was made in — where what 

155 it proposes is created (``app/dependency/workspace.py``).""" 

156 from app.dependency.workspace import requested_workspace 

157 from app.services.workspace import WorkspaceKind, parse_key 

158 

159 key = requested_workspace() 

160 if not key: 

161 return {} 

162 try: 

163 kind, id_ = parse_key(key) 

164 except Exception: 

165 return {} 

166 return { 

167 "workspace_organisation_id": id_ 

168 if kind is WorkspaceKind.organisation 

169 else None, 

170 "workspace_project_id": id_ if kind is WorkspaceKind.project else None, 

171 } 

172 

173 

174def _model_columns(model_info: Optional[dict]) -> dict[str, Any]: 

175 """Pull the denormalised model identity out of svc-ai's model payload. 

176 

177 Tolerant of a missing or partial payload: the run is worth recording even 

178 when model resolution is what failed. 

179 """ 

180 if not model_info: 

181 return {"ai_model_id": None, "provider": None, "model_name": None} 

182 provider = model_info.get("provider") 

183 provider_name = provider.get("name") if isinstance(provider, dict) else provider 

184 raw_id = model_info.get("id") 

185 return { 

186 "ai_model_id": UUID(str(raw_id)) if raw_id else None, 

187 "provider": str(provider_name) if provider_name else None, 

188 "model_name": model_info.get("model_name"), 

189 } 

190 

191 

192def apply( 

193 db: Session, 

194 run: Optional[GenerationRun], 

195 *, 

196 target_resource_type: Optional[HistoryEnum.ResourceType] = None, 

197 target_resource_id: Optional[UUID] = None, 

198 warnings: Optional[Iterable[str]] = None, 

199) -> Optional[GenerationRun]: 

200 """Mark a run applied and record what it produced. 

201 

202 Accepts ``None`` so callers can pass an optional run through without 

203 branching — a resource created by hand simply has no run to update. 

204 """ 

205 if run is None: 

206 return None 

207 run.status = GenerationEnum.Status.applied 

208 run.applied_at = aware_utcnow() 

209 if target_resource_type is not None: 

210 run.target_resource_type = target_resource_type 

211 if target_resource_id is not None: 

212 run.target_resource_id = target_resource_id 

213 if warnings is not None: 

214 run.warnings = list(warnings) 

215 return run 

216 

217 

218def fail( 

219 db: Session, 

220 run: Optional[GenerationRun], 

221 *, 

222 error: str, 

223) -> Optional[GenerationRun]: 

224 """Mark a run failed with the reason. 

225 

226 Best-effort: a failure here must never mask the original error the caller 

227 is already raising, so it is logged and swallowed. 

228 """ 

229 if run is None: 

230 return None 

231 try: 

232 run.status = GenerationEnum.Status.failed 

233 run.error = error[:2000] 

234 db.add(run) 

235 except Exception: # pragma: no cover - defensive 

236 logger.exception("Could not record generation failure") 

237 return run 

238 

239 

240@contextmanager 

241def metered(db: Session, run: Optional[GenerationRun]) -> Iterator[Any]: 

242 """Ledger what a generation flow's svc-ai call spent, against its run — 

243 and refuse it when the workspace's budget is used up. 

244 

245 Generative flows used to be the one way to reach a model that nothing 

246 counted: no ledger row, so no cost cap saw them and no spend board showed 

247 them. Wrap the flow's svc-ai call in this; the spend is attributed to the 

248 run (``UsageEnum.Source.generation``) so an invocation's cost is one query 

249 away from ``GET /app/generations/{id}``, and filed in the workspace the 

250 flow ran in — it used to land in the actor's Personal, where an 

251 organisation's budget never saw it. A call that raised is recorded as 

252 failed — it may still have been paid for (a retry that never parsed). 

253 Does not commit: the flow commits the run and the row together. 

254 

255 Before the call, the workspace's budgets are asked (``budgets.gate``): 

256 one used up fails the run with its message, commits that, and raises 

257 ``BudgetReached`` (a 403); one with something left limits the call to it, 

258 and svc-ai stopping it there ends the same way. 

259 """ 

260 from app.services import ai_client 

261 from app.services import usage as usage_service 

262 from app.services import workspace as workspace_service 

263 from app.services.budgets import gate 

264 

265 ws = ( 

266 workspace_service.made_in( 

267 db, 

268 organisation_id=run.workspace_organisation_id, 

269 project_id=run.workspace_project_id, 

270 user_id=run.actor_user_id, 

271 ) 

272 if run is not None 

273 else None 

274 ) 

275 limit = None 

276 if ws is not None: 

277 try: 

278 limit = gate.check( 

279 db, 

280 ws=ws, 

281 actor_user_id=run.actor_user_id, 

282 execution_type=GENERATION_EXECUTION_TYPE, 

283 ) 

284 except gate.BudgetReached as exc: 

285 fail(db, run, error=exc.message) 

286 db.commit() 

287 raise 

288 

289 failed = False 

290 stopped: gate.BudgetReached | None = None 

291 with ai_client.usage_capture() as used, ai_client.in_spend_limit(limit): 

292 try: 

293 yield used 

294 except ai_client.SpendLimitReached as exc: 

295 failed = True 

296 stopped = gate.BudgetReached.from_stop(exc) 

297 except BaseException: 

298 failed = True 

299 raise 

300 finally: 

301 if run is not None: 

302 usage_service.record_measured( 

303 db, 

304 owner_user_id=run.actor_user_id, 

305 execution_type=GENERATION_EXECUTION_TYPE, 

306 source_type=UsageEnum.Source.generation, 

307 source_id=run.id, 

308 measured=used, 

309 failed=failed, 

310 workspace=ws, 

311 ) 

312 if stopped is not None: 

313 fail(db, run, error=stopped.message) 

314 db.commit() 

315 raise stopped 

316 

317 

318def record_progress(run: GenerationRun, stage: str, **details: Any) -> None: 

319 """Say where a ``running`` run has got to: its stage, any counts so far, 

320 and when it last reported — what tells a live run from a dead one.""" 

321 run.progress = { 

322 **(run.progress or {}), 

323 **details, 

324 "stage": stage, 

325 "updated_at": utc_isoformat(aware_utcnow()), 

326 } 

327 

328 

329def propose( 

330 run: GenerationRun, proposal: dict, warnings: Optional[Iterable[str]] = None 

331) -> None: 

332 """Land a background run's proposal: ``proposed``, ready for review.""" 

333 run.status = GenerationEnum.Status.proposed 

334 run.proposal = proposal 

335 if warnings is not None: 

336 run.warnings = list(warnings) 

337 record_progress(run, "done") 

338 

339 

340def is_stale(run: GenerationRun, now: Optional[datetime] = None) -> bool: 

341 """A ``running`` run that has not reported for :data:`STALE_AFTER` — its 

342 worker went with the process that ran it.""" 

343 if run.status != GenerationEnum.Status.running: 

344 return False 

345 raw = (run.progress or {}).get("updated_at") 

346 try: 

347 updated = datetime.fromisoformat(raw) if isinstance(raw, str) else None 

348 except ValueError: 

349 updated = None 

350 if updated is None: 

351 updated = run.created_at 

352 if updated is None: 

353 return False 

354 if updated.tzinfo is None: 

355 updated = updated.replace(tzinfo=aware_utcnow().tzinfo) 

356 return (now or aware_utcnow()) - updated > STALE_AFTER 

357 

358 

359def made_in(db: Session, run: GenerationRun) -> Any: 

360 """The workspace a run was invoked in — what a background worker, which 

361 inherits no request context, names on its svc-ai calls.""" 

362 from app.services import workspace as workspace_service 

363 

364 return workspace_service.made_in( 

365 db, 

366 organisation_id=run.workspace_organisation_id, 

367 project_id=run.workspace_project_id, 

368 user_id=run.actor_user_id, 

369 ) 

370 

371 

372def record_warnings( 

373 run: Optional[GenerationRun], warnings: Optional[Iterable[str]] 

374) -> None: 

375 """Attach non-fatal problems to a run without changing its status.""" 

376 if run is None or warnings is None: 

377 return 

378 run.warnings = list(warnings) 

379 

380 

381def resolve( 

382 db: Session, 

383 generation_id: Optional[UUID], 

384 actor: User, 

385) -> Optional[GenerationRun]: 

386 """Look up a run the client handed back, verifying it belongs to ``actor``. 

387 

388 Used by create endpoints that accept a ``generation_id`` from a proposal 

389 (dashboards). A run that does not exist, or belongs to someone else, is 

390 treated as absent rather than an error: the resource is still legitimate, 

391 it just loses its provenance link, and failing the create would be a worse 

392 outcome than an unlinked row. 

393 """ 

394 if generation_id is None: 

395 return None 

396 run = db.get(GenerationRun, generation_id) 

397 if run is None: 

398 logger.warning("Unknown generation_id %s ignored", generation_id) 

399 return None 

400 if run.actor_user_id and actor and run.actor_user_id != actor.id: 

401 logger.warning( 

402 "generation_id %s belongs to another user; ignoring", generation_id 

403 ) 

404 return None 

405 return run 

406 

407 

408def stamp(resources: Iterable[Any], run: Optional[GenerationRun]) -> None: 

409 """Tag every resource in ``resources`` as produced by ``run``. 

410 

411 Sets both ``is_ai_generated`` and ``generation_id`` together so the flag 

412 and its explanation can never disagree. Silently skips resources whose 

413 model does not carry the columns, so a caller does not have to know which 

414 of its rows are generation-aware. 

415 """ 

416 if run is None: 

417 return 

418 for resource in resources: 

419 if hasattr(resource, "is_ai_generated"): 

420 resource.is_ai_generated = True 

421 if hasattr(resource, "generation_id"): 

422 resource.generation_id = run.id