Coverage for app / services / decisions / schema.py: 100%

213 statements  

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

1"""The decision record as it is served (``GET /app/decisions/{id}``). 

2 

3One record per governed turn — an answer or a skill run — built from every 

4row that carries the turn's ``invocation_id``: its messages or run, the 

5rules that ran, review flags, the usage ledger, and svc-ai's model and tool 

6calls. Each section is its own typed model, discriminated by ``key``, and 

7says through ``status`` whether it holds what was recorded, found nothing, 

8or cannot say (``DecisionEnum.SectionStatus``). 

9""" 

10 

11from __future__ import annotations 

12 

13from typing import Annotated, Any, Literal, Union 

14from uuid import UUID 

15 

16from pydantic import BaseModel, Field 

17 

18from app.db.postgres.crud_schemas import Schema 

19from app.db.postgres.enums import DecisionEnum 

20from app.util.time import UTCDateTime 

21 

22Status = DecisionEnum.SectionStatus 

23 

24 

25class _Section(BaseModel): 

26 title: str 

27 status: Status = Status.recorded 

28 #: Why the section holds what it does, when it is not simply recorded. 

29 note: str | None = None 

30 

31 

32class RequestSection(_Section): 

33 """What the turn was asked, as stored — after the policy rules ran.""" 

34 

35 key: Literal["request"] = "request" 

36 prompt: str | None = None 

37 #: The chat command the turn ran, when it ran one (``meta.command``). 

38 command: dict[str, Any] | None = None 

39 #: The documents the message attached (``meta.attachments``): each 

40 #: ``{id, name, mime_type?}``, never its text. 

41 attachments: list[dict[str, Any]] | None = None 

42 #: A skill run's task and form values, as the skill was given them. 

43 task: str | None = None 

44 inputs: dict[str, Any] | None = None 

45 

46 

47class AnswerSection(_Section): 

48 """What came back, as stored — after the audit rules ran.""" 

49 

50 key: Literal["answer"] = "answer" 

51 #: The message's status (completed / blocked / error) or the run's. 

52 #: None when the answer was not stored. 

53 outcome: str | None = None 

54 content: str | None = None 

55 #: A skill run's structured outputs. 

56 outputs: dict[str, Any] | None = None 

57 stopped: bool = False 

58 #: The rule that refused it, when one did. 

59 blocked_by: str | None = None 

60 #: The Output rule that withheld it, when one did: ``content`` is then 

61 #: the rule's message, and the answer itself is on a review item. 

62 withheld_by: str | None = None 

63 error: str | None = None 

64 

65 

66class ConfigurationSection(_Section): 

67 """Which configuration answered: the revision in force when it ran.""" 

68 

69 key: Literal["configuration"] = "configuration" 

70 agent_id: UUID | None = None 

71 agent_name: str | None = None 

72 agent_version: int | None = None 

73 skill_id: UUID | None = None 

74 skill_name: str | None = None 

75 skill_version: int | None = None 

76 ai_model_id: UUID | None = None 

77 #: The model the answer names (an agent turn's meta, or svc-ai's trace). 

78 provider: str | None = None 

79 model_name: str | None = None 

80 #: The cost profile the agent ran under (``app/util/cost_profiles.py``): 

81 #: an answer from before profiles, or of the default, says ``thorough``. 

82 cost_profile: str | None = None 

83 #: Set when an Economy profile's lighter model wrote the answer 

84 #: (``{"answered": true, "reason": "simple"}``): ``model_name`` is it. 

85 lighter_model: dict | None = None 

86 

87 

88class RulesSection(_Section): 

89 """Every rule that ran on the turn, and what each came to.""" 

90 

91 key: Literal["rules"] = "rules" 

92 events: list[Schema.GovernanceActivity.Read] = [] 

93 #: Counts per ``GovernanceEnum.Outcome``. 

94 outcomes: dict[str, int] = {} 

