Coverage for app / services / knowledge / source_map / evidence.py: 93%
153 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 can connect two knowledge sources: one class per kind of evidence.
3A connection on the source map is never drawn by hand. Each kind here reads
4one recorded fact two sources share — the same document in both, answers
5citing both, pages in one linking into the other's site, the same sites or
6publishers — and counts it. The count becomes a score with a saturating
7curve (``1 − exp(−count / tau)``: a little evidence counts, a lot does not
8count forever), and the kind's ``strength`` says how much a full score of it
9means. The builder combines a pair's kinds (``builder.combine``) into one
10weight, and every edge keeps each kind's count and a few examples, so it can
11say why it is there.
13Registered with :func:`register_evidence` and served as the map's legend, so
14adding a kind is one class. Each collects only pairs with at least one end
15in the repository: a pair of suggestions is no evidence about it.
17Semantic similarity (embeddings) is not a kind on purpose: sources may be
18embedded by different models, the edge could not show an example of why,
19and its centroids would need recomputing on every crawl.
20"""
22from __future__ import annotations
24import math
25from abc import ABC, abstractmethod
26from collections import defaultdict
27from dataclasses import dataclass, field
28from datetime import datetime
29from typing import Any
30from uuid import UUID
32from sqlalchemy import and_, func, or_, text
33from sqlalchemy.orm import Session, aliased
35from app.db.postgres.models import KnowledgeCitation, KnowledgeDocument
36from app.util import web_domains
39@dataclass(frozen=True)
40class Example:
41 """One instance of the evidence, as the map shows it."""
43 label: str
44 url: str | None = None
47@dataclass
48class PairEvidence:
49 """One kind of evidence between two sources: how much, and examples."""
51 a: UUID
52 b: UUID
53 kind: str
54 count: float
55 examples: list[Example] = field(default_factory=list)
58@dataclass
59class MapContext:
60 """What every kind reads: the sources, and the sites their content comes
61 from (``trust.source_hosts``)."""
63 db: Session
64 ws: Any
65 members: set[UUID]
66 #: Members and suggestion candidates together.
67 ids: list[UUID]
68 hosts: dict[UUID, frozenset[str]]
69 since: datetime
72def pair(a: UUID, b: UUID) -> tuple[UUID, UUID]:
73 """A pair in one order, so a → b and b → a are the same connection."""
74 return (a, b) if str(a) < str(b) else (b, a)
77class EvidenceKind(ABC):
78 key: str
79 label: str
80 description: str
81 #: What a full score of this kind means, 0–1.
82 strength: float
83 #: The count at which the score is ~63% of full.
84 tau: float
85 #: What the count counts, one and many ("document in both"), for a page
86 #: to say it in words; ``None`` where the count is a weighting, not a
87 #: tally, and the examples say it instead.
88 unit: tuple[str, str] | None = None
90 def score(self, count: float) -> float:
91 return 0.0 if count <= 0 else 1.0 - math.exp(-count / self.tau)
93 @abstractmethod
94 def collect(self, ctx: MapContext) -> list[PairEvidence]: ...
97_REGISTRY: dict[str, EvidenceKind] = {}
100def register_evidence(cls: type[EvidenceKind]) -> type[EvidenceKind]:
101 instance = cls()
102 if instance.key in _REGISTRY:
103 raise ValueError(f"Evidence kind {instance.key!r} registered twice")
104 _REGISTRY[instance.key] = instance
105 return cls
108def kinds() -> list[EvidenceKind]:
109 return list(_REGISTRY.values())
112def get_kind(key: str) -> EvidenceKind | None:
113 return _REGISTRY.get(key)
116def catalogue() -> list[dict[str, Any]]:
117 return [
118 {
119 "key": k.key,
120 "label": k.label,
121 "description": k.description,
122 "strength": k.strength,
123 "tau": k.tau,
124 "unit_one": k.unit[0] if k.unit else None,
125 "unit_many": k.unit[1] if k.unit else None,
126 }
127 for k in kinds()
128 ]
131def _touches(a: UUID, b: UUID, ctx: MapContext) -> bool:
132 return a in ctx.members or b in ctx.members
135# Written out whole rather than assembled from fragments, so nothing is
136# ever formatted into a statement; only bind parameters vary.
137#
138# A page's address is its ``source_url`` (an import) or, on a website
139# source, its ``source_id``. Two sources' copies of one page share it as a
140# key: lowercase, no scheme, no ``www.``, no fragment, no trailing slash.
141SAME_DOCUMENT_SQL = r"""
142WITH keyed AS (
143 SELECT d.knowledge_id, d.id AS document_id,
144 coalesce(d.document_metadata ->> 'title',
145 d.document_metadata ->> 'original_filename',
146 d.source_id) AS label,
147 coalesce(d.document_metadata ->> 'source_url',
148 CASE WHEN s.source_type = 'web' THEN d.source_id END) AS url,
149 k.key
150 FROM knowledge_documents d
151 JOIN knowledge s ON s.id = d.knowledge_id
152 CROSS JOIN LATERAL (VALUES
153 ('u:' || rtrim(regexp_replace(lower(split_part(coalesce(d.document_metadata ->> 'source_url', CASE WHEN s.source_type = 'web' THEN d.source_id END), '#', 1)), '^[a-z][a-z0-9+.-]*://(www\.)?', ''), '/')),
154 ('h:' || (d.document_metadata ->> 'sha256'))
155 ) AS k(key)
156 WHERE d.knowledge_id = ANY(CAST(:ids AS uuid[]))
157 AND k.key IS NOT NULL
158 AND (d.document_metadata ->> 'page_status') IS DISTINCT FROM 'gone'
159)
160SELECT a.knowledge_id AS a, b.knowledge_id AS b,
161 count(DISTINCT a.document_id) AS n,
162 (array_agg(DISTINCT a.label))[1:3] AS labels,
163 (array_agg(DISTINCT a.url) FILTER (WHERE a.url IS NOT NULL))[1:3] AS urls
164 FROM keyed a
165 JOIN keyed b ON a.key = b.key AND a.knowledge_id < b.knowledge_id
166 WHERE a.knowledge_id = ANY(CAST(:members AS uuid[]))
167 OR b.knowledge_id = ANY(CAST(:members AS uuid[]))
168 GROUP BY a.knowledge_id, b.knowledge_id
169"""
171# A link in page metadata is an object's ``url``, or a bare string in records
172# from before links had kinds; its host is lowercase, without ``www.``.
173LINK_HOSTS_SQL = r"""
174SELECT d.knowledge_id AS source, lower(regexp_replace(substring(u.url from '^[a-zA-Z][a-zA-Z0-9+.-]*://([^/?#:@]+)'), '^www\.', '')) AS host,
175 count(DISTINCT d.id) AS pages,
176 (array_agg(DISTINCT u.url))[1:3] AS urls
177 FROM knowledge_documents d
178 CROSS JOIN LATERAL json_array_elements(
179 CASE WHEN json_typeof(d.document_metadata -> 'links') = 'array'
180 THEN d.document_metadata -> 'links' ELSE '[]'::json END) AS l
181 CROSS JOIN LATERAL (SELECT CASE json_typeof(l) WHEN 'object' THEN l ->> 'url' WHEN 'string' THEN l #>> '{}' END AS url) AS u
182 WHERE d.knowledge_id = ANY(CAST(:ids AS uuid[]))
183 AND u.url IS NOT NULL
184 GROUP BY d.knowledge_id, 2
185"""
188def _uuids(values) -> list[str]:
189 return [str(v) for v in values]
192@register_evidence
193class SameDocument(EvidenceKind):
194 key = "same_document"
195 label = "Same documents"
196 description = (
197 "Both hold the same document or page: the same address, or a file "
198 "with the same bytes. Also a sign it is indexed twice."
199 )
200 strength = 0.9
201 tau = 2.0
202 unit = ("document in both", "documents in both")
204 def collect(self, ctx: MapContext) -> list[PairEvidence]:
205 rows = ctx.db.execute(
206 text(SAME_DOCUMENT_SQL),
207 {"ids": _uuids(ctx.ids), "members": _uuids(ctx.members)},
208 ).all()
209 out = []
210 for row in rows:
211 urls = list(row.urls or [])
212 examples = [
213 Example(label=str(label), url=urls[i] if i < len(urls) else None)
214 for i, label in enumerate(row.labels or [])
215 ]
216 out.append(PairEvidence(row.a, row.b, self.key, int(row.n), examples))
217 return out
220@register_evidence
221class CitedTogether(EvidenceKind):
222 key = "cited_together"
223 label = "Cited together"
224 description = (
225 "Answers given here cited both: agents draw on them for the same questions."
226 )
227 strength = 0.8
228 tau = 3.0
229 unit = ("answer cited both", "answers cited both")
231 def collect(self, ctx: MapContext) -> list[PairEvidence]:
232 a = aliased(KnowledgeCitation)
233 b = aliased(KnowledgeCitation)
234 rows = (
235 ctx.db.query(
236 a.knowledge_id, b.knowledge_id, func.count(func.distinct(a.message_id))
237 )
238 .join(
239 b, and_(b.message_id == a.message_id, a.knowledge_id < b.knowledge_id)
240 )
241 .filter(
242 a.knowledge_id.in_(ctx.ids),
243 b.knowledge_id.in_(ctx.ids),
244 or_(
245 a.knowledge_id.in_(list(ctx.members)),
246 b.knowledge_id.in_(list(ctx.members)),
247 ),
248 a.cited_at >= ctx.since,
249 ctx.ws.stamped(a, projects=False),
250 )
251 .group_by(a.knowledge_id, b.knowledge_id)
252 .all()
253 )
254 # No example: the answers are other people's conversations, and the
255 # count already says it.
256 return [PairEvidence(x, y, self.key, int(n), []) for x, y, n in rows]
259@register_evidence
260class LinksTo(EvidenceKind):
261 key = "links_to"
262 label = "Links between them"
263 description = "Pages in one link to the site the other's content comes from."
264 strength = 0.7
265 tau = 5.0
266 unit = ("link", "links")
268 def collect(self, ctx: MapContext) -> list[PairEvidence]:
269 rows = ctx.db.execute(text(LINK_HOSTS_SQL), {"ids": _uuids(ctx.ids)}).all()
270 counts: dict[tuple[UUID, UUID], float] = defaultdict(float)
271 examples: dict[tuple[UUID, UUID], list[Example]] = defaultdict(list)
272 for row in rows:
273 source, host = row.source, row.host
274 if not host:
275 continue
276 # A link within its own site is navigation, not a connection.
277 if web_domains.covered(host, ctx.hosts.get(source, ())):
278 continue
279 for other, hosts in ctx.hosts.items():
280 if other == source or not web_domains.covered(host, hosts):
281 continue
282 if not _touches(source, other, ctx):
283 continue
284 key = pair(source, other)
285 counts[key] += int(row.pages)
286 if len(examples[key]) < 3:
287 examples[key].extend(
288 Example(label=url, url=url)
289 for url in (row.urls or [])[: 3 - len(examples[key])]
290 )
291 return [
292 PairEvidence(a, b, self.key, n, examples[(a, b)])
293 for (a, b), n in counts.items()
294 ]
297@register_evidence
298class SharedSite(EvidenceKind):
299 key = "shared_site"
300 label = "Same sites or publishers"
301 description = (
302 "Their content comes from the same sites, or names the same "
303 "publisher. A site many sources share counts for less."
304 )
305 strength = 0.5
306 tau = 1.5
308 def collect(self, ctx: MapContext) -> list[PairEvidence]:
309 meta = KnowledgeDocument.document_metadata
310 publisher = func.lower(func.trim(meta.op("->>")("publisher")))
311 publishers: dict[UUID, set[str]] = defaultdict(set)
312 for knowledge_id, name in (
313 ctx.db.query(KnowledgeDocument.knowledge_id, publisher)
314 .filter(
315 KnowledgeDocument.knowledge_id.in_(ctx.ids),
316 publisher.isnot(None),
317 publisher != "",
318 )
319 .distinct()
320 .all()
321 ):
322 publishers[knowledge_id].add(name)
323 holdings: dict[UUID, set[str]] = defaultdict(set)
324 for source, hosts in ctx.hosts.items():
325 holdings[source] |= {f"site:{h}" for h in hosts}
326 for source, names in publishers.items():
327 holdings[source] |= {f"publisher:{n}" for n in names}
328 holders: dict[str, int] = defaultdict(int)
329 for items in holdings.values():
330 for item in items:
331 holders[item] += 1
333 out = []
334 sources = sorted(holdings, key=str)
335 for i, a in enumerate(sources):
336 for b in sources[i + 1 :]:
337 if not _touches(a, b, ctx):
338 continue
339 shared = holdings[a] & holdings[b]
340 if not shared:
341 continue
342 # 1 / ln(1 + holders): a site two sources share counts ~0.9,
343 # one ten share ~0.4.
344 count = sum(1 / math.log(1 + holders[item]) for item in shared)
345 examples = [
346 Example(label=item.split(":", 1)[1])
347 for item in sorted(shared, key=lambda x: holders[x])[:3]
348 ]
349 out.append(PairEvidence(*pair(a, b), self.key, count, examples))
350 return out