Coverage for app / services / web_search_summary.py: 100%

139 statements  

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

1"""A turn's web searches, read back: what they came to, and what each of the 

2turn's Tools rules did to them. 

3 

4svc-ai's ``web_search`` keeps a report of every call 

5(``app/util/web_search_report.py``); svc-core captures them from the raw 

6stream or the batch response (``ai_client.UsageCapture.web_searches``). 

7Two things are read from them here: 

8 

9- **The turn's summary** (:func:`summarise`), stored on the answer as 

10 ``meta.web_search`` and sent on the chat's ``response`` frame: one outcome 

11 for the turn (:class:`TurnOutcome`), what the engines failed with, what 

12 each check removed, and per Tools rule what it did — the hosts it left out 

13 or put first, unless the answer may yet be withheld (``held``). 

14- **Each Tools rule, settled** (:func:`settle`). A Tools rule's action sets 

15 the run's web sources and so read "applied" on every turn it governed, 

16 whether or not a search ever met it. Settled after the run, it stays 

17 ``applied`` only when it changed a search — left a result out, limited a 

18 query to its sources, left no source at all, or put a source first — and 

19 is ``no_change`` otherwise. Its activity detail gains counts 

20 (``detail[action]["web"]``), never a host: the activity log names the 

21 rule's own words, not what the turn read. 

22 

23Which rule a removal belongs to is read from the hosts: a host a blocking 

24rule's domains cover is that rule's; a host outside an only-these rule's is 

25that rule's. A removal no named host explains (a search names at most ten) 

26goes to every rule of its kind. 

27 

28Not settled yet: skill runs, evaluation cells and dashboard tiles, whose 

29Tools rows keep reading "applied". ``url_fetch`` keeps no report, so a page 

30a rule refused to read does not count as the rule acting. 

31""" 

32 

33from __future__ import annotations 

34 

35from collections import Counter 

36from collections.abc import Iterable, Sequence 

37from dataclasses import dataclass, field 

38from enum import StrEnum 

39from typing import Any 

40 

41from app.db.postgres.enums import GovernanceEnum, RuleEnum 

42from app.util import web_domains 

43from app.util.web_search_report import ( 

44 MAX_HOSTS, 

45 AttemptOutcome, 

46 Removal, 

47 ScopedTo, 

48 SearchOutcome, 

49 SearchReport, 

50) 

51 

52#: The summary's shape on a message's meta. 

53VERSION = 1 

54 

55#: The Tools actions, by type. 

56TRUSTED = "trusted_sources" 

57BLOCKED = "blocked_sources" 

58TOOLS_ACTIONS = (TRUSTED, BLOCKED) 

59 

60 

61class TurnOutcome(StrEnum): 

62 """What a turn's web searches came to, the strongest first: the rules 

63 left no source; the rules narrowed a search; a search found something; 

64 no engine could answer; nothing usable came back.""" 

65 

66 closed = "closed" 

67 limited = "limited" 

68 found = "found" 

69 unavailable = "unavailable" 

70 empty = "empty" 

71 

72 

73@dataclass(frozen=True) 

74class ToolsRule: 

75 """One Tools action of a rule the turn ran under, as its evaluation 

76 recorded it.""" 

77 

78 rule_id: str | None 

79 rule: str | None 

80 action: str 

81 domains: frozenset[str] 

82 only: bool = False 

83 

84 

85@dataclass 

86class Effect: 

87 """What one Tools action did to the turn's searches.""" 

88 

89 searches: int = 0 

90 #: Searches it changed: a result left out, the query limited to its 

91 #: sources, or no source left. 

92 narrowed: int = 0 

93 closed: bool = False 

94 left_out: list[str] = field(default_factory=list) 

95 put_first: list[str] = field(default_factory=list) 

96 

97 @property 

98 def acted(self) -> bool: 

99 return self.narrowed > 0 or bool(self.put_first) 

100 

101 def counts(self) -> dict[str, Any]: 

102 """What the activity log keeps of it: counts, never a host.""" 

103 return { 

104 "searches": self.searches, 

105 "narrowed": self.narrowed, 

106 "left_out": len(self.left_out), 

107 "put_first": len(self.put_first), 

108 **({"closed": True} if self.closed else {}), 

109 } 

110 

111 

112def _value(item: Any) -> str: 

113 return str(getattr(item, "value", item) or "") 

114 

115 

116def tools_rules(evaluations: Iterable[dict[str, Any]] | None) -> list[ToolsRule]: 

