Coverage for app / services / system_resources / written.py: 90%

133 statements  

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

1""" 

2Index the built-in knowledge CHAIN-R writes — the user guide, and every other 

3written source in :mod:`.knowledge` — into its knowledge bases. 

4 

5Each written source is a folder of markdown shipped inside the image, so the 

6documents an image indexes are always the ones for the release it runs. They 

7are indexed through the same path a user's upload takes — stored in MinIO, 

8chunked, embedded by svc-ai and written to Qdrant — so an agent retrieves and 

9cites them exactly as it does its own documents. 

10 

11Idempotent by content hash. A document is (re)indexed when it is new, when 

12its text changed, or when its last indexing did not finish (svc-ai or Qdrant 

13was down); a document removed from its folder is removed from the index. An 

14unchanged source costs one hash per file and no network call, which is what 

15lets the job run hourly without doing anything most of the time. 

16 

17What indexing costs is the platform's: a built-in source has no owner, so the 

18usage ledger records nothing for it. Each document keeps what its last 

19indexing measured (``index_usage``), and the job's summary adds it up. 

20""" 

21 

22from __future__ import annotations 

23 

24import asyncio 

25import hashlib 

26import logging 

27from dataclasses import dataclass, field 

28from decimal import Decimal 

29from typing import Any, Iterable 

30 

31from sqlalchemy.orm import Session 

32 

33from app.db.postgres.models import KnowledgeDocument 

34from app.services import ai_client 

35from app.util import minio_client 

36 

37from .knowledge import WRITTEN_MIME_TYPE, WrittenSourceSpec, written_sources 

38 

39logger = logging.getLogger(__name__) 

40 

41#: ``document_metadata`` key holding the hash of the text last indexed. 

42HASH_KEY = "content_sha256" 

43#: ``document_metadata`` key holding what its last indexing measured. 

44USAGE_KEY = "index_usage" 

45 

46 

47@dataclass 

48class WrittenSyncResult: 

49 """What one written source's sync did.""" 

50 

51 source: str = "" 

52 indexed: list[str] = field(default_factory=list) 

53 removed: list[str] = field(default_factory=list) 

54 unchanged: int = 0 

55 failed: dict[str, str] = field(default_factory=dict) 

56 #: Embedding calls made, and their measured cost (None: none priced). 

57 calls: int = 0 

58 cost_usd: Decimal | None = None 

59 

60 @property 

61 def changed(self) -> bool: 

62 return bool(self.indexed or self.removed or self.failed) 

63 

64 def add_usage(self, report: dict[str, Any] | None) -> None: 

65 if not report: 

66 return 

67 self.calls += int(report.get("calls") or 0) 

68 cost = report.get("estimated_cost_usd") 

69 if cost is not None: 

70 self.cost_usd = (self.cost_usd or Decimal(0)) + Decimal(str(cost)) 

71 

72 def summary(self) -> str: 

73 parts = [] 

74 if self.indexed: 

75 parts.append(f"indexed {len(self.indexed)}") 

76 if self.removed: 

77 parts.append(f"removed {len(self.removed)}") 

78 if self.failed: 

79 parts.append( 

80 f"failed {len(self.failed)} ({', '.join(sorted(self.failed))})" 

81 ) 

82 parts.append(f"{self.unchanged} unchanged") 

83 return f"{self.source or 'Written'} documents: " + ", ".join(parts) + "." 

84 

85 

86@dataclass 

87class WrittenSyncReport: 

88 """What syncing every written source did.""" 

89 

90 results: list[WrittenSyncResult] = field(default_factory=list) 

91 

92 @property 

93 def changed(self) -> bool: 

94 return any(result.changed for result in self.results) 

95 

96 @property 

97 def failed(self) -> dict[str, str]: 

98 return { 

99 f"{result.source}: {name}": reason 

100 for result in self.results 

101 for name, reason in result.failed.items() 

102 } 

103 

104 @property 

105 def unchanged(self) -> int: 

106 return sum(result.unchanged for result in self.results) 

107 

108 def summary(self) -> str: 

109 parts = [result.summary() for result in self.results if result.changed] 

110 calls = sum(result.calls for result in self.results) 

111 costs = [r.cost_usd for r in self.results if r.cost_usd is not None] 

112 if calls: 

113 cost = f", ${sum(costs, Decimal(0)):.4f}" if costs else "" 

114 parts.append(f"Indexing made {calls} embedding call(s){cost}.") 

115 if not parts: 

116 return f"{self.unchanged} written document(s) indexed, none changed." 

117 return " ".join(parts) 

118 

119 

120def _index(knowledge_id: str, document_id: str, content: bytes, filename: str) -> None: 

121 """Parse, embed and index one written document. 

122 

123 The indexing routine is the knowledge router's own, so a written source 

124 is chunked and stored exactly as an upload is. Imported here rather than 

125 at module level: the router pulls in FastAPI's whole request layer, which 

126 the scheduler has no other reason to load. 

127 """ 

