Coverage for app / router / dev / scenario_loader / objects.py: 69%
160 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"""
2Scenario loader data types.
4Each record type is a thin wrapper around the corresponding ``Schema.X.Create``
5class from ``crud_schemas``, adding:
7- ``id: UUID | None = None`` — lets scenario files pin deterministic UUIDs so
8 that cross-collection references (e.g. ``owner_user_id → user.id``) remain
9 stable across multiple loads of the same scenario.
10- ``model_config = ConfigDict(extra="ignore")`` — silently drops any legacy or
11 extra JSON keys rather than raising a validation error.
12"""
14from __future__ import annotations
16from pathlib import Path
17from typing import Any
18from uuid import UUID
20from pydantic import BaseModel, ConfigDict
22from app.db.postgres.crud_schemas import Schema
23from app.db.postgres.enums import RuleEnum
24from app.router.app.knowledge.models import GraphEdgeIn, GraphNodeIn
25from app.util.file import dir_exists, read_json_file_as_model
28# ---------------------------------------------------------------------------
29# Per-collection record types (thin wrappers over Schema.X.Create)
30# ---------------------------------------------------------------------------
33class ResourceIndustryRecord(Schema.ResourceIndustry.Create):
34 model_config = ConfigDict(extra="ignore")
35 id: UUID | None = None
38class ResourceRoleRecord(Schema.ResourceRole.Create):
39 model_config = ConfigDict(extra="ignore")
40 id: UUID | None = None
43class OrganisationRecord(Schema.Organisation.Create):
44 model_config = ConfigDict(extra="ignore")
45 id: UUID | None = None
48class UserRecord(Schema.User.Create):
49 model_config = ConfigDict(extra="ignore")
50 id: UUID | None = None
51 is_active: bool = True
52 is_superuser: bool = False
55class ProjectRecord(Schema.Project.Create):
56 model_config = ConfigDict(extra="ignore")
57 id: UUID | None = None
60class AgentRecord(Schema.Agent.Create):
61 model_config = ConfigDict(extra="ignore")
62 id: UUID | None = None
65# class TaskRecord(Schema.Task.Create):
66# model_config = ConfigDict(extra="ignore")
67# id: UUID | None = None
70class KnowledgeRecord(Schema.Knowledge.Create):
71 model_config = ConfigDict(extra="ignore")
72 id: UUID | None = None
75class SkillRecord(Schema.Skill.Create):
76 model_config = ConfigDict(extra="ignore")
77 id: UUID | None = None
80class CustomWorkerRecord(Schema.CustomWorker.Create):
81 model_config = ConfigDict(extra="ignore")
82 id: UUID | None = None
85class ExperimentRecord(Schema.Experiment.Create):
86 model_config = ConfigDict(extra="ignore")
87 id: UUID | None = None
90class ExperimentVariantRecord(Schema.ExperimentVariant.Create):
91 model_config = ConfigDict(extra="ignore")
92 id: UUID | None = None
93 # Declared here, not on ``Create``: the nested endpoint takes the parent
94 # from the path, while the loader inserts rows directly and has nowhere
95 # else to get it. ``extra="ignore"`` means a missing declaration would
96 # drop the field silently and insert a NULL.
97 experiment_id: UUID
100class TestSuiteRecord(Schema.TestSuite.Create):
101 model_config = ConfigDict(extra="ignore")
102 id: UUID | None = None
105class TestCaseRecord(Schema.TestCase.Create):
106 model_config = ConfigDict(extra="ignore")
107 id: UUID | None = None
108 # See ``ExperimentVariantRecord``.
109 test_suite_id: UUID
112class SimulationWorldRecord(Schema.SimulationWorld.Create):
113 model_config = ConfigDict(extra="ignore")
114 id: UUID | None = None
117class SimulationScenarioRecord(Schema.SimulationScenario.Create):
118 model_config = ConfigDict(extra="ignore")
119 id: UUID | None = None
120 # See ``ExperimentVariantRecord``: the loader inserts rows directly.
121 world_id: UUID
124class SimulationRecord(Schema.Simulation.Create):
125 model_config = ConfigDict(extra="ignore")
126 id: UUID | None = None
127 # See ``ExperimentVariantRecord``: the loader inserts rows directly.
128 world_id: UUID
131class RuleRecord(Schema.Rule.Create):
132 model_config = ConfigDict(extra="ignore")
133 id: UUID | None = None
134 # Provide defaults so minimal fixture entries work without specifying every field
135 scope_type: RuleEnum.Scope = RuleEnum.Scope.global_
136 conditions: list[dict] = []
137 actions: list[dict] = []
138 is_active: bool = True
139 priority: int = 0
142class KnowledgeGraphRecord(BaseModel):
143 """
144 Graph data for a single ``source_type='graph'`` knowledge base.
146 ``knowledge_id`` must match the ``id`` of a KnowledgeRecord (either loaded
147 in the same scenario run or already present in the database).
149 ``nodes`` and ``edges`` use the same shape as the live graph save endpoint
150 — ``properties`` is a plain dict here and serialised to JSON when passed to
151 the Neo4j client.
152 """
154 model_config = ConfigDict(extra="ignore")
156 knowledge_id: UUID
157 nodes: list[GraphNodeIn] = []
158 edges: list[GraphEdgeIn] = []
161class KnowledgeFileEntry(BaseModel):
162 """A single file to ingest, with its folder path relative to the KB root."""
164 model_config = ConfigDict(extra="ignore")
166 path: Path
167 folder_path: str # relative sub-directory within the KB, e.g. "docs/legal" or ""
170class KnowledgeFilesRecord(BaseModel):
171 """
172 Files to ingest into a ``source_type='file'`` knowledge base.
174 Auto-discovered from a ``files/<knowledge_id>/`` subdirectory within the
175 scenario directory. Each entry maps a knowledge base UUID to the local file
176 paths that should be uploaded to MinIO and indexed into Qdrant.
178 Directory layout::
180 scenarios/<scenario>/
181 files/
182 <knowledge_id>/
183 document.pdf
184 subdir/
185 report.csv
186 """
188 model_config = ConfigDict(extra="ignore")
190 knowledge_id: UUID
191 file_entries: list[KnowledgeFileEntry] = []
194# ---------------------------------------------------------------------------
195# Registry — drives both the Scenario class and the router
196# ---------------------------------------------------------------------------
198# Ordered to respect FK dependencies on insertion.
199# ``knowledge_graph`` is intentionally absent — it targets Neo4j, not Postgres,
200# and is handled separately by the router after the SQL insert loop.
201COLLECTION_ORDER: list[str] = [
202 "resource_industry",
203 "resource_role",
204 "organisation",
205 "user",
206 "project",
207 "skill",
208 "custom_worker",
209 "agent",
210 # "task",
211 "knowledge",
212 "experiment",
213 "experiment_variant",
214 "test_suite",
215 "test_case",
216 "simulation_world",
217 "simulation_scenario",
218 "simulation",
219 "rule",
220]
222COLLECTION_SCHEMAS: dict[str, type[BaseModel]] = {
223 "resource_industry": ResourceIndustryRecord,
224 "resource_role": ResourceRoleRecord,
225 "organisation": OrganisationRecord,
226 "user": UserRecord,
227 "project": ProjectRecord,
228 "skill": SkillRecord,
229 "custom_worker": CustomWorkerRecord,
230 "agent": AgentRecord,
231 # "task": TaskRecord,
232 "knowledge": KnowledgeRecord,
233 "experiment": ExperimentRecord,
234 "experiment_variant": ExperimentVariantRecord,
235 "test_suite": TestSuiteRecord,
236 "test_case": TestCaseRecord,
237 "simulation_world": SimulationWorldRecord,
238 "simulation_scenario": SimulationScenarioRecord,
239 "simulation": SimulationRecord,
240 "rule": RuleRecord,
241 # Neo4j — loaded by Scenario.load() but not written to Postgres
242 "knowledge_graph": KnowledgeGraphRecord,
243}
246# ---------------------------------------------------------------------------
247# Scenario
248# ---------------------------------------------------------------------------
251class Scenario(BaseModel):
252 """Holds all records parsed from a scenario directory."""
254 name: str
255 parse_errors: list[str] = []
257 resource_industry: list[ResourceIndustryRecord] = []
258 resource_role: list[ResourceRoleRecord] = []
259 organisation: list[OrganisationRecord] = []
260 user: list[UserRecord] = []
261 project: list[ProjectRecord] = []
262 skill: list[SkillRecord] = []
263 custom_worker: list[CustomWorkerRecord] = []
264 agent: list[AgentRecord] = []
265 # task: list[TaskRecord] = []
266 knowledge: list[KnowledgeRecord] = []
267 experiment: list[ExperimentRecord] = []
268 experiment_variant: list[ExperimentVariantRecord] = []
269 test_suite: list[TestSuiteRecord] = []
270 test_case: list[TestCaseRecord] = []
271 simulation_world: list[SimulationWorldRecord] = []
272 simulation_scenario: list[SimulationScenarioRecord] = []
273 simulation: list[SimulationRecord] = []
274 rule: list[RuleRecord] = []
275 knowledge_graph: list[KnowledgeGraphRecord] = []
276 knowledge_files: list[KnowledgeFilesRecord] = []
278 @classmethod
279 def load(cls, scenario_dir: str) -> Scenario | None:
280 """Load a scenario directory, silently skipping unrecognised files."""
281 import logging as _logging
283 path = Path(scenario_dir)
284 if not dir_exists(path):
285 return None
287 _log = _logging.getLogger(__name__)
288 data: dict[str, Any] = {"name": path.name, "parse_errors": []}
289 for stem, record_type in COLLECTION_SCHEMAS.items():
290 json_file = path / f"{stem}.json"
291 if not json_file.exists():
292 continue
293 try:
294 records = read_json_file_as_model(json_file, record_type)
295 data[stem] = records if isinstance(records, list) else [records]
296 except Exception as exc:
297 msg = f"{stem}: {type(exc).__name__}: {exc}"
298 _log.warning("Could not parse %s — %s", json_file, msg)
299 data["parse_errors"].append(msg)
301 # Scan files/ subdirectory for knowledge base document fixtures
302 files_dir = path / "files"
303 knowledge_files: list[KnowledgeFilesRecord] = []
304 if files_dir.is_dir():
305 for kb_dir in sorted(files_dir.iterdir()):
306 if not kb_dir.is_dir():
307 continue
308 try:
309 knowledge_id = UUID(kb_dir.name)
310 except ValueError:
311 msg = f"files/{kb_dir.name}: directory name is not a valid UUID — skipping"
312 _log.warning(msg)
313 data["parse_errors"].append(msg)
314 continue
315 file_entries = []
316 for f in sorted(kb_dir.rglob("*")):
317 if not f.is_file():
318 continue
319 relative = f.relative_to(kb_dir)
320 parent = str(relative.parent)
321 folder_path = "" if parent == "." else parent
322 file_entries.append(
323 KnowledgeFileEntry(path=f, folder_path=folder_path)
324 )
325 if file_entries:
326 knowledge_files.append(
327 KnowledgeFilesRecord(
328 knowledge_id=knowledge_id, file_entries=file_entries
329 )
330 )
331 data["knowledge_files"] = knowledge_files
333 return cls(**data)
335 def to_records(self) -> dict[str, list[dict]]:
336 """Dump in insertion order as plain dicts, ready for ORM construction."""
337 result: dict[str, list[dict]] = {}
338 for collection in COLLECTION_ORDER:
339 items: list[BaseModel] = getattr(self, collection, [])
340 if not items:
341 continue
342 result[collection] = [item.model_dump() for item in items]
344 return result