117 """The Tools actions among a turn's rule evaluations (``RulePass 

118 .evaluations`` or activity rows read as dicts), that ran: a rule whose 

119 conditions did not hold set no source.""" 

120 found: list[ToolsRule] = [] 

121 for evaluation in evaluations or []: 

122 if _value(evaluation.get("layer")) != RuleEnum.Layer.tools.value: 

123 continue 

124 if ( 

125 _value(evaluation.get("outcome")) 

126 == GovernanceEnum.Outcome.not_matched.value 

127 ): 

128 continue 

129 detail = evaluation.get("detail") or {} 

130 for action in TOOLS_ACTIONS: 

131 block = detail.get(action) 

132 if not isinstance(block, dict): 

133 continue 

134 found.append( 

135 ToolsRule( 

136 rule_id=( 

137 str(evaluation["rule_id"]) 

138 if evaluation.get("rule_id") 

139 else None 

140 ), 

141 rule=evaluation.get("rule"), 

142 action=action, 

143 domains=frozenset( 

144 web_domains.normalise_domains(block.get("domains")) 

145 ), 

146 only=bool(block.get("only")) if action == TRUSTED else False, 

147 ) 

148 ) 

149 return found 

150 

151 

152def _add(hosts: list[str], new: Iterable[str]) -> None: 

153 for host in new: 

154 if host not in hosts and len(hosts) < MAX_HOSTS: 

155 hosts.append(host) 

156 

157 

158def effects( 

159 rules: Sequence[ToolsRule], reports: Sequence[SearchReport] 

160) -> list[Effect]: 

161 """What each of ``rules`` did to ``reports``, in the same order.""" 

162 out = [Effect(searches=len(reports)) for _ in rules] 

163 blocking = [i for i, r in enumerate(rules) if r.action == BLOCKED] 

164 limiting = [i for i, r in enumerate(rules) if r.action == TRUSTED and r.only] 

165 for report in reports: 

166 changed: set[int] = set() 

167 # Ruled out: the hosts each blocking rule's domains cover. 

168 blocked = [o.host for o in report.left_out if o.by is Removal.rules_blocked] 

169 explained = False 

170 for i in blocking: 

171 mine = [h for h in blocked if web_domains.covered(h, rules[i].domains)] 

172 if mine: 

173 _add(out[i].left_out, mine) 

174 changed.add(i) 

175 explained = True 

176 if report.removed_by(Removal.rules_blocked) and not explained: 

177 changed.update(blocking) 

178 # Outside the only sources allowed: the hosts each limiting rule's 

179 # domains leave out; a query limited to them, a refusal, or no 

180 # source left is every limiting rule's doing. 

181 outside = [o.host for o in report.left_out if o.by is Removal.rules_not_allowed] 

182 explained = False 

183 for i in limiting: 

184 mine = [h for h in outside if not web_domains.covered(h, rules[i].domains)] 

185 if mine: 

186 _add(out[i].left_out, mine) 

187 changed.add(i) 

188 explained = True 

189 if ( 

190 (report.removed_by(Removal.rules_not_allowed) and not explained) 

191 or report.scoped_to is ScopedTo.rules 

192 or report.outcome is SearchOutcome.closed 

193 ): 

194 changed.update(limiting) 

195 if report.outcome is SearchOutcome.closed: 

196 for i in limiting: 

197 out[i].closed = True 

198 # Put first: the kept hosts each trusting rule's domains cover. 

199 for i, rule in enumerate(rules): 

200 if rule.action == TRUSTED: 

201 _add( 

202 out[i].put_first, 

203 ( 

204 h 

205 for h in report.put_first 

206 if web_domains.covered(h, rule.domains) 

207 ), 

208 ) 

209 for i in changed: 

210 out[i].narrowed += 1 

211 return out 

212 

213 

214def outcome(reports: Sequence[SearchReport]) -> TurnOutcome: 

215 """The turn's web outcome (:class:`TurnOutcome`). A search that found 

216 something outweighs one whose engines failed: the answer had material.""" 

217 if any(r.outcome is SearchOutcome.closed for r in reports): 

218 return TurnOutcome.closed 

219 if any(r.narrowed_by_rules for r in reports): 

220 return TurnOutcome.limited 

221 if any(r.outcome is SearchOutcome.found for r in reports): 

222 return TurnOutcome.found 

223 if any(r.outcome is SearchOutcome.unavailable for r in reports): 