95 

96 

97class WebSearchRecord(BaseModel): 

98 """One web search the turn made, as svc-ai recorded the call.""" 

99 

100 created_at: UTCDateTime | None = None 

101 #: What the agent searched for, as it asked (``input_args.query``). 

102 query: str | None = None 

103 #: What the engines said and what each check removed 

104 #: (``app/util/web_search_report.py``); None for a search recorded before 

105 #: reports were kept. 

106 report: dict[str, Any] | None = None 

107 

108 

109class WebSourcesSection(_Section): 

110 """Where the turn looked on the web: each search, what came back and 

111 what the checks — the workspace's Tools rules among them — did with it.""" 

112 

113 key: Literal["web_sources"] = "web_sources" 

114 searches: list[WebSearchRecord] = [] 

115 #: The turn's searches together, with what each Tools rule did 

116 #: (``web_search_summary.summarise``); None without a report to read. 

117 summary: dict[str, Any] | None = None 

118 

119 

120class QualityCheckSection(_Section): 

121 """What the evaluator concluded (answers only).""" 

122 

123 key: Literal["quality_check"] = "quality_check" 

124 #: passed / revised / failed / unavailable / skipped 

125 #: (``quality_check.Outcome``). 

126 outcome: str | None = None 

127 #: Uncalibrated; never a confidence. 

128 score: float | None = None 

129 critique: str | None = None 

130 gaps: list[str] = [] 

131 

132 

133class HumanInputSection(_Section): 

134 """Every time the turn stopped for a person, and what they said.""" 

135 

136 key: Literal["human_input"] = "human_input" 

137 #: ``hitl.exchange`` records: what was asked or held, the answer, who 

138 #: gave it and when. 

139 exchanges: list[dict[str, Any]] = [] 

140 #: A pause still waiting for an answer. 

141 pending: dict[str, Any] | None = None 

142 

143 

144class ReviewsSection(_Section): 

145 """What a person was asked to look at, and what they decided.""" 

146 

147 key: Literal["reviews"] = "reviews" 

148 flags: list[Schema.Review.Read] = [] 

149 

150 

151class RecordRead(BaseModel): 

152 """One read of this record by somebody other than its owner.""" 

153 

154 reader_user_id: UUID 

155 #: Their name, else their email; None when the account has gone. 

156 reader_name: str | None = None 

157 #: ``DecisionEnum.Access``: ``reviewer`` today. 

158 access: str 

159 #: The flag that let them in. 

160 flag_id: UUID | None = None 

161 read_at: UTCDateTime 

162 

163 

164class ReadsSection(_Section): 

165 """Who other than the owner has opened this record (``decision_reads``).""" 

166 

167 key: Literal["reads"] = "reads" 

168 reads: list[RecordRead] = [] 

169 

170 

171class OutcomeRead(BaseModel): 

172 """One verdict on the turn (``DecisionOutcome``).""" 

173 

174 id: UUID 

175 #: ``DecisionEnum.Verdict``: accepted, edited or rejected. 

176 verdict: str 

177 corrected_text: str | None = None 

178 label: str | None = None 

179 note: str | None = None 

180 #: ``DecisionEnum.OutcomeSource``: on the answer, or resolving a review. 

181 source: str 

182 review_flag_id: UUID | None = None 

183 actor_user_id: UUID 

184 #: Their name, else their email; None when the account has gone. 

185 actor_name: str | None = None 

186 created_at: UTCDateTime 

187 

188 class Config: 

189 from_attributes = True 

190 

191 

192class CaseRef(BaseModel): 

193 """A dataset case made from this turn ("Add to dataset").""" 

194 

195 case_id: UUID 

196 test_suite_id: UUID 

197 test_suite_name: str | None = None 

198 created_at: UTCDateTime | None = None 

199 

200 

201class OutcomeSection(_Section): 

202 """What a person said of the answer, and what became of it.""" 

