Coverage for app / util / web_search_report.py: 99%
93 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""What one web search did, as a record — the report the ``web_search`` tool
2keeps beside the text it gives the model.
4The model reads the tool's text (``tools/web/search.py``). Everything else
5reads this: the chat trace, the turn's summary on the answer
6(``meta.web_search``), the decision record, and the settling of the turn's
7Tools rules, which stay "applied" only when one changed a search. Before it
8existed, nothing kept what a search returned, what was removed and why, or
9which engine failed: an answer saying "no results matched the safety and
10domain criteria" (25 October 2026) could not be checked against anything.
12svc-ai writes it (the tool's artifact, never shown to a model); svc-core
13reads it. The two services carry this file byte for byte
14(``tools/test_shared_modules.py``), so a field one writes is a field the
15other reads. A report from a later version reads as far as it can: unknown
16fields are ignored, and a value outside a vocabulary makes it unreadable
17(None), never a guess.
19It names no engine (``engine`` is ``primary`` or ``fallback``), carries no
20result's text and no URL: only hosts, and only the hosts the workspace's
21rules removed or put first, or that the platform's own sources put first
22for CHAINR Bot (at most :data:`MAX_HOSTS` each), which
23:meth:`SearchReport.without_hosts` drops for a turn whose answer may yet be
24withheld.
25"""
27from __future__ import annotations
29from enum import StrEnum
30from typing import Any
32from pydantic import BaseModel, ConfigDict, Field, ValidationError
34#: The report's shape. A reader keeps what it understands of a later one.
35VERSION = 1
37#: The hosts a report names as left out, and as put first, at most.
38MAX_HOSTS = 10
41class SearchOutcome(StrEnum):
42 """What a call to the tool came to."""
44 #: Results went back to the model.
45 found = "found"
46 #: The engines answered, and nothing could be used: none came back, or
47 #: every one was removed.
48 empty = "empty"
49 #: No engine could answer.
50 unavailable = "unavailable"
51 #: The workspace's rules leave no web source at all.
52 closed = "closed"
53 #: Every domain the call asked for is outside what may be used.
54 refused = "refused"
55 #: The tool's calls for the run were used up.
56 call_limit = "call_limit"
57 #: The tool could not be set up (no engine configured).
58 misconfigured = "misconfigured"
61class Removal(StrEnum):
62 """What removed a result (svc-ai's ``DomainPolicy.verdict``, permitted
63 aside)."""
65 #: Link shorteners, disposable domains, pages without HTTPS.
66 safety = "safety"
67 #: The tool's own configured sites.
68 tool_config = "tool_config"
69 #: A source the workspace's Tools rules rule out.
70 rules_blocked = "rules_blocked"
71 #: A source outside the only ones the workspace's rules allow.
72 rules_not_allowed = "rules_not_allowed"
73 #: A site outside the ``domains`` the call asked for.
74 not_requested = "not_requested"
77#: The removals that are the workspace's rules acting.
78RULE_REMOVALS = frozenset({Removal.rules_blocked, Removal.rules_not_allowed})
81class Engine(StrEnum):
82 """Which engine was asked: the first, or one after it. Never its name."""
84 primary = "primary"
85 fallback = "fallback"
88class AttemptOutcome(StrEnum):
89 """What asking one engine came to (svc-ai's ``AttemptOutcome``)."""
91 answered = "answered"
92 empty = "empty"
93 failed = "failed"
94 #: Not asked: the call ran out of time first.
95 skipped = "skipped"
98class ScopedTo(StrEnum):
99 """Whose domains a call's query was limited to (``site:``), or refused
100 by when none was left."""
102 #: The domains the model passed.
103 call = "call"
104 #: The only sources the workspace's rules allow.
105 rules = "rules"
106 #: The tool's configured allowlist.
107 config = "config"
110class SourcesSetBy(StrEnum):
111 """Who chose the sources a search put first."""
113 #: The workspace's Tools rules (``trusted_sources``).
114 rules = "rules"
115 #: CHAIN-R, for its own agent (CHAINR Bot's preferred sources), where
116 #: no workspace rule chose any.
117 platform = "platform"
120class _Record(BaseModel):
121 model_config = ConfigDict(extra="ignore", frozen=True)
124class Attempt(_Record):
125 """One engine asked for one search."""
127 engine: Engine
128 search_type: str
129 outcome: AttemptOutcome
130 #: Why it failed (svc-ai's ``FailureReason`` value), when it did.
131 reason: str | None = None
132 returned: int = 0
135class LeftOut(_Record):
136 """A host the workspace's rules removed from a search, and which way."""
138 host: str
139 by: Removal
142class SearchReport(_Record):
143 """One call to ``web_search``: what was asked of the engines, what they
144 said, and what each check did with what came back."""
146 version: int = VERSION
147 #: The kind of search the call asked for.
148 search_type: str
149 #: The kind that gave the results, when not the one asked for: an empty
150 #: news search is tried once as a web search.
151 searched_as: str | None = None
152 freshness: str | None = None
153 outcome: SearchOutcome
154 attempts: list[Attempt] = Field(default_factory=list)
155 #: Results the engine that answered returned.
156 returned: int = 0
157 #: Results given to the model.
158 kept: int = 0
159 #: Results removed, by what removed them (:class:`Removal` values).
160 removed: dict[str, int] = Field(default_factory=dict)
161 #: Results that passed every check but did not fit the call's count.
162 not_shown: int = 0
163 #: Hosts the workspace's rules removed, in the engine's order.
164 left_out: list[LeftOut] = Field(default_factory=list)
165 #: Hosts of results given to the model that were put first — by the
166 #: rules, or the platform's own sources (``sources_set_by``).
167 put_first: list[str] = Field(default_factory=list)
168 scoped_to: ScopedTo | None = None
169 #: One more search ran, limited to the trusted sources, and found some.
170 trusted_search: bool = False
171 #: A date taken out of the query for the web search an empty news
172 #: search was tried as (``without_date``).
173 date_removed: str | None = None
174 #: Who set the sources put first, when any were.
175 sources_set_by: SourcesSetBy | None = None
176 #: Served from the tool's cache rather than an engine.
177 cached: bool = False
179 @classmethod
180 def read(cls, value: Any) -> SearchReport | None:
181 """``value`` as a report, or None when it is not one."""
182 if isinstance(value, cls):
183 return value
184 if not isinstance(value, dict):
185 return None
186 try:
187 report = cls.model_validate(value)
188 except ValidationError:
189 return None
190 return report
192 def removed_by(self, removal: Removal) -> int:
193 return int(self.removed.get(removal.value, 0) or 0)
195 @property
196 def removed_by_rules(self) -> int:
197 """Results the workspace's rules removed."""
198 return sum(self.removed_by(r) for r in RULE_REMOVALS)
200 @property
201 def narrowed_by_rules(self) -> bool:
202 """Whether the workspace's rules changed this search: they removed a
203 result, limited its query to their sources, or left no source."""
204 return (
205 self.removed_by_rules > 0
206 or self.scoped_to is ScopedTo.rules
207 or self.outcome is SearchOutcome.closed
208 )
210 def without_hosts(self) -> SearchReport:
211 """This report naming no host: for a turn whose answer a rule may
212 withhold, which keeps nothing of what the run read."""
213 return self.model_copy(update={"left_out": [], "put_first": []})
215 def wire(self) -> dict[str, Any]:
216 """This report as JSON travels: a frame, a column, a message's meta."""
217 return self.model_dump(mode="json")
220def reports(values: Any) -> list[SearchReport]:
221 """Every readable report among ``values`` (a list from a frame, a
222 response or a stored row), in order; anything else is skipped."""
223 if not isinstance(values, list):
224 return []
225 return [r for r in (SearchReport.read(v) for v in values) if r is not None]
228__all__ = [
229 "MAX_HOSTS",
230 "RULE_REMOVALS",
231 "VERSION",
232 "Attempt",
233 "AttemptOutcome",
234 "Engine",
235 "LeftOut",
236 "Removal",
237 "ScopedTo",
238 "SearchOutcome",
239 "SearchReport",
240 "SourcesSetBy",
241 "reports",
242]