Coverage for app / services / knowledge / generation_job.py: 95%

237 statements  

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

1"""Generative knowledge setup, run in the background. 

2 

3Designing a repository on real sources takes longer than a request may — the 

4searches, a check of every result, then the design — so ``POST 

5/knowledge/generate`` opens a ``running`` run and returns, and this does the 

6work on its own pool. The person polls the run (``GET /knowledge/generate/ 

7{id}``), which says the stage it is on, and the proposal lands on the run 

8(``generation.propose``) for them to review — however long they took to 

9come back, and from another page. 

10 

11The steps are separate svc-ai calls, so each is well inside a request's time 

12and the run's progress is written between them: 

13 

14 planning /knowledge/discover/plan a model writes the searches 

15 searching /knowledge/discover/search they run (no model) 

16 checking /knowledge/discover/check what they found is probed (no model) 

17 designing /knowledge/generate-config the design, choosing candidates 

18 

19All of it inside one ``generation.metered``: one budget question first, one 

20ledger row for the run, and svc-ai told what is left of the budget — for the 

21design, less what the plan has spent. 

22 

23Discovery degrades rather than fails: no plan, no search, or nothing usable 

24found, and the design runs on stubs with a warning saying so. 

25 

26A second flow runs on the same pool: **source discovery** (``Flow. 

27source_discovery``) fills sources that already exist or were already 

28proposed — the agent wizard's, or an empty source's "Find sources". It 

29searches and checks the same way, then asks ``/knowledge/discover/assign`` 

30which candidates fill which given source; nothing new is proposed. Each 

31flow is one entry in ``_WORK``. 

32""" 

33 

34from __future__ import annotations 

35 

36import logging 

37from collections.abc import Callable 

38from concurrent.futures import ThreadPoolExecutor 

39from enum import StrEnum 

40from typing import Any 

41from uuid import UUID 

42 

43from sqlalchemy.orm import Session 

44 

45from app.db.postgres.enums import GenerationEnum 

46from app.db.postgres.models import GenerationRun, Knowledge 

47from app.services import ai_client, appearance 

48from app.services import generation as generation_service 

49from app.services.knowledge import candidates as candidate_service 

50from app.services.knowledge import repositories, source_types, web_config 

51from app.services.knowledge.imports import MAX_IMPORTS_PER_SOURCE 

52from app.services.workspace import in_scope 

53from app.util import knowledge_categories 

54from app.util.knowledge_categories import KnowledgeCategory 

55 

56logger = logging.getLogger(__name__) 

57 

58 

59class Stage(StrEnum): 

60 """Where a background knowledge generation is.""" 

61 

62 queued = "queued" 

63 planning = "planning" 

64 searching = "searching" 

65 checking = "checking" 

66 designing = "designing" 

67 

68 

69#: The most of the workspace's own sources the design is shown. 

70MAX_CATALOG_ITEMS = 50 

71#: Cap on how many sources one invocation may propose. A generated shelf the 

72#: user has to read through stops being a shortcut. 

73MAX_PROPOSED_KNOWLEDGE = 12 

74#: How much of an existing source's description the design is shown. 

75DESCRIPTION_CHARS = 300 

76 

77#: What a person reads when the run failed for a reason that is not theirs. 

78UNREACHABLE = "Could not reach the model service to design the knowledge. Try again." 

79UNEXPECTED = "Something went wrong designing the knowledge. Try again." 

80 

81_executor = ThreadPoolExecutor(max_workers=4, thread_name_prefix="knowledge-generation") 

82 

83 

84def submit(run_id: UUID) -> None: 

85 """Start a run on the generation pool. Called once its row commits.""" 

86 _executor.submit(execute, run_id) 

87 

88 

89def _stage(db: Session, run: GenerationRun, stage: Stage, **details: Any) -> None: 

90 generation_service.record_progress(run, stage.value, **details) 

91 db.commit() 

92 

93 