203 

204 key: Literal["outcome"] = "outcome" 

205 #: The turn's verdict: the newest. 

206 current: OutcomeRead | None = None 

207 #: Every verdict, oldest first — a changed mind is a new one. 

208 history: list[OutcomeRead] = [] 

209 #: The dataset cases made from it. 

210 cases: list[CaseRef] = [] 

211 

212 

213class LaneStep(BaseModel): 

214 """What one knowledge lane did (svc-ai's lane frame, and the join's 

215 packing of it): counts only, never what a passage said.""" 

216 

217 #: The kind of knowledge it searched (``app/util/knowledge_categories.py``). 

218 category: str 

219 #: Its role in the turn's knowledge mix: primary, supporting or method. 

220 role: str = "" 

221 knowledge_bases: int = 0 

222 queries: int = 0 

223 found: int = 0 

224 #: Passages its relevance judge was shown. 

225 judged: int = 0 

226 ruled_out: int = 0 

227 out_of_window: int = 0 

228 handed_on: int = 0 

229 #: What the join packed of it; None when the trace does not say. 

230 packed: int | None = None 

231 #: Its judge failed, or its search did (one line each). 

232 judge_failure: str | None = None 

233 failure: str | None = None 

234 

235 

236class Step(BaseModel): 

237 node_id: str 

238 #: ``system`` for the platform's own nodes (``__gate__`` …), else 

239 #: ``node`` — the agent's, or a skill's. 

240 kind: str 

241 model_name: str | None = None 

242 provider: str | None = None 

243 input_tokens: int | None = None 

244 output_tokens: int | None = None 

245 duration_ms: int | None = None 

246 error: bool = False 

247 output_preview: str | None = None 

248 #: Names of the tools the step called, in order. 

249 tools: list[str] = [] 

250 #: Earlier turns of the conversation its model could not be sent — 

251 #: fitted to the model's window and price tier (svc-ai 

252 #: ``token_budget``). None when it was sent them all. 

253 history_turns_omitted: int | None = None 

254 #: A knowledge lane's step: its kind, role and what it found and packed. 

255 lane: LaneStep | None = None 

256 

257 

258class StepsSection(_Section): 

259 """The nodes the turn ran through, in order.""" 

260 

261 key: Literal["steps"] = "steps" 

262 steps: list[Step] = [] 

263 

264 

265class ModelCall(BaseModel): 

266 """One model call, as svc-ai metered it.""" 

267 

268 provider: str 

269 model_name: str 

270 model_display_name: str | None = None 

271 node: str | None = None 

272 #: ``chat`` or ``embedding``. 

273 kind: str = "chat" 

274 #: What the traced invocation was for (agent, skill, evaluation …). 

275 purpose: str | None = None 

276 prompt_tokens: int = 0 

277 completion_tokens: int = 0 

278 cache_read_tokens: int = 0 

279 cache_write_tokens: int = 0 

280 reasoning_tokens: int = 0 

281 latency_ms: int | None = None 

282 status: str 

283 error_detail: str | None = None 

284 #: None when the call could not be priced — never 0 for that. 

285 estimated_cost_usd: float | None = None 

286 

287 

288class ModelCallsSection(_Section): 

289 key: Literal["model_calls"] = "model_calls" 

290 calls: list[ModelCall] = [] 

291 

292 

293class Citation(BaseModel): 

294 index: int 

295 source_type: str 

296 source: str 

297 title: str 

298 collection: str | None = None 

299 relevance_score: float | None = None 

300 

301 

302class ToolCall(BaseModel): 

303 tool_name: str 

304 created_at: UTCDateTime | None = None 

305 input_args: dict[str, Any] | None = None 

306 output: str | None = None 

307 #: The output was cut for the record (svc-ai ``TOOL_OUTPUT_CHARS``). 

308 truncated: bool = False 

309 latency_ms: int | None = None 