224 return TurnOutcome.unavailable 

225 return TurnOutcome.empty 

226 

227 

228def summarise( 

229 reports: Sequence[SearchReport], 

230 evaluations: Iterable[dict[str, Any]] | None = None, 

231 *, 

232 held: bool = False, 

233) -> dict[str, Any] | None: 

234 """The turn's web searches for its answer (``meta.web_search``), or None 

235 when it made none. ``held``: the answer may yet be withheld, so no host 

236 is named — counts only.""" 

237 if not reports: 

238 return None 

239 rules = tools_rules(evaluations) 

240 failures: Counter[str] = Counter() 

241 removed: Counter[str] = Counter() 

242 for report in reports: 

243 for attempt in report.attempts: 

244 if attempt.outcome is AttemptOutcome.failed: 

245 failures[attempt.reason or "error"] += 1 

246 for kind, count in report.removed.items(): 

247 if count: 

248 removed[kind] += int(count) 

249 return { 

250 "version": VERSION, 

251 "outcome": outcome(reports).value, 

252 "searches": len(reports), 

253 "found": sum(1 for r in reports if r.outcome is SearchOutcome.found), 

254 "kept": sum(r.kept for r in reports), 

255 "failures": dict(failures), 

256 "removed": dict(removed), 

257 "rules": [ 

258 { 

259 "rule_id": rule.rule_id, 

260 "rule": rule.rule, 

261 "action": rule.action, 

262 "only": rule.only, 

263 # The rule's own words, as its activity row keeps them. 

264 "domains": sorted(rule.domains), 

265 "acted": effect.acted, 

266 "narrowed": effect.narrowed, 

267 "closed": effect.closed, 

268 "left_out_count": len(effect.left_out), 

269 "put_first_count": len(effect.put_first), 

270 **( 

271 {} 

272 if held 

273 else {"left_out": effect.left_out, "put_first": effect.put_first} 

274 ), 

275 } 

276 for rule, effect in zip(rules, effects(rules, reports)) 

277 ], 

278 } 

279 

280 

281def settle( 

282 evaluations: Iterable[dict[str, Any]] | None, 

283 reports: Sequence[SearchReport], 

284) -> list[dict[str, Any]]: 

285 """``evaluations`` with each Tools rule that ran settled on the turn's 

286 searches: ``applied`` only when it changed one, ``no_change`` 

287 otherwise, its detail's action blocks gaining ``web`` counts. Every 

288 other evaluation is returned as it was.""" 

289 settled: list[dict[str, Any]] = [] 

290 for evaluation in evaluations or []: 

291 rules = tools_rules([evaluation]) 

292 if not rules: 

293 settled.append(evaluation) 

294 continue 

295 acted = False 

296 detail = dict(evaluation.get("detail") or {}) 

297 for rule, effect in zip(rules, effects(rules, reports)): 

298 detail[rule.action] = { 

299 **detail.get(rule.action, {}), 

300 "web": effect.counts(), 

301 } 

302 acted = acted or effect.acted 

303 settled.append( 

304 { 

305 **evaluation, 

306 "outcome": ( 

307 GovernanceEnum.Outcome.applied 

308 if acted 

309 else GovernanceEnum.Outcome.no_change 

310 ), 

311 "detail": detail, 

312 } 

313 ) 

314 return settled 

315 

316 

317def settled_changes( 

318 before: Iterable[dict[str, Any]], after: Iterable[dict[str, Any]] 

319) -> dict[str, dict[str, Any]]: 

320 """The Tools rules :func:`settle` changed, by rule id: their outcome and 

321 detail, for the activity rows the turn already wrote 

322 (``governance_activity.settle_tools``).""" 

323 changes: dict[str, dict[str, Any]] = {} 

324 for old, new in zip(before, after): 

325 if old is new or not new.get("rule_id"): 

326 continue 

327 changes[str(new["rule_id"])] = { 

328 "outcome": new["outcome"], 

329 "detail": new.get("detail") or {}, 

330 } 

331 return changes 

332 

333 

334__all__ = [ 

335 "BLOCKED", 

336 "TOOLS_ACTIONS", 

337 "TRUSTED", 

338 "VERSION", 

339 "Effect", 

340 "ToolsRule", 

341 "TurnOutcome", 

342 "effects", 

343 "outcome", 

344 "settle", 

345 "settled_changes", 

346 "summarise", 

347 "tools_rules", 

348]