94def _fail(db: Session, run: GenerationRun, *, error: str, message: str) -> None: 

95 """Failed, with the raw reason on the run and a safe one for the person.""" 

96 generation_service.fail(db, run, error=error) 

97 generation_service.record_progress(run, "failed", message=message) 

98 db.commit() 

99 

100 

101def execute( 

102 run_id: UUID, 

103 *, 

104 session_factory: Callable[[], Session] | None = None, 

105 client: Any = ai_client, 

106) -> None: 

107 """Do one ``running`` run's work. Never raises: a failure is on the run, 

108 with a message the person may read.""" 

109 from app.db.postgres.engine import SessionLocal 

110 from app.services.budgets import gate 

111 

112 db = (session_factory or SessionLocal)() 

113 try: 

114 run = db.get(GenerationRun, run_id) 

115 if run is None or run.status != GenerationEnum.Status.running: 

116 return 

117 if run.flow not in _WORK: 

118 _fail(db, run, error=f"no job for flow {run.flow}", message=UNEXPECTED) 

119 return 

120 ws = generation_service.made_in(db, run) 

121 try: 

122 # svc-ai names the workspace on its traces; a worker thread 

123 # inherits no request, so it is said here. 

124 with ( 

125 ai_client.in_workspace(ws.key if ws is not None else None), 

126 generation_service.metered(db, run) as used, 

127 ): 

128 proposal, warnings = _WORK[run.flow](db, run, ws, used, client) 

129 except gate.BudgetReached as exc: 

130 # ``metered`` has failed the run; the person reads why. 

131 generation_service.record_progress(run, "failed", message=exc.message) 

132 db.commit() 

133 return 

134 except ai_client.GenerationFailedError as exc: 

135 _fail(db, run, error=str(exc), message=str(exc)) 

136 return 

137 except ai_client.AIServiceError as exc: 

138 logger.warning("Knowledge generation %s: svc-ai unreachable", run_id) 

139 _fail(db, run, error=str(exc), message=UNREACHABLE) 

140 return 

141 db.refresh(run) 

142 if run.status != GenerationEnum.Status.running: 

143 # Failed meanwhile (taken for stale): never overwritten. 

144 db.commit() 

145 return 

146 generation_service.propose(run, proposal, warnings) 

147 db.commit() 

148 except Exception as exc: # a background job never raises 

149 logger.exception("Knowledge generation %s failed unexpectedly", run_id) 

150 db.rollback() 

151 try: 

152 run = db.get(GenerationRun, run_id) 

153 if run is not None and run.status == GenerationEnum.Status.running: 

154 _fail(db, run, error=f"{type(exc).__name__}: {exc}", message=UNEXPECTED) 

155 except Exception: 

156 logger.exception("Could not record knowledge generation %s failing", run_id) 

157 finally: 

158 db.close() 

159 

160 

161def _model(run: GenerationRun) -> dict[str, Any]: 

162 return { 

163 "provider": run.provider, 

164 "model": run.model_name, 

165 "model_id": str(run.ai_model_id) if run.ai_model_id else None, 

166 } 

167 

168 

169def _catalogue(db: Session, ws: Any, run: GenerationRun) -> list[Knowledge]: 

170 """The run's workspace's own sources, never another workspace's.""" 

171 query = db.query(Knowledge) 

172 if ws is not None: 

173 query = query.filter(in_scope(Knowledge, ws, system=False)) 

174 else: 

175 query = query.filter(Knowledge.owner_user_id == run.actor_user_id) 

176 return query.limit(MAX_CATALOG_ITEMS).all() 

177 

178 

179def _discover( 

180 db: Session, 

181 run: GenerationRun, 

182 client: Any, 

183 description: str, 

184 warnings: list[str], 

185 *, 

186 category: KnowledgeCategory | None = None, 

187) -> list[candidate_service.Candidate]: 

