Coverage for app / services / scenarios / readiness.py: 83%

83 statements  

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

1"""Waiting for a run's built-in knowledge to be there before its first turn. 

2 

3The first scenario run (27 October 2026) started while every built-in 

4website repository it granted was still empty: they are crawled only while 

5an agent holds them, and the run's grants were the first. Agent A's eight 

6turns ran against knowledge bases with nothing indexed, its answers said the 

7knowledge held nothing, and its recommendations read them as questions the 

8knowledge could not answer. The run was a test of empty knowledge. 

9 

10The grants now start the crawls (``knowledge/built_in_crawls``), and 

11:func:`wait` holds the first turn until every source the file granted has 

12**settled** — or ``KNOWLEDGE_WAIT_S`` passes: 

13 

14- a website source has settled once it holds indexed documents from a crawl 

15 that finished, or its newest crawl finished (completed, failed or held) 

16 with nothing left indexing — a source that cannot be fetched will not get 

17 better by waiting; 

18- a written source (the frameworks CHAIN-R writes) once its documents are 

19 stored and none is still indexing; 

20- a source the deployment does not crawl (its switch off) at once. 

21 

22What each source held when the turns began is the export's 

23``run.knowledge`` (:func:`report`), with its documents listed, so a review 

24can tell a page never crawled from one never retrieved. 

25""" 

26 

27from __future__ import annotations 

28 

29import asyncio 

30import time 

31from collections.abc import Awaitable, Callable, Iterable 

32from typing import Any 

33from uuid import UUID 

34 

35from sqlalchemy.orm import Session 

36 

37from app.db.postgres.models import Knowledge, KnowledgeDocument 

38from app.services.knowledge import stats 

39from app.util.time import aware_utcnow, utc_isoformat 

40 

41#: How long the first turn waits for the run's knowledge. A built-in 

42#: repository's crawl takes a few minutes; 20 is room for several at once on 

43#: a crawl pool of two. 

44KNOWLEDGE_WAIT_S = 20 * 60 

45#: How often it looks. 

46POLL_S = 10 

47#: The most documents listed for one source. 

48MAX_DOCUMENTS = 200 

49#: Index states that will still change. 

50_UNSETTLED = ("pending", "indexing", "importing") 

51#: Crawl states that are over. 

52_FINISHED = ("completed", "failed", "held") 

53 

54 

55def _sources( 

56 db: Session, repositories: Iterable[Any] 

57) -> list[tuple[Any, list[Knowledge]]]: 

58 """Each built-in repository with its source rows, in its own order.""" 

59 entries = list(dict.fromkeys(repositories)) 

60 ids = [source.id for entry in entries for source in entry.sources] 

61 rows = {k.id: k for k in db.query(Knowledge).filter(Knowledge.id.in_(ids)).all()} 

62 return [ 

63 (entry, [rows[s.id] for s in entry.sources if s.id in rows]) 

64 for entry in entries 

65 ] 

66 

67 

68def _iso(value: Any) -> str | None: 

69 return utc_isoformat(value) if value is not None else None 

70 

71 

72def _settled( 

73 knowledge: Knowledge, crawl: Any, counts: stats.DocumentCounts, crawled: bool 

74) -> bool: 

75 if any(counts.count(state) for state in _UNSETTLED): 

76 return False 

77 if knowledge.source_type != "web": 

78 return counts.total > 0 

79 if not crawled: 

80 return True 

81 if crawl is None: 

82 return False 

83 if counts.count("indexed") and counts.chunks: 

84 return True 

85 return crawl.status in _FINISHED 

86 

87 

88def _documents(db: Session, knowledge_id: UUID) -> list[dict[str, Any]]: 

89 rows = ( 

90 db.query(KnowledgeDocument.source_id, KnowledgeDocument.document_metadata) 

91 .filter(KnowledgeDocument.knowledge_id == knowledge_id) 

92 .order_by(KnowledgeDocument.source_id) 

93 .limit(MAX_DOCUMENTS) 

94 .all() 

95 ) 

96 out = [] 

97 for source_id, meta in rows: 

98 meta = meta if isinstance(meta, dict) else {} 

99 out.append( 

100 { 

101 "title": str(meta.get("page_title") or meta.get("title") or "") or None, 

102 "source": source_id, 

103 "index_status": meta.get("index_status"), 

104 "chunks": meta.get("chunk_count"), 

105 "page_status": meta.get("page_status"), 

106 } 

107 ) 

