Coverage for app / services / system_resources / provision.py: 96%
227 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"""
2Provision the built-in rows — CHAINR Bot, its guide, the built-in skillsets,
3the gold datasets, the built-in knowledge repositories, the built-in rules
4and the built-in dashboards — from :mod:`.definition`, :mod:`.skillsets`,
5:mod:`.datasets`, :mod:`.knowledge`, :mod:`.rules` and :mod:`.dashboards`.
7Idempotent, and cheap when nothing has changed: each row is looked up by its
8fixed id, created if missing and brought back in line with the definition if
9a release changed it. Both cases write a ``ResourceVersion`` with no actor,
10so the bot's edit history reads as its release history — the audit rule that
11every user-creatable resource has a trail applies here too, even though no
12user created it.
14Called at startup (so the bot exists before anybody asks for it) and again by
15the guide sync job (so a replica that started before migrations finished, or
16a database that was reset underneath a running service, heals itself).
17"""
19from __future__ import annotations
21import logging
22from dataclasses import dataclass, field
23from typing import Any
25from sqlalchemy import text
26from sqlalchemy.orm import Session
28from app.db.postgres.enums import DashboardEnum, HistoryEnum
29from app.db.postgres.models import (
30 Agent,
31 AgentRepository,
32 Dashboard,
33 DashboardWidget,
34 ExperimentRun,
35 Knowledge,
36 KnowledgeRepository,
37 RepositoryKnowledge,
38 Rule,
39 Skill,
40 Skillset,
41 SkillsetSkill,
42 TestCase,
43 TestSuite,
44)
45from app.services import history as history_service
46from app.services.evaluation import dataset_versions
48from .dashboards import SYSTEM_DASHBOARDS
49from .definition import (
50 CHAINR_BOT,
51 GUIDE_KNOWLEDGE,
52 GUIDE_REPOSITORY,
53 SystemDashboardSpec,
54 SystemDatasetSpec,
55 SystemSkillsetSpec,
56)
57from .datasets import SYSTEM_DATASETS
58from .knowledge import BUILT_IN_REPOSITORIES, BuiltInRepository
59from .rules import SYSTEM_RULES
60from .skillsets import SYSTEM_SKILLSETS
62logger = logging.getLogger(__name__)
64#: Transaction-scoped advisory lock, so two replicas starting together do not
65#: both insert the same fixed-id row. Distinct from the migration runner's and
66#: the scheduler's ids.
67PROVISION_LOCK_ID = 551_203_117
70@dataclass
71class ProvisionResult:
72 created: list[str] = field(default_factory=list)
73 updated: list[str] = field(default_factory=list)
74 #: True when another replica held the lock and this one did nothing.
75 skipped: bool = False
77 @property
78 def changed(self) -> bool:
79 return bool(self.created or self.updated)
81 def summary(self) -> str:
82 if self.skipped:
83 return "Another replica is provisioning the built-in resources."
84 parts = []
85 if self.created:
86 parts.append(f"created {', '.join(self.created)}")
87 if self.updated:
88 parts.append(f"updated {', '.join(self.updated)}")
89 return "; ".join(parts) or "Built-in resources are up to date."
92def _acquire_lock(db: Session) -> bool:
93 return bool(
94 db.execute(
95 text("SELECT pg_try_advisory_xact_lock(:key)"), {"key": PROVISION_LOCK_ID}
96 ).scalar()
97 )
100def _upsert(
101 db: Session,
102 model: type,
103 spec: Any,
104 label: str,
105 result: ProvisionResult,
106 *,
107 resource_type: HistoryEnum.ResourceType,
108 children: Any = None,
109) -> Any:
110 """Bring one system row in line with ``spec``; record a version if it moved."""
111 row, action = _sync(db, model, spec, label, result)
112 if action is not None:
113 history_service.record_version(
114 db,
115 resource_type=resource_type,
116 model=model,
117 resource=row,
118 action=action,
119 actor=None,
120 children_resolver=children,
121 )
122 return row
125def _sync(
126 db: Session,
127 model: type,
128 spec: Any,
129 label: str,
130 result: ProvisionResult,
131) -> tuple[Any, HistoryEnum.Action | None]:
132 """Bring one system row in line with ``spec``, recording nothing.
134 Returns the row and what happened to it — ``created``, ``updated`` or
135 None when it already matched — for a caller that has more to change
136 before the version is written (a dataset's cases).
137 """
138 wanted = spec.fields()
139 row = db.get(model, spec.id)
140 if row is None:
141 row = model(id=spec.id, is_system=True, **wanted)
142 db.add(row)
143 db.flush()
144 # Read back what the database stored, so the first version's snapshot
145 # holds the naive timestamp every later snapshot will — not the
146 # aware Python default, which would diff as a change next release.
147 db.refresh(row)
148 action = HistoryEnum.Action.created
149 result.created.append(label)
150 else:
151 drift = {
152 name: value
153 for name, value in wanted.items()
154 if getattr(row, name, None) != value
155 }
156 # A row that lost its flag (or somehow gained an owner) is put back:
157 # the flag and the ownerlessness are what keep it read-only.
158 if row.is_system is not True:
159 drift["is_system"] = True
160 for column in ("owner_user_id", "owner_organisation_id", "owner_project_id"):
161 if getattr(row, column, None) is not None:
162 drift[column] = None
163 if not drift:
164 return row, None
165 for name, value in drift.items():
166 setattr(row, name, value)
167 db.flush()
168 action = HistoryEnum.Action.updated
169 result.updated.append(label)
170 return row, action
173def _ensure_link(db: Session, model: type, key: dict[str, Any]) -> bool:
174 """Create a junction row if missing. Returns True when it was created."""
175 if db.get(model, key) is not None:
176 return False
177 db.add(model(**key))
178 db.flush()
179 return True
182def _bot_children() -> dict:
183 """The bot's grants, in the shape ``_agent_children_snapshot`` uses."""
184 return {
185 "toolkits": [],
186 "skillsets": [],
187 "repositories": [
188 {
189 "repository_id": str(GUIDE_REPOSITORY.id),
190 "name": GUIDE_REPOSITORY.name,
191 "config": None,
192 }
193 ],
194 }
197def _provision_skillset(
198 db: Session, spec: SystemSkillsetSpec, result: ProvisionResult
199) -> None:
200 """One built-in skillset, its skills, and exactly its declared membership.
202 Membership is reconciled both ways: a release that drops a skill from a
203 skillset removes the link, so an agent granted the skillset stops being
204 offered that skill. The skill row itself stays, as does its history.
205 """
206 for skill in spec.skills:
207 _upsert(
208 db,
209 Skill,
210 skill,
211 f"skill “{skill.name}”",
212 result,
213 resource_type=HistoryEnum.ResourceType.skill,
214 )
216 declared = [skill.id for skill in spec.skills]
218 def children() -> dict:
219 return {"skills": [{"skill_id": str(skill_id)} for skill_id in declared]}
221 label = f"skillset “{spec.name}”"
222 row = _upsert(
223 db,
224 Skillset,
225 spec,
226 label,
227 result,
228 resource_type=HistoryEnum.ResourceType.skillset,
229 children=children,
230 )
231 membership_changed = False
232 for skill_id in declared:
233 membership_changed |= _ensure_link(
234 db, SkillsetSkill, {"skillset_id": spec.id, "skill_id": skill_id}
235 )
236 stale = [
237 link
238 for link in db.query(SkillsetSkill)
239 .filter(SkillsetSkill.skillset_id == spec.id)
240 .all()
241 if link.skill_id not in declared
242 ]
243 for row in stale:
244 db.delete(row)
245 membership_changed = True
246 if stale:
247 db.flush()
248 if not membership_changed or label in result.created:
249 return
250 # Membership is part of what a skillset *is* — an agent granted it gets
251 # these skills — so a release that only moves a skill still versions it.
252 if label not in result.updated:
253 history_service.record_version(
254 db,
255 resource_type=HistoryEnum.ResourceType.skillset,
256 model=Skillset,
257 resource=row,
258 action=HistoryEnum.Action.updated,
259 actor=None,
260 children_resolver=children,
261 )
262 result.updated.append(f"{label} membership")
265def _reconcile_cases(
266 db: Session, spec: SystemDatasetSpec, result: ProvisionResult
267) -> bool:
268 """Make a gold dataset's cases exactly its declared cases. Returns True
269 when anything changed.
271 Cases are matched by their fixed ids, created when missing and corrected
272 in place when a release changed them. A case the release no longer
273 declares is deleted only when nobody has results for it: deleting a case
274 cascades to every user's results, and a release is not a user's decision
275 to lose them. One that has results is kept, and logged loudly — the
276 definition must be put back (``datasets.py`` never removes a case).
277 """
278 declared = {case.id: case for case in spec.cases}
279 existing = {
280 row.id: row
281 for row in db.query(TestCase).filter(TestCase.test_suite_id == spec.id).all()
282 }
283 changed = False
284 for case_id, case in declared.items():
285 wanted = case.fields()
286 row = existing.get(case_id)
287 if row is None:
288 db.add(TestCase(id=case_id, test_suite_id=spec.id, **wanted))
289 changed = True
290 continue
291 drift = {k: v for k, v in wanted.items() if getattr(row, k, None) != v}
292 for name, value in drift.items():
293 setattr(row, name, value)
294 changed |= bool(drift)
295 for case_id, row in existing.items():
296 if case_id in declared:
297 continue
298 has_results = (
299 db.query(ExperimentRun.id)
300 .filter(ExperimentRun.test_case_id == case_id)
301 .first()
302 is not None
303 )
304 if has_results:
305 logger.error(
306 "Gold dataset %r no longer declares case %s, which has results; "
307 "kept. Released cases are corrected in place, never removed.",
308 spec.name,
309 case_id,
310 )
311 continue
312 db.delete(row)
313 changed = True
314 if changed:
315 db.flush()
316 result.updated.append(f"dataset “{spec.name}” cases")
317 return changed
320def _provision_dataset(
321 db: Session, spec: SystemDatasetSpec, result: ProvisionResult
322) -> None:
323 """One gold dataset and exactly its declared cases, as one version.
325 The version is written after the cases are reconciled, so its snapshot
326 holds the cases the release declares — and a release that changes any
327 case starts a new *content version* of the dataset, which is what keeps
328 runs before and after the change from being compared.
329 """
330 label = f"dataset “{spec.name}”"
331 row, action = _sync(db, TestSuite, spec, label, result)
332 cases_changed = _reconcile_cases(db, spec, result)
333 if action is None and not cases_changed:
334 return
335 history_service.record_version(
336 db,
337 resource_type=HistoryEnum.ResourceType.test_suite,
338 model=TestSuite,
339 resource=row,
340 action=action or HistoryEnum.Action.updated,
341 actor=None,
342 children_resolver=lambda: dataset_versions.case_snapshot(db, spec.id),
343 )
346def _dashboard_children(spec: SystemDashboardSpec) -> dict:
347 """A board's declared tiles, in the shape the dashboards router's
348 ``dashboard_children_snapshot`` gives every board's versions."""
349 return {
350 "widgets": [
351 {
352 "widget_id": str(widget.id),
353 "widget_type": widget.widget_type.value,
354 "title": widget.title,
355 }
356 for widget in spec.widgets
357 ]
358 }
361def _reconcile_widgets(
362 db: Session, spec: SystemDashboardSpec, *, report: bool, result: ProvisionResult
363) -> bool:
364 """Make a built-in board's tiles exactly its declared tiles. Returns True
365 when anything changed.
367 Tiles are matched by fixed id, so one a release only moves or retitles
368 keeps its cache. One whose type or config changed has its cache cleared:
369 the answer it holds was to a different question. A tile the release no
370 longer declares is removed — nobody owns it, and nothing points at it.
371 """
372 declared = {widget.id: (index, widget) for index, widget in enumerate(spec.widgets)}
373 existing = {
374 row.id: row
375 for row in db.query(DashboardWidget)
376 .filter(DashboardWidget.dashboard_id == spec.id)
377 .all()
378 }
379 changed = False
380 for widget_id, (position, widget) in declared.items():
381 wanted = widget.fields(position)
382 row = existing.get(widget_id)
383 if row is None:
384 db.add(DashboardWidget(id=widget_id, dashboard_id=spec.id, **wanted))
385 changed = True
386 continue
387 drift = {k: v for k, v in wanted.items() if getattr(row, k, None) != v}
388 if not drift:
389 continue
390 for name, value in drift.items():
391 setattr(row, name, value)
392 if "config" in drift or "widget_type" in drift:
393 row.cache_status = DashboardEnum.RefreshStatus.empty
394 row.cache_payload = None
395 row.cache_error = None
396 row.cached_at = None
397 changed = True
398 for widget_id, row in existing.items():
399 if widget_id not in declared:
400 db.delete(row)
401 changed = True
402 if changed:
403 db.flush()
404 if report:
405 result.updated.append(f"dashboard “{spec.name}” widgets")
406 return changed
409def _provision_dashboard(
410 db: Session, spec: SystemDashboardSpec, result: ProvisionResult
411) -> None:
412 """One built-in board and exactly its declared tiles, as one version."""
413 label = f"dashboard “{spec.name}”"
414 row, action = _sync(db, Dashboard, spec, label, result)
415 widgets_changed = _reconcile_widgets(
416 db, spec, report=label not in result.created, result=result
417 )
418 if action is None and not widgets_changed:
419 return
420 history_service.record_version(
421 db,
422 resource_type=HistoryEnum.ResourceType.dashboard,
423 model=Dashboard,
424 resource=row,
425 action=action or HistoryEnum.Action.updated,
426 actor=None,
427 children_resolver=lambda: _dashboard_children(spec),
428 )
431def _provision_repository(
432 db: Session, entry: BuiltInRepository, result: ProvisionResult
433) -> None:
434 """A built-in repository, its sources, and exactly its declared
435 membership.
437 Skipped when the deployment turns it off (its ``switch``, such as
438 ``BUILT_IN_NEWS_ENABLED``): rows already written stay, and are no longer
439 crawled (``web_crawl.due_sources``) or offered. A source a release drops
440 leaves the repository — so no agent reaches it and nothing crawls it —
441 but its row and history stay, like a skill dropped from a built-in
442 skillset.
443 """
444 if not entry.enabled():
445 return
446 for source in entry.sources:
447 _upsert(
448 db,
449 Knowledge,
450 source,
451 f"{entry.source_label} “{source.name}”",
452 result,
453 resource_type=HistoryEnum.ResourceType.knowledge,
454 )
456 declared = [source.id for source in entry.sources]
458 def children() -> dict:
459 return {
460 "knowledge": [
461 {"knowledge_id": str(source.id), "name": source.name}
462 for source in entry.sources
463 ]
464 }
466 label = entry.label
467 row = _upsert(
468 db,
469 KnowledgeRepository,
470 entry.repository,
471 label,
472 result,
473 resource_type=HistoryEnum.ResourceType.knowledge_repository,
474 children=children,
475 )
476 changed = False
477 for knowledge_id in declared:
478 changed |= _ensure_link(
479 db,
480 RepositoryKnowledge,
481 {"repository_id": entry.id, "knowledge_id": knowledge_id},
482 )
483 stale = [
484 link
485 for link in db.query(RepositoryKnowledge)
486 .filter(RepositoryKnowledge.repository_id == entry.id)
487 .all()
488 if link.knowledge_id not in declared
489 ]
490 for link in stale:
491 db.delete(link)
492 changed = True
493 if stale:
494 db.flush()
495 if not changed or label in result.created:
496 return
497 if label not in result.updated:
498 history_service.record_version(
499 db,
500 resource_type=HistoryEnum.ResourceType.knowledge_repository,
501 model=KnowledgeRepository,
502 resource=row,
503 action=HistoryEnum.Action.updated,
504 actor=None,
505 children_resolver=children,
506 )
507 result.updated.append(f"{label} membership")
510def ensure_system_resources(db: Session) -> ProvisionResult:
511 """Create or update every built-in row: CHAINR Bot, its guide repository
512 and knowledge base, the built-in skillsets with their skills, the gold
513 datasets with their cases, the built-in knowledge repositories with their
514 sources, the built-in rules, and the built-in dashboards with their tiles.
516 Commits on success and rolls back on failure; raises only what the caller
517 should log (the startup hook and the job both catch it).
518 """
519 result = ProvisionResult()
520 try:
521 if not _acquire_lock(db):
522 result.skipped = True
523 db.rollback()
524 return result
526 _upsert(
527 db,
528 Knowledge,
529 GUIDE_KNOWLEDGE,
530 "guide knowledge base",
531 result,
532 resource_type=HistoryEnum.ResourceType.knowledge,
533 )
534 _upsert(
535 db,
536 KnowledgeRepository,
537 GUIDE_REPOSITORY,
538 "guide repository",
539 result,
540 resource_type=HistoryEnum.ResourceType.knowledge_repository,
541 children=lambda: {
542 "knowledge": [
543 {
544 "knowledge_id": str(GUIDE_KNOWLEDGE.id),
545 "name": GUIDE_KNOWLEDGE.name,
546 }
547 ]
548 },
549 )
550 if _ensure_link(
551 db,
552 RepositoryKnowledge,
553 {"repository_id": GUIDE_REPOSITORY.id, "knowledge_id": GUIDE_KNOWLEDGE.id},
554 ):
555 result.updated.append("guide repository membership")
557 # The version's children snapshot is the *declared* grant, so it is
558 # right whichever order the agent row and its grant are flushed in.
559 _upsert(
560 db,
561 Agent,
562 CHAINR_BOT,
563 "CHAINR Bot",
564 result,
565 resource_type=HistoryEnum.ResourceType.agent,
566 children=_bot_children,
567 )
568 if (
569 _ensure_link(
570 db,
571 AgentRepository,
572 {"agent_id": CHAINR_BOT.id, "repository_id": GUIDE_REPOSITORY.id},
573 )
574 and "CHAINR Bot" not in result.created
575 ):
576 result.updated.append("CHAINR Bot's guide grant")
578 for skillset in SYSTEM_SKILLSETS:
579 _provision_skillset(db, skillset, result)
581 for dataset in SYSTEM_DATASETS:
582 _provision_dataset(db, dataset, result)
584 # Every built-in repository but the guide, which is provisioned with
585 # the bot above (it is the bot's, and granted to it).
586 for entry in BUILT_IN_REPOSITORIES:
587 if entry.grantable:
588 _provision_repository(db, entry, result)
590 # A built-in rule a release no longer declares is left where it is:
591 # users' rules record it as what they were based on. Removing one is
592 # a migration's work (104 removed *Route long prompts* with routing).
593 for rule in SYSTEM_RULES:
594 _upsert(
595 db,
596 Rule,
597 rule,
598 f"rule “{rule.name}”",
599 result,
600 resource_type=HistoryEnum.ResourceType.rule,
601 )
603 for dashboard in SYSTEM_DASHBOARDS:
604 _provision_dashboard(db, dashboard, result)
606 db.commit()
607 except Exception:
608 db.rollback()
609 raise
610 if result.changed:
611 logger.info("Built-in resources provisioned: %s", result.summary())
612 return result