188 """Plan, search and check — what the design may choose from. Each step 

189 that cannot be done is a warning, and leaves the design on stubs. 

190 ``category``, when known, is the kind of knowledge to look for (feeds 

191 and updates for dated knowledge, say); None looks for any.""" 

192 user_id = str(run.actor_user_id) if run.actor_user_id else "system" 

193 _stage(db, run, Stage.planning) 

194 try: 

195 plan = client.plan_knowledge_discovery( 

196 { 

197 "problem_description": description, 

198 **_model(run), 

199 "user_id": user_id, 

200 **({"category": category.value} if category is not None else {}), 

201 } 

202 ) 

203 except ai_client.GenerationFailedError: 

204 warnings.append( 

205 "The web searches could not be planned, so the sources are left " 

206 "for you to fill." 

207 ) 

208 return [] 

209 searches = list(plan.get("searches") or []) 

210 if not searches: 

211 warnings.append( 

212 "No web searches were planned for this description, so the " 

213 "sources are left for you to fill." 

214 ) 

215 return [] 

216 

217 _stage(db, run, Stage.searching, searches=len(searches)) 

218 try: 

219 searched = client.search_knowledge_candidates( 

220 {"searches": searches, "user_id": user_id} 

221 ) 

222 except ai_client.AIServiceError: 

223 searched = {"unavailable": "Web search did not answer."} 

224 if searched.get("unavailable"): 

225 warnings.append( 

226 f"{searched['unavailable']} The sources are left for you to fill." 

227 ) 

228 return [] 

229 found = [f for f in searched.get("found") or [] if isinstance(f, dict)] 

230 if not found: 

231 warnings.append( 

232 "The web searches found nothing, so the sources are left for you to fill." 

233 ) 

234 return [] 

235 

236 _stage(db, run, Stage.checking, searches=len(searches), found=len(found)) 

237 try: 

238 checked = client.check_knowledge_candidates( 

239 {"urls": [f.get("url") for f in found]} 

240 ) 

241 except ai_client.AIServiceError: 

242 warnings.append( 

243 "What the searches found could not be checked, so the sources are " 

244 "left for you to fill." 

245 ) 

246 return [] 

247 usable = candidate_service.from_checked( 

248 found, checked.get("checked") or [], warnings 

249 ) 

250 if not usable: 

251 warnings.append( 

252 "Nothing the searches found could be used, so the sources are left " 

253 "for you to fill." 

254 ) 

255 return usable 

256 

257 

258def _work( 

259 db: Session, run: GenerationRun, ws: Any, used: Any, client: Any 

260) -> tuple[dict, list[str]]: 

261 arguments = run.arguments or {} 

262 description = str(arguments.get("problem_description") or "") 

263 want_repository = arguments.get("want_repository", True) is not False 

264 category = knowledge_categories.of(arguments.get("category")) 

265 warnings: list[str] = [] 

266 

267 found = _discover(db, run, client, description, warnings, category=category) 

268 # Only what may join a repository of this kind: a source already held as 

269 # another would be refused at create. 

270 catalogue = _catalogue(db, ws, run) 

271 allowed = set(repositories.joinable(db, category, [k.id for k in catalogue])) 

272 catalogue = [k for k in catalogue if k.id in allowed] 

273 _stage(db, run, Stage.designing, usable=len(found)) 

274 

275 payload = { 

276 "problem_description": description, 

277 **_model(run), 

278 "existing_knowledge": [ 

279 { 

280 "id": str(k.id), 

281 "name": k.name, 

282 "description": (k.description or "")[:DESCRIPTION_CHARS], 

283 "source_type": k.source_type, 

284 } 

285 for k in catalogue 

286 ], 

287 # svc-core owns what it will accept back, so it states the 

288 # vocabularies rather than letting svc-ai's prompt drift from them. 

289 "source_types": source_types.catalogue(), 

290 "default_source_type": source_types.DEFAULT_SOURCE_TYPE, 

291 "repository_icons": appearance.REPOSITORY_ICONS, 

292 "accents": appearance.ACCENTS, 

293 "want_repository": want_repository, 

294 "user_id": str(run.actor_user_id) if run.actor_user_id else "system", 

295 "candidates": _offered(found), 

296 "web_scopes": web_config.catalogue_scopes(), 

297 "web_refresh": web_config.catalogue_refresh(), 

298 "category": category.value, 

299 } 