128 from app.router.app.knowledge.router import _index_document 

129 

130 asyncio.run( 

131 _index_document( 

132 document_id=document_id, 

133 knowledge_id=knowledge_id, 

134 content=content, 

135 filename=filename, 

136 mime_type=WRITTEN_MIME_TYPE, 

137 file_extension=".md", 

138 source_id=filename, 

139 ) 

140 ) 

141 

142 

143def _drop_chunks(knowledge_id: str, document_id: str) -> None: 

144 """Remove a document's vectors, best-effort. 

145 

146 Chunk ids are per (document, chunk index), so a shorter new version would 

147 otherwise leave the old version's tail behind to be retrieved. 

148 """ 

149 from app.util import qdrant_client 

150 

151 try: 

152 qdrant_client.delete_document_chunks(knowledge_id, document_id) 

153 except Exception: 

154 logger.warning("Could not drop the chunks of written document %s", document_id) 

155 

156 

157def sync_source(db: Session, source: WrittenSourceSpec) -> WrittenSyncResult: 

158 """Bring one written source's knowledge base in line with its folder.""" 

159 result = WrittenSyncResult(source=source.name) 

160 knowledge_id = str(source.id) 

161 existing = { 

162 doc.source_id: doc 

163 for doc in db.query(KnowledgeDocument) 

164 .filter(KnowledgeDocument.knowledge_id == source.id) 

165 .all() 

166 } 

167 

168 for path in source.files(): 

169 filename = path.name 

170 doc = existing.pop(filename, None) 

171 try: 

172 content = path.read_bytes() 

173 digest = hashlib.sha256(content).hexdigest() 

174 meta = dict(doc.document_metadata or {}) if doc is not None else {} 

175 if ( 

176 doc is not None 

177 and meta.get(HASH_KEY) == digest 

178 and meta.get("index_status") == "indexed" 

179 ): 

180 result.unchanged += 1 

181 continue 

182 

183 stored = minio_client.upload( 

184 knowledge_id, filename, content, WRITTEN_MIME_TYPE 

185 ) 

186 if doc is None: 

187 doc = KnowledgeDocument( 

188 knowledge_id=source.id, 

189 source_id=filename, 

190 folder_path="", 

191 ) 

192 db.add(doc) 

193 else: 

194 _drop_chunks(knowledge_id, str(doc.id)) 

195 doc.document_metadata = { 

196 "original_filename": filename, 

197 "size_bytes": len(content), 

198 "mime_type": WRITTEN_MIME_TYPE, 

199 "minio_object": stored, 

200 "folder_path": "", 

201 "index_status": "pending", 

202 HASH_KEY: digest, 

203 } 

204 db.commit() 

205 db.refresh(doc) 

206 

207 # Records its own outcome on the row (``index_status``) in a 

208 # session of its own, which is what the next run reads to decide 

209 # whether to retry. 

210 with ai_client.usage_capture() as used: 

211 _index(knowledge_id, str(doc.id), content, filename) 

212 db.refresh(doc) 

213 report = used.report() 

214 if report is not None: 

215 doc.document_metadata = { 

216 **(doc.document_metadata or {}), 

217 USAGE_KEY: report, 

218 } 

219 db.commit() 

220 result.add_usage(report) 

221 status = (doc.document_metadata or {}).get("index_status") 

222 if status == "indexed": 

223 result.indexed.append(filename) 

224 else: 

225 result.failed[filename] = str( 

226 (doc.document_metadata or {}).get("index_error") or status 

227 ) 

228 except Exception as exc: # one document must not stop the rest 

229 db.rollback() 

230 logger.exception("Could not sync written document %s", filename) 

231 result.failed[filename] = f"{type(exc).__name__}: {exc}" 

232 

233 for filename, doc in existing.items(): 

234 try: 

235 _drop_chunks(knowledge_id, str(doc.id)) 

236 stored = (doc.document_metadata or {}).get("minio_object") 

237 if stored: 

238 minio_client.delete(stored) 

239 db.delete(doc) 

240 db.commit() 

241 result.removed.append(filename) 

242 except Exception as exc: 

243 db.rollback() 

244 logger.exception("Could not remove written document %s", filename) 

245 result.failed[filename] = f"{type(exc).__name__}: {exc}" 

246 

247 return result 

248 

249 

250def sync_written( 

251 db: Session, sources: Iterable[WrittenSourceSpec] | None = None 

252) -> WrittenSyncReport: 

253 """Sync every written source this deployment provides (or ``sources``), 

254 the guide first.""" 

255 report = WrittenSyncReport() 

256 for source in written_sources() if sources is None else sources: 

257 report.results.append(sync_source(db, source)) 

258 return report 

259 

260 

261__all__ = [ 

262 "HASH_KEY", 

263 "USAGE_KEY", 

264 "WrittenSyncReport", 

265 "WrittenSyncResult", 

266 "sync_source", 

267 "sync_written", 

268]