310 status: str 

311 error_detail: str | None = None 

312 citations: list[Citation] = [] 

313 #: A web search's report (``app/util/web_search_report.py``). 

314 report: dict[str, Any] | None = None 

315 

316 

317class ToolCallsSection(_Section): 

318 key: Literal["tool_calls"] = "tool_calls" 

319 calls: list[ToolCall] = [] 

320 

321 

322class LedgerEntry(BaseModel): 

323 """One ``governance_usage`` row: a segment's spend, as the ledger 

324 counted it against quotas and cost cards.""" 

325 

326 occurred_at: UTCDateTime | None = None 

327 execution_type: str | None = None 

328 outcome: str 

329 input_tokens: int = 0 

330 output_tokens: int = 0 

331 estimated_cost_usd: float | None = None 

332 llm_calls: int = 0 

333 unpriced_calls: int = 0 

334 latency_ms: int | None = None 

335 

336 

337class CostSection(_Section): 

338 key: Literal["cost"] = "cost" 

339 entries: list[LedgerEntry] = [] 

340 #: The priced part; a lower bound when ``complete`` is false. 

341 cost_usd: float | None = None 

342 #: Every call on every entry was priced. 

343 complete: bool = True 

344 input_tokens: int = 0 

345 output_tokens: int = 0 

346 

347 

348DecisionSection = Annotated[ 

349 Union[ 

350 RequestSection, 

351 AnswerSection, 

352 ConfigurationSection, 

353 RulesSection, 

354 WebSourcesSection, 

355 QualityCheckSection, 

356 HumanInputSection, 

357 ReviewsSection, 

358 OutcomeSection, 

359 StepsSection, 

360 ModelCallsSection, 

361 ToolCallsSection, 

362 CostSection, 

363 ReadsSection, 

364 ], 

365 Field(discriminator="key"), 

366] 

367 

368 

369class DecisionRead(BaseModel): 

370 """One governed turn, everything it recorded, in one place.""" 

371 

372 #: The turn's ``invocation_id``. 

373 id: UUID 

374 kind: DecisionEnum.Kind 

375 #: How the reader may read it: their own turn, or one flagged for them 

376 #: to review. 

377 access: DecisionEnum.Access = DecisionEnum.Access.owner 

378 #: The agent, model or skill that answered, by name. 

379 subject: str | None = None 

380 #: The answer's or the run's status. 

381 status: str 

382 started_at: UTCDateTime | None = None 

383 finished_at: UTCDateTime | None = None 

384 conversation_id: UUID | None = None 

385 #: The answer's message (the assistant's). 

386 message_id: UUID | None = None 

387 agent_id: UUID | None = None 

388 ai_model_id: UUID | None = None 

389 skill_id: UUID | None = None 

390 skill_run_id: UUID | None = None 

391 #: For a swarm task: the run it belongs to, and the task. 

392 swarm_run_id: UUID | None = None 

393 swarm_task_id: UUID | None = None 

394 sections: list[DecisionSection] = [] 

395 

396 

397class OutcomeCreate(BaseModel): 

398 """A verdict on the turn. ``corrected_text`` is the answer as it should 

399 have been, and is required for ``edited``.""" 

400 

401 verdict: DecisionEnum.Verdict 

402 corrected_text: str | None = None 

403 #: The business outcome ("refund issued"), free text. 

404 label: str | None = None 

405 note: str | None = None 

406 

407 

408class CaseCreate(BaseModel): 

409 """Add the turn to a dataset as a case.""" 

410 

411 test_suite_id: UUID 

412 #: Redact personal data from the question, the answer and the 

413 #: conversation before the case is written. On unless turned off. 

414 redact_pii: bool = True 

415 

416 

417class CaseCreated(BaseModel): 

418 case: Schema.TestCase.Read 

419 #: Values redacted, by kind of personal data. 

420 redacted: dict[str, int] = {}