300 with _what_is_left(used): 

301 result = client.generate_knowledge_config(payload) 

302 proposal = build_proposal( 

303 result, 

304 catalogue, 

305 found, 

306 want_repository=want_repository, 

307 warnings=warnings, 

308 category=category, 

309 ) 

310 proposal["model"] = _model_info(run) 

311 return proposal, warnings 

312 

313 

314#: What svc-ai is shown of each candidate (its ``DesignCandidate``). 

315_OFFERED = frozenset( 

316 { 

317 "kind", 

318 "url", 

319 "title", 

320 "host", 

321 "snippet", 

322 "published", 

323 "content_type", 

324 "size_bytes", 

325 } 

326) 

327 

328 

329def _offered(found: list[candidate_service.Candidate]) -> list[dict]: 

330 """The candidates as svc-ai's design and assignment calls read them, in 

331 the order their indexes refer to.""" 

332 return [c.model_dump(include=_OFFERED) for c in found] 

333 

334 

335def _what_is_left(used: Any) -> Any: 

336 """The spend limit for the run's last call: what is left of the budget 

337 after the plan.""" 

338 limit = ai_client.current_spend_limit() 

339 return ai_client.in_spend_limit( 

340 limit.after(used.enforcement_usd()) if limit is not None else None 

341 ) 

342 

343 

344def _model_info(run: GenerationRun) -> dict[str, Any]: 

345 """The model a proposal names, as the review shows it.""" 

346 return { 

347 "provider": run.provider, 

348 "model_name": run.model_name, 

349 "ai_model_id": str(run.ai_model_id) if run.ai_model_id else None, 

350 } 

351 

352 

353def _web_settings(chosen: dict) -> tuple[str | None, str | None]: 

354 """A website source's scope and cadence as the model chose them, or 

355 None for the defaults.""" 

356 scope = chosen.get("scope") 

357 refresh = chosen.get("refresh") 

358 return ( 

359 scope if scope in web_config.SCOPE_GUIDE else None, 

360 refresh if refresh in web_config.REFRESH_GUIDE else None, 

361 ) 

362 

363 

364def _dedupe_name(name: str, taken: set[str]) -> str: 

365 """``name``, or with a numeric suffix when the workspace has it already 

366 (as agent setup steers its names).""" 

367 if name not in taken: 

368 return name 

369 n = 2 

370 while f"{name} ({n})" in taken: 

371 n += 1 

372 return f"{name} ({n})" 

373 

374 

375def build_proposal( 

376 result: dict, 

377 catalogue: list[Knowledge], 

378 found: list[candidate_service.Candidate], 

379 *, 

380 want_repository: bool, 

381 warnings: list[str], 

382 category: KnowledgeCategory = knowledge_categories.DEFAULT, 

383) -> dict: 

384 """svc-ai's design, authoritatively filtered — what the run keeps and the 

385 review shows. Hallucinated ids dropped, names steered clear of existing 

386 ones, types clamped, each source's candidates mapped back to svc-core's 

387 own copy (never an address from the reply), and the count capped. A 

388 website source is read as often as its kind of knowledge needs 

389 (``web_config.refresh_for``), which the review shows.""" 

390 config: dict = result.get("config") or {} 

391 warnings.extend(result.get("warnings") or []) 

392 

393 by_id = {str(k.id): k for k in catalogue} 

394 selected: list[str] = [] 

395 for knowledge_id in config.get("selected_knowledge_ids") or []: 

396 if knowledge_id in by_id: 

397 selected.append(knowledge_id) 

398 else: 