108 return out 

109 

110 

111def report( 

112 db: Session, 

113 repositories: Iterable[Any], 

114 *, 

115 ready_at: dict[UUID, str] | None = None, 

116 documents: bool = True, 

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

118 """What each of ``repositories``' sources holds now: its crawl, its 

119 documents counted by state, its chunks, whether it has settled, and (with 

120 ``documents``) each document.""" 

121 from app.common.settings import get_settings 

122 from app.services.system_resources import knowledge as built_in 

123 

124 settings = get_settings() 

125 grouped = _sources(db, repositories) 

126 ids = [k.id for _, rows in grouped for k in rows] 

127 counts = {r.knowledge_id: stats.counts_of(r) for r in stats.document_rows(db, ids)} 

128 crawls = { 

129 r.knowledge_id: r 

130 for r in stats.latest_crawls( 

131 db, [k.id for _, rows in grouped for k in rows if k.source_type == "web"] 

132 ) 

133 } 

134 out = [] 

135 for entry, rows in grouped: 

136 sources = [] 

137 for knowledge in rows: 

138 held = counts.get(knowledge.id, stats.DocumentCounts()) 

139 crawl = crawls.get(knowledge.id) 

140 crawled = knowledge.source_type != "web" or built_in.crawl_enabled( 

141 knowledge.id, settings 

142 ) 

143 item: dict[str, Any] = { 

144 "id": str(knowledge.id), 

145 "name": knowledge.name, 

146 "source_type": knowledge.source_type, 

147 "crawl": ( 

148 { 

149 "status": crawl.status, 

150 "started_at": _iso(crawl.started_at), 

151 "finished_at": _iso(crawl.finished_at), 

152 "pages_failed": crawl.pages_failed or 0, 

153 } 

154 if crawl is not None 

155 else None 

156 ), 

157 "crawled_here": crawled, 

158 "documents": { 

159 "total": held.total, 

160 **{state: n for state, n in held.by_state.items() if n}, 

161 }, 

162 "chunks": held.chunks, 

163 "settled": _settled(knowledge, crawl, held, crawled), 

164 "ready_at": (ready_at or {}).get(knowledge.id), 

165 } 

166 if documents: 

167 item["document_list"] = _documents(db, knowledge.id) 

168 sources.append(item) 

169 out.append( 

170 { 

171 "repository": entry.name, 

172 "id": str(entry.id), 

173 "category": entry.category.value, 

174 "sources": sources, 

175 } 

176 ) 

177 return out 

178 

179 

180async def wait( 

181 db: Session, 

182 repositories: Iterable[Any], 

183 *, 

184 progress: Callable[[str], None], 

185 cancelled: Callable[[], bool], 

186 timeout_s: float = KNOWLEDGE_WAIT_S, 

187 poll_s: float = POLL_S, 

188 clock: Callable[[], float] = time.monotonic, 

189 sleep: Callable[[float], Awaitable[Any]] = asyncio.sleep, 

190) -> dict[str, Any]: 

191 """Wait until every source of ``repositories`` has settled, the run is 

192 cancelled, or ``timeout_s`` passes; then what each held (``run.knowledge``). 

193 

194 ``progress`` is told where the wait stands on every look (the runner 

195 saves it, so a long wait never reads as a stale run). 

196 """ 

197 entries = list(repositories) 

198 started = clock() 

199 ready_at: dict[UUID, str] = {} 

200 timed_out = False 

201 while True: 

202 db.expire_all() 

203 now = report(db, entries, ready_at=ready_at, documents=False) 

204 sources = [s for r in now for s in r["sources"]] 

205 for source in sources: 

206 if source["settled"]: 

207 ready_at.setdefault(UUID(source["id"]), utc_isoformat(aware_utcnow())) 

208 settled = sum(1 for s in sources if s["settled"]) 

209 if settled == len(sources) or cancelled(): 

210 break 

211 if clock() - started >= timeout_s: 

212 timed_out = True 

213 break 

214 progress(f"indexing: {settled} of {len(sources)} sources ready") 

215 await sleep(poll_s) 

216 return { 

217 "waited_ms": int((clock() - started) * 1000), 

218 "timed_out": timed_out, 

219 "repositories": report(db, entries, ready_at=ready_at), 

220 }