Coverage for app / services / knowledge / recommendations / upkeep.py: 91%
132 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"""Recommendations from how knowledge is kept: a website source read more or
2less often than its kind wants, the same documents held twice, a repository
3whose sources are all dated, and one holding sources of another kind.
4"""
6from __future__ import annotations
8from sqlalchemy import text
10from app.db.postgres.models import Knowledge
11from app.services.knowledge import repositories, web_config
12from app.services.knowledge.recommendations.base import (
13 Action,
14 Example,
15 Figure,
16 Flow,
17 Prefill,
18 Recommendation,
19 RecommendationKind,
20 Section,
21 Subject,
22 SubjectKind,
23 Touches,
24 band,
25 fingerprint,
26 plural,
27 register_kind,
28)
29from app.services.knowledge.recommendations.context import RecommendationContext
30from app.services.knowledge.source_map.evidence import SAME_DOCUMENT_SQL
31from app.util import knowledge_categories
32from app.util.knowledge_categories import KnowledgeCategory
34#: Documents two sources share before they read as holding the same thing.
35MIN_SHARED = 3
36#: The pairs recommended at once: those sharing the most.
37MAX_PAIRS = 10
39Cadence = web_config.RefreshCadence
41#: The cadences a kind reads too often, and what it would rather keep:
42#: reference material rarely changes by the hour, and a framework is read
43#: again when somebody changes it.
44TOO_OFTEN: dict[KnowledgeCategory, tuple[frozenset[str], Cadence]] = {
45 KnowledgeCategory.domain: (frozenset({Cadence.hourly.value}), Cadence.weekly),
46 KnowledgeCategory.reasoning: (
47 frozenset({Cadence.hourly.value, Cadence.daily.value}),
48 Cadence.manual,
49 ),
50}
53def _label(category: KnowledgeCategory) -> str:
54 return knowledge_categories.LABELS[category]
57@register_kind
58class RefreshForItsKind(RecommendationKind):
59 key = "refresh_for_its_kind"
60 section = Section.upkeep
61 label = "Read more or less often than its kind wants"
62 description = (
63 "A website source's refresh, or the window of pages it keeps, does not "
64 "suit the kind of knowledge it is held as."
65 )
67 def find(self, ctx: RecommendationContext) -> list[Recommendation]:
68 out = []
69 for knowledge_id, source in ctx.sources.items():
70 if source.source_type != "web":
71 continue
72 try:
73 config = web_config.parse_web_config(source.source_config)
74 except ValueError:
75 continue
76 category = ctx.category_of(knowledge_id)
77 cadence = config.refresh.value
78 refresh: str | None = None
79 window: int | None = None
80 reasons = []
81 if category is KnowledgeCategory.temporal:
82 wanted = web_config.refresh_for(category, cadence)
83 if wanted != cadence:
84 refresh = wanted
85 reasons.append(
86 f"it is read {cadence}, and dated knowledge goes out of "
87 f"date unless it is read at least {wanted}"
88 )
89 if config.max_age_days is None:
90 window = web_config.TEMPORAL_MAX_AGE_DAYS
91 reasons.append(
92 "it keeps every page it has read, where dated knowledge "
93 f"keeps the last {window} days"
94 )
95 elif category in TOO_OFTEN:
96 often, wanted = TOO_OFTEN[category]
97 if cadence in often:
98 refresh = wanted.value
99 reasons.append(
100 f"it is read {cadence}, and {_label(category).lower()} "
101 f"knowledge changes seldom enough to read "
102 + (
103 "when it changes"
104 if wanted is Cadence.manual
105 else wanted.value
106 )
107 )
108 if not reasons:
109 continue
110 changes = []
111 if refresh:
112 changes.append(f"refresh {refresh}")
113 if window:
114 changes.append(f"keep {window} days")
115 out.append(
116 self.recommendation(
117 subject=Subject(
118 SubjectKind.knowledge, str(knowledge_id), source.name
119 ),
120 title=(
121 f"{source.name} is not kept as {_label(category).lower()} "
122 "knowledge is"
123 ),
124 why=(
125 f"It is held as {_label(category)} knowledge, and "
126 + "; ".join(reasons)
127 + "."
128 ),
129 figures=(),
130 examples=(),
131 actions=(
132 Action(
133 Flow.edit_source,
134 "Change its settings: " + ", ".join(changes),
135 Prefill(
136 knowledge_id=knowledge_id,
137 knowledge_name=source.name,
138 category=category.value,
139 refresh=refresh,
140 max_age_days=window,
141 ),
142 ),
143 ),
144 fingerprint=fingerprint(
145 category.value, cadence, config.max_age_days
146 ),
147 touches=Touches(
148 sources=frozenset({knowledge_id}),
149 repositories=ctx.holders(knowledge_id),
150 ),
151 )
152 )
153 return out
156@register_kind
157class SameDocuments(RecommendationKind):
158 key = "same_documents"
159 section = Section.upkeep
160 label = "The same documents in two sources"
161 description = (
162 "Two sources hold the same documents or pages (the same address, or a "
163 "file with the same bytes): indexed twice, searched twice, and each "
164 "passage can come back twice."
165 )
167 def find(self, ctx: RecommendationContext) -> list[Recommendation]:
168 ids = [k for k, s in ctx.sources.items() if s.source_type in ("file", "web")]
169 if len(ids) < 2:
170 return []
171 rows = ctx.db.execute(
172 text(SAME_DOCUMENT_SQL),
173 {"ids": [str(i) for i in ids], "members": [str(i) for i in ids]},
174 ).all()
175 shared = sorted(
176 (
177 r
178 for r in rows
179 if int(r.n) >= MIN_SHARED and r.a in ctx.sources and r.b in ctx.sources
180 ),
181 key=lambda r: (-int(r.n), str(r.a), str(r.b)),
182 )[:MAX_PAIRS]
183 out = []
184 for row in shared:
185 a: Knowledge = ctx.sources[row.a]
186 b: Knowledge = ctx.sources[row.b]
187 n = int(row.n)
188 out.append(
189 self.recommendation(
190 subject=Subject(
191 SubjectKind.pair, f"{a.id}|{b.id}", f"{a.name} and {b.name}"
192 ),
193 title=f"{a.name} and {b.name} hold {plural(n, 'document')} in common",
194 why=(
195 "Held twice, they are indexed and searched twice, and a "
196 "passage can reach an answer twice. Keeping them in one "
197 "source halves both."
198 ),
199 figures=(Figure("Documents in both", n),),
200 examples=tuple(
201 Example(text=str(label)) for label in (row.labels or [])[:3]
202 ),
203 actions=tuple(
204 Action(
205 Flow.open_source,
206 f"Review {source.name}",
207 Prefill(
208 knowledge_id=source.id,
209 knowledge_name=source.name,
210 tab="content",
211 ),
212 )
213 for source in (a, b)
214 ),
215 fingerprint=fingerprint(band(n)),
216 touches=Touches(
217 sources=frozenset({a.id, b.id}),
218 repositories=ctx.holders(a.id) | ctx.holders(b.id),
219 ),
220 weight=n,
221 )
222 )
223 return out
226def _member_sources(ctx: RecommendationContext, ids: list) -> list[Knowledge]:
227 """A repository's member sources, built-ins included."""
228 known = [ctx.sources[i] for i in ids if i in ctx.sources]
229 missing = [i for i in ids if i not in ctx.sources]
230 if missing:
231 known += ctx.db.query(Knowledge).filter(Knowledge.id.in_(missing)).all()
232 return known
235def _keeps_a_window(source: Knowledge) -> bool:
236 if source.source_type != "web":
237 return False
238 try:
239 return (
240 web_config.parse_web_config(source.source_config).max_age_days is not None
241 )
242 except ValueError:
243 return False
246@register_kind
247class LooksDated(RecommendationKind):
248 key = "looks_dated"
249 section = Section.upkeep
250 label = "Dated knowledge held as reference"
251 description = (
252 "Every source in a Domain repository keeps a rolling window of pages, "
253 "as dated knowledge does: as Temporal, it is read newest first."
254 )
256 def find(self, ctx: RecommendationContext) -> list[Recommendation]:
257 out = []
258 for repository_id, repository in ctx.repositories.items():
259 if (
260 knowledge_categories.of(repository.category)
261 is not KnowledgeCategory.domain
262 ):
263 continue
264 ids = ctx.members.get(repository_id, [])
265 if not ids:
266 continue
267 members = _member_sources(ctx, ids)
268 if not members or not all(_keeps_a_window(m) for m in members):
269 continue
270 if not repositories.may_become(
271 ctx.db, repository_id, KnowledgeCategory.temporal, ids
272 ):
273 continue
274 out.append(
275 self.recommendation(
276 subject=Subject(
277 SubjectKind.repository, str(repository_id), repository.name
278 ),
279 title=f"{repository.name} holds only dated pages",
280 why=(
281 f"Each of its {plural(len(members), 'source')} keeps a "
282 "rolling window of pages, as dated knowledge does. Held as "
283 "Temporal, it is read newest first and kept to the "
284 "question's time window."
285 ),
286 figures=(Figure("Sources keeping a window", len(members)),),
287 examples=(),
288 actions=(
289 Action(
290 Flow.edit_repository,
291 "Make it Temporal",
292 Prefill(
293 repository_id=repository_id,
294 repository_name=repository.name,
295 category=KnowledgeCategory.temporal.value,
296 ),
297 ),
298 ),
299 fingerprint=fingerprint(len(members)),
300 touches=Touches(
301 repositories=frozenset({repository_id}),
302 sources=frozenset(ids),
303 ),
304 )
305 )
306 return out
309@register_kind
310class MixedKinds(RecommendationKind):
311 key = "mixed_kinds"
312 section = Section.upkeep
313 label = "Sources of another kind"
314 description = (
315 "A repository holds sources also held as another kind of knowledge, "
316 "stored before a source could be one kind only. They are read as "
317 "Domain until they are."
318 )
320 def find(self, ctx: RecommendationContext) -> list[Recommendation]:
321 all_ids = [i for ids in ctx.members.values() for i in ids]
322 if not all_ids:
323 return []
324 held = repositories._held_as(ctx.db, all_ids)
325 out = []
326 for repository_id, repository in ctx.repositories.items():
327 ids = ctx.members.get(repository_id, [])
328 own = knowledge_categories.of(repository.category)
329 mixed = [i for i in ids if held.get(i, set()) - {own}]
330 if not mixed:
331 continue
332 others = sorted(
333 {_label(k) for i in mixed for k in held.get(i, set()) - {own}}
334 )
335 out.append(
336 self.recommendation(
337 subject=Subject(
338 SubjectKind.repository, str(repository_id), repository.name
339 ),
340 title=f"{repository.name} holds sources of another kind",
341 why=(
342 f"{len(mixed):,} of its sources "
343 f"{'is' if len(mixed) == 1 else 'are'} also held as "
344 f"{' and '.join(others)} knowledge, so they are read as "
345 "Domain. Keep each in repositories of one kind."
346 ),
347 figures=(Figure("Sources of another kind", len(mixed)),),
348 examples=(),
349 actions=(
350 Action(
351 Flow.open_repository,
352 "Review its sources",
353 Prefill(
354 repository_id=repository_id,
355 repository_name=repository.name,
356 tab="sources",
357 ),
358 ),
359 ),
360 fingerprint=fingerprint(len(mixed), *others),
361 touches=Touches(
362 repositories=frozenset({repository_id}),
363 sources=frozenset(ids),
364 ),
365 weight=len(mixed),
366 )
367 )
368 return out
371__all__ = ["LooksDated", "MixedKinds", "RefreshForItsKind", "SameDocuments"]