399 warnings.append( 

400 f"Dropped unknown knowledge base id '{knowledge_id}' from selection." 

401 ) 

402 

403 taken = {k.name for k in catalogue} 

404 proposed: list[dict] = [] 

405 raw = [s for s in config.get("proposed_knowledge") or [] if isinstance(s, dict)] 

406 for stub in raw[:MAX_PROPOSED_KNOWLEDGE]: 

407 raw_name = stub.get("name") or "New Knowledge Base" 

408 name = _dedupe_name(raw_name, taken) 

409 if name != raw_name: 

410 warnings.append( 

411 f"Renamed proposed source '{raw_name}' to '{name}' to avoid a " 

412 "name conflict." 

413 ) 

414 taken.add(name) 

415 source_type = source_types.clamp(stub.get("source_type")) 

416 if source_type != stub.get("source_type"): 

417 warnings.append( 

418 f"Source '{name}' was proposed as an unknown type " 

419 f"'{stub.get('source_type')}'; created as a file source instead." 

420 ) 

421 chosen = candidate_service.resolve( 

422 source_type, 

423 stub.get("candidates") or [], 

424 found, 

425 name=name, 

426 warnings=warnings, 

427 ) 

428 entry: dict[str, Any] = { 

429 "name": name, 

430 "description": str(stub.get("description") or ""), 

431 "source_type": source_type, 

432 "pages": [], 

433 "documents": [], 

434 "scope": None, 

435 "refresh": None, 

436 } 

437 _fill(entry, chosen, stub) 

438 if source_type == "web": 

439 entry["refresh"] = web_config.refresh_for(category, entry["refresh"]) 

440 proposed.append(entry) 

441 dropped = len(raw) - len(proposed) 

442 if dropped > 0: 

443 warnings.append( 

444 f"Dropped {dropped} proposed source(s) beyond the " 

445 f"{MAX_PROPOSED_KNOWLEDGE} this flow will create at once." 

446 ) 

447 

448 return { 

449 "repository_name": str(config.get("repository_name") or "") 

450 if want_repository 

451 else "", 

452 "repository_description": str(config.get("repository_description") or "") 

453 if want_repository 

454 else "", 

455 "icon": appearance.repository_icon(config.get("icon")), 

456 "accent": appearance.accent(config.get("accent")), 

457 "category": category.value, 

458 "reasoning": str(config.get("reasoning") or ""), 

459 "selected_knowledge_ids": selected, 

460 "proposed_knowledge": proposed, 

461 "candidates": [c.model_dump() for c in found], 

462 } 

463 

464 

465def _fill(entry: dict, chosen: list[candidate_service.Candidate], picked: dict) -> None: 

466 """A source's links from what it was given: a website source's pages 

467 (capped as a hand-made one is), scope and cadence; a file source's 

468 documents (capped at what one import takes).""" 

469 if entry["source_type"] == "web": 

470 entry["pages"] = [c.model_dump() for c in chosen][: web_config.MAX_URLS] 

471 entry["scope"], entry["refresh"] = _web_settings(picked) 

472 elif entry["source_type"] == "file": 

473 entry["documents"] = [c.model_dump() for c in chosen][:MAX_IMPORTS_PER_SOURCE] 

474 

475 

476# --------------------------------------------------------------------------- 

477# Source discovery: filling given sources 

478# --------------------------------------------------------------------------- 

479 

480#: What a source to fill is called to the planner, by type. 

481_TYPE_WORDS = {"web": "a website source", "file": "a source of documents"} 

482 

483 

484def _fill_description(context: str, sources: list[dict]) -> str: 

485 """What discovery's planner is asked to find: the knowledge's purpose, 

486 and each source to fill. Cut to what the planner takes.""" 

487 lines = [ 

488 f"- {s.get('name')} ({_TYPE_WORDS.get(s.get('source_type'), 'a source')})" 

489 + (f": {s.get('description')}" if s.get("description") else "") 

490 for s in sources 

491 ] 

