Coverage for app / services / knowledge / web_graph.py: 100%

96 statements  

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

1""" 

2The link graph of a website source: which stored page links to which. 

3 

4The pages list says *what* a crawl stored; this says *how it got there*. A 

5crawl walks outward from its seed URLs, and — with ``follow_external`` — hops 

6off-site to pages a crawled page cites. Both leave their trail in each page's 

7record: ``links`` (what the page linked to when last read) and, for a linked 

8page, ``linked_from`` (the crawled pages that led to it). This module joins 

9those into nodes and edges; it reads nothing but the stored records, so it 

10never fetches and never costs a crawl. 

11 

12Only edges between *stored* pages are drawn. A page's other links — skipped as 

13low-value, out of scope or past the page budget — are counted on the node 

14(``unfollowed_links``) rather than drawn as a cloud of dead ends. 

15""" 

16 

17from __future__ import annotations 

18 

19from collections import deque 

20from collections.abc import Iterable 

21from dataclasses import dataclass, field 

22from typing import Any 

23from urllib.parse import urlsplit 

24 

25from app.services.knowledge.web_crawl import PageStatus, _host 

26 

27#: Nodes beyond this are dropped, seeds and shallowest first kept. A source 

28#: stores at most 300 pages a crawl, but gone pages accumulate across crawls. 

29MAX_NODES = 400 

30#: A page stores up to 300 links; a dense site would otherwise draw a hairball. 

31MAX_EDGES = 2000 

32 

33 

34def _key(url: str) -> str: 

35 """URLs as the crawler compares them, less a fragment and trailing slash.""" 

36 url = (url or "").split("#", 1)[0] 

37 return ( 

38 url[:-1] if url.endswith("/") and urlsplit(url).path not in ("", "/") else url 

39 ) 

40 

41 

42@dataclass 

43class GraphNode: 

44 id: str 

45 url: str 

46 title: str | None 

47 status: str 

48 origin: str 

49 host: str 

50 is_seed: bool 

51 version_count: int 

52 depth: int | None = None 

53 unfollowed_links: int = 0 

54 in_links: int = 0 

55 out_links: int = 0 

56 

57 

58@dataclass 

59class GraphEdge: 

60 source: str 

61 target: str 

62 text: str 

63 #: ``internal`` (same site) or ``external`` (a hop off-site) 

64 kind: str 

65 

66 

67@dataclass 

68class LinkGraph: 

69 nodes: list[GraphNode] = field(default_factory=list) 

70 edges: list[GraphEdge] = field(default_factory=list) 

71 truncated: bool = False 

72 

73 

74def build_graph(docs: Iterable[Any], seed_urls: Iterable[str]) -> LinkGraph: 

75 """Join stored pages' ``links`` and ``linked_from`` into a graph. 

76 

77 ``docs`` are ``KnowledgeDocument`` rows (anything with ``id``, 

78 ``source_id`` and ``document_metadata``). Depth is the shortest link path 

79 from any seed, or None for a page no stored link reaches — one found only 

80 in the sitemap, or whose linking page has since gone. 

81 """ 

82 seeds = {_key(u) for u in seed_urls} 

83 nodes: dict[str, GraphNode] = {} 

84 by_url: dict[str, str] = {} 

85 metas: dict[str, dict] = {} 

86 

87 for doc in docs: 

88 meta = doc.document_metadata or {} 

89 url = meta.get("url") or doc.source_id 

90 node_id = str(doc.id) 

91 nodes[node_id] = GraphNode( 

92 id=node_id, 

93 url=url, 

94 title=meta.get("title"), 

95 status=meta.get("page_status") or PageStatus.active.value, 

96 origin=meta.get("origin") or "crawled", 

97 host=_host(urlsplit(url).hostname), 

98 is_seed=_key(url) in seeds, 

99 version_count=int(meta.get("version_count") or 0), 

100 ) 

101 metas[node_id] = meta 

102 for alias in (url, doc.source_id, meta.get("final_url")): 

103 if alias: 

104 by_url.setdefault(_key(alias), node_id) 

105 

106 edges: dict[tuple[str, str], GraphEdge] = {} 

107 

108 def add(source: str, target: str, text: str) -> None: 

109 if source == target or (source, target) in edges: 

110 return 

111 kind = ( 

112 "external" 

113 if nodes[source].host != nodes[target].host 

114 or nodes[target].origin == "linked" 

115 else "internal" 

116 ) 

117 edges[(source, target)] = GraphEdge(source, target, (text or "")[:200], kind) 

118 

119 for node_id, meta in metas.items(): 

120 unfollowed = 0 

121 for link in meta.get("links") or []: 

122 if isinstance(link, str): # a record written before links had kinds 

123 link = {"url": link} 

124 target = by_url.get(_key(link.get("url") or "")) 

125 if target is None: 

126 unfollowed += 1 

127 elif target != node_id: 

128 add(node_id, target, link.get("text") or "") 

129 nodes[node_id].unfollowed_links = unfollowed 

130 # A linked page names the pages that led to it — the edge the deep 

131 # citation shows, even if the referrer's own links have since changed. 

132 for ref in meta.get("linked_from") or []: 

133 source = by_url.get(_key(ref.get("url") or "")) 

134 if source is not None: 

135 add(source, node_id, ref.get("text") or "") 

136 

137 # Shortest link path from the seeds. 

138 outgoing: dict[str, list[str]] = {} 

139 for s, t in edges: 

140 outgoing.setdefault(s, []).append(t) 

141 queue = deque(n.id for n in nodes.values() if n.is_seed) 

142 for n in queue: 

143 nodes[n].depth = 0 

144 while queue: 

145 current = queue.popleft() 

146 for target in outgoing.get(current, []): 

147 if nodes[target].depth is None: 

148 nodes[target].depth = nodes[current].depth + 1 # type: ignore[operator] 

149 queue.append(target) 

150 

151 ordered = sorted( 

152 nodes.values(), 

153 key=lambda n: ( 

154 n.depth is None, 

155 n.depth if n.depth is not None else 0, 

156 n.origin != "crawled", 

157 n.url, 

158 ), 

159 ) 

160 truncated = len(ordered) > MAX_NODES 

161 kept = {n.id for n in ordered[:MAX_NODES]} 

162 kept_edges = [e for e in edges.values() if e.source in kept and e.target in kept] 

163 if len(kept_edges) > MAX_EDGES: 

164 truncated = True 

165 # Keep the edges that explain the tree: those into a node from one 

166 # level up come first. 

167 kept_edges.sort( 

168 key=lambda e: ( 

169 nodes[e.target].depth is None 

170 or nodes[e.source].depth is None 

171 or nodes[e.target].depth != nodes[e.source].depth + 1 # type: ignore[operator] 

172 ) 

173 ) 

174 kept_edges = kept_edges[:MAX_EDGES] 

175 for e in kept_edges: 

176 nodes[e.source].out_links += 1 

177 nodes[e.target].in_links += 1 

178 

179 return LinkGraph( 

180 nodes=[n for n in ordered if n.id in kept], 

181 edges=kept_edges, 

182 truncated=truncated, 

183 )