492 text = ( 

493 (context.strip() + "\n\n" if context.strip() else "") 

494 + "Find material for these knowledge sources:\n" 

495 + "\n".join(lines) 

496 ) 

497 return text[:4000] 

498 

499 

500def _fill_sources( 

501 db: Session, run: GenerationRun, ws: Any, used: Any, client: Any 

502) -> tuple[dict, list[str]]: 

503 arguments = run.arguments or {} 

504 sources = [ 

505 s 

506 for s in arguments.get("sources") or [] 

507 if isinstance(s, dict) and s.get("source_type") in candidate_service.ACCEPTS 

508 ] 

509 context = str(arguments.get("context") or "") 

510 warnings: list[str] = [] 

511 description = _fill_description(context, sources) 

512 

513 found = _discover(db, run, client, description, warnings) 

514 _stage(db, run, Stage.designing, usable=len(found)) 

515 assignments: list[dict] = [] 

516 if found and sources: 

517 payload = { 

518 "problem_description": description, 

519 **_model(run), 

520 "user_id": str(run.actor_user_id) if run.actor_user_id else "system", 

521 "sources": [ 

522 { 

523 "name": str(s.get("name") or "")[:255] or "Knowledge", 

524 "description": str(s.get("description") or "")[:2000], 

525 "source_type": s["source_type"], 

526 } 

527 for s in sources 

528 ], 

529 "candidates": _offered(found), 

530 "web_scopes": web_config.catalogue_scopes(), 

531 "web_refresh": web_config.catalogue_refresh(), 

532 } 

533 with _what_is_left(used): 

534 result = client.assign_knowledge_sources(payload) 

535 assignments = [ 

536 a for a in result.get("assignments") or [] if isinstance(a, dict) 

537 ] 

538 proposal = build_fill(sources, assignments, found, warnings=warnings) 

539 proposal["model"] = _model_info(run) 

540 return proposal, warnings 

541 

542 

543def build_fill( 

544 sources: list[dict], 

545 assignments: list[dict], 

546 found: list[candidate_service.Candidate], 

547 *, 

548 warnings: list[str], 

549) -> dict: 

550 """svc-ai's assignment, authoritatively filtered: each given source with 

551 the candidates it was assigned, mapped back to svc-core's own copy (a 

552 kind its type does not hold dropped with a warning), capped as a source 

553 of its type is. Every source is listed, filled or not.""" 

554 by_source: dict[int, dict] = {} 

555 for a in assignments: 

556 index = a.get("source") 

557 if isinstance(index, int) and 0 <= index < len(sources): 

558 by_source.setdefault(index, a) 

559 filled: list[dict] = [] 

560 for index, source in enumerate(sources): 

561 picked = by_source.get(index, {}) 

562 name = str(source.get("name") or "") 

563 entry: dict[str, Any] = { 

564 "key": str(source.get("key") or index), 

565 "name": name, 

566 "source_type": source["source_type"], 

567 "pages": [], 

568 "documents": [], 

569 "scope": None, 

570 "refresh": None, 

571 } 

572 chosen = candidate_service.resolve( 

573 source["source_type"], 

574 picked.get("candidates") or [], 

575 found, 

576 name=name, 

577 warnings=warnings, 

578 ) 

579 _fill(entry, chosen, picked) 

580 filled.append(entry) 

581 if found and not any(e["pages"] or e["documents"] for e in filled): 

582 warnings.append( 

583 "Nothing the searches found fitted these sources; add links by hand." 

584 ) 

585 return {"sources": filled, "candidates": [c.model_dump() for c in found]} 

586 

587 

588#: The work of each background flow. 

589_WORK: dict[GenerationEnum.Flow, Callable[..., tuple[dict, list[str]]]] = { 

590 GenerationEnum.Flow.knowledge_setup: _work, 

591 GenerationEnum.Flow.source_discovery: _fill_sources, 

592}