Coverage for src/romfarmer/driver/spec_resolve.py: 87%
150 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
1"""RESOLVE from a ``Spec`` — ``resolve_build(spec, …) -> tuple[ResolvedBuild, …]``.
3The Spec carries the *choices* (sources, extraction, compression, DAT lever,
4pass policy, budget). Platform *intrinsics* that are facts rather than
5choices (arcade filter, PS3 keys config, DAT platform name, emulator, …)
6still come from ``config/platforms/<id>.yaml``; the frontend/device pair
7comes from ``config/frontends`` + ``config/devices``. The Spec wins wherever
8both say something.
10``spec_from_build`` is the shim that lowers a legacy ``config/builds`` YAML
11(recipes + target) into a Spec, so every existing build is one caller of the
12new seam. Its docstring records whether the legacy name is reclaimed later.
13"""
15from __future__ import annotations
17import logging
18from pathlib import Path
19from typing import TYPE_CHECKING, Any
21from romfarmer.ir.spec import (
22 Spec,
23 SpecBudget,
24 SpecCuratedLists,
25 SpecDat,
26 SpecError,
27 SpecIntent,
28 SpecPasses,
29 SpecPlatform,
30 SpecRating,
31 SpecRegion,
32 SpecSample,
33 SpecTarget,
34)
36from .resolve import ResolvedBuild, ResolvePaths, dat_is_retool_1g1r, resolve_platform
37from .sources import alias_path, load_source_roots, resolve_source
39if TYPE_CHECKING:
40 from romfarmer.config.resolver import ResolvedPlatformConfig
41 from romfarmer.config.target import ComposedTarget
43logger = logging.getLogger(__name__)
46# ---------------------------------------------------------------------------
47# Target composition (frontend + device, no config/targets/*.yaml needed)
48# ---------------------------------------------------------------------------
51def compose_target(frontend: str, device: str | None, config_root: Path) -> ComposedTarget:
52 from romfarmer.config.target import ComposedTarget, TargetConfig
53 from romfarmer.config.target_loader import load_device, load_frontend
55 dev = device or "pc"
56 try:
57 fe_cfg = load_frontend(frontend, config_root)
58 dev_cfg = load_device(dev, config_root)
59 except Exception as exc:
60 raise SpecError(f"target {frontend}/{dev}: {exc}") from exc
61 tc = TargetConfig(name=f"{frontend}-{dev}", frontend=frontend, device=dev)
62 return ComposedTarget(name=tc.name, frontend=fe_cfg, device=dev_cfg, target_config=tc)
65# ---------------------------------------------------------------------------
66# Defaults
67# ---------------------------------------------------------------------------
69_BY_EXTRACTION: dict[str, str] = {
70 "disc": "chd",
71 "cartridge": "zip",
72 "xiso": "xiso",
73 "rvz": "rvz",
74 "wux": "none",
75 "ps3": "jb",
76 "none": "none",
77 "mixed": "none",
78}
81def default_compression(
82 composed: ComposedTarget, platform: str, extraction: Any
83) -> tuple[Any, str]:
84 """``(format, how)`` — frontend-preferred format for *platform*, else by extraction family.
86 ``how`` is ``"frontend"`` or ``"extraction-family"``; the platform's RESOLVE
87 notes carry it so a default never passes as a choice. Lookup failures are
88 loud, not a silent family default.
89 """
90 from romfarmer.config.models import CompressionFormat
92 try:
93 pref = composed.get_preferred_compression(platform, default="")
94 except Exception as exc:
95 raise SpecError(
96 f"platforms[{platform!r}]: frontend preference lookup failed: {exc}"
97 ) from exc
98 if pref:
99 try:
100 return CompressionFormat(pref), "frontend"
101 except ValueError as exc:
102 raise SpecError(
103 f"platforms[{platform!r}]: frontend prefers {pref!r}, not a known CompressionFormat"
104 ) from exc
105 fam = _BY_EXTRACTION.get(getattr(extraction, "value", str(extraction)), "none")
106 return CompressionFormat(fam), "extraction-family"
109# ---------------------------------------------------------------------------
110# Spec platform → ResolvedPlatformConfig
111# ---------------------------------------------------------------------------
113# RESOLVE notes for a freshly built (frozen) ResolvedPlatformConfig, handed to
114# resolve_platform as extra_notes. Keyed by object id; consumed once.
115_NOTES: dict[int, tuple[str, ...]] = {}
118def _resolved_from_spec_platform(
119 sp: SpecPlatform,
120 composed: ComposedTarget,
121 config_root: Path,
122 output_base: Path,
123 roots: dict[str, Path],
124) -> ResolvedPlatformConfig:
125 from romfarmer.config.models import (
126 CompressionFormat,
127 DATSource,
128 ExtractionType,
129 SelectionConfig,
130 SourceConfig,
131 )
132 from romfarmer.config.new_loader import load_slim_platform
133 from romfarmer.config.resolver import ResolvedPlatformConfig
134 from romfarmer.config.slim_platform import DATReference
136 try:
137 slim = load_slim_platform(sp.platform, config_root, check_source_paths=False)
138 except FileNotFoundError as exc:
139 raise SpecError(
140 f"platforms[{sp.platform!r}]: no config/platforms/{sp.platform}.yaml"
141 ) from exc
142 # Defaults are facts, not guesses: extraction is intrinsic to the platform
143 # config; compression is the frontend's preferred format for it (falling
144 # back by extraction family). A stated value always wins, and a default is
145 # always NAMED in the platform's RESOLVE notes.
146 notes: list[str] = []
147 try:
148 if sp.extraction is not None:
149 extraction = ExtractionType(sp.extraction)
150 else:
151 extraction = slim.extraction
152 notes.append(f"extraction defaulted to platform intrinsic {extraction.value!r}")
153 if sp.compression is not None:
154 compression = CompressionFormat(sp.compression)
155 else:
156 compression, how = default_compression(composed, sp.platform, extraction)
157 notes.append(f"compression defaulted to {compression.value!r} ({how})")
158 except ValueError as exc:
159 raise SpecError(f"platforms[{sp.platform!r}]: {exc}") from exc
161 sources = []
162 for i, src in enumerate(sp.sources):
163 p = resolve_source(src, roots, f"platforms[{sp.platform!r}].sources[{i}]")
164 if not p.exists():
165 raise SpecError(
166 f"platforms[{sp.platform!r}].sources[{i}]: directory not found: {p} "
167 f"(root {src.root!r} → {roots[src.root]})"
168 )
169 sources.append(SourceConfig.model_validate({"path": p, "recursive": src.recursive}))
171 dat: DATReference | None = slim.dat
172 if sp.dat.source is not None or sp.dat.file is not None:
173 update: dict[str, Any] = {}
174 if sp.dat.source is not None:
175 try:
176 update["source"] = DATSource(sp.dat.source)
177 except ValueError as exc:
178 raise SpecError(f"platforms[{sp.platform!r}].dat.source: {exc}") from exc
179 if sp.dat.file is not None:
180 update["file"] = Path(sp.dat.file)
181 dat = (
182 slim.dat.model_copy(update=update)
183 if slim.dat is not None
184 else DATReference.model_validate(update)
185 )
187 ps = sp.passes
188 selection = SelectionConfig.model_validate(
189 {
190 "preferred_regions": list(ps.region.preferred),
191 "min_rating": ps.rating.min,
192 "top_n": ps.rating.top_n,
193 "unrated": ps.rating.unrated or "keep",
194 "max_size_gb": (ps.budget.max_bytes / 1024**3) if ps.budget.max_bytes else None,
195 "unrated_as": ps.budget.unrated_as,
196 "safety_margin": 0.0, # retired: p90 headroom is the constraint
197 }
198 )
200 folder_name = composed.get_folder_name(sp.platform)
201 defaults = getattr(composed.frontend, "defaults", None)
202 organization = getattr(defaults, "organization", "flat") if defaults else "flat"
203 metadata = getattr(defaults, "metadata", True) if defaults else True
205 rc = ResolvedPlatformConfig(
206 platform=sp.platform,
207 display_name=slim.display_name,
208 platform_type=slim.type,
209 emulator=slim.emulator,
210 metadata_system=slim.metadata_system,
211 extraction_type=extraction,
212 compression=compression,
213 multi_disc=slim.multi_disc,
214 dat=dat,
215 sources=sources,
216 chd_sources=slim.chd_sources,
217 selection=selection,
218 arcade_filter=slim.arcade_filter,
219 bios=slim.bios,
220 samples_sources=slim.samples_sources,
221 output_dir=output_base / (folder_name or sp.platform),
222 folder_name=folder_name or "",
223 organization=organization,
224 metadata=metadata,
225 ps3=slim.ps3,
226 xbox=slim.xbox,
227 extras=slim.extras,
228 recipe_name=None,
229 )
230 _NOTES[id(rc)] = tuple(notes)
231 if sp.dat.retool_1g1r != dat_is_retool_1g1r(rc):
232 raise SpecError(
233 f"platforms[{sp.platform!r}].dat.retool_1g1r={sp.dat.retool_1g1r} disagrees with the DAT "
234 f"source {getattr(rc.dat, 'source', None)!r} — the flag must state what the DAT is"
235 )
236 return rc
239# ---------------------------------------------------------------------------
240# Entry point
241# ---------------------------------------------------------------------------
244def resolve_build(
245 spec: Spec,
246 config_root: Path,
247 *,
248 workspace_root: Path | None = None,
249 output_base: Path | None = None,
250 artifacts_dir: Path | None = None,
251) -> tuple[ResolvedBuild, ...]:
252 """RESOLVE every platform of *spec*; platforms ordered by priority desc, then id.
254 Pure apart from reading config/DAT/artifact files. Raises ``SpecError``
255 for anything the spec gets wrong (unknown platform, missing source dir,
256 mismatched DAT lever, unresolvable curated ref) and the usual
257 ``FormatNegotiationError`` / ``TargetProfileError`` from RESOLVE.
258 """
259 from romfarmer.driver.curated import load_curated
261 ws = workspace_root or config_root.parent
262 paths = ResolvePaths(
263 workspace_root=ws, config_dir=config_root, dats_dir=ws / "dats", lists_dir=ws / "lists"
264 )
265 art_dir = artifacts_dir or ws / "artifacts"
266 out_base = output_base or ws / "output" / f"spec-{spec.spec_hash()[:12]}"
267 composed = compose_target(spec.target.frontend, spec.target.device, config_root)
268 roots = load_source_roots(config_root)
270 builds: list[ResolvedBuild] = []
271 for sp in sorted(spec.platforms, key=lambda p: (-p.priority, p.platform)):
272 rc = _resolved_from_spec_platform(sp, composed, config_root, out_base, roots)
273 curated: tuple[frozenset[str], frozenset[str]] | None = (frozenset(), frozenset())
274 if sp.passes.curated_lists.ref is not None:
275 art = load_curated(sp.passes.curated_lists.ref, art_dir)
276 curated = (art.include, art.exclude)
277 rb = resolve_platform(
278 rc,
279 composed,
280 paths,
281 sample_n=sp.passes.sample.n,
282 sample_seed=sp.passes.sample.seed,
283 curated=curated,
284 dat_filter=sp.passes.dat_filter,
285 extra_notes=_NOTES.pop(id(rc), ()),
286 )
287 if sp.compression not in (None, "none") and rb.chain == ("passthrough",):
288 raise SpecError(
289 f"platforms[{sp.platform!r}]: compression {sp.compression!r} resolves to a passthrough "
290 f"chain — extraction is {rc.extraction_type.value!r}; state extraction (disc|cartridge|…) "
291 "or omit compression to take the frontend's preferred format"
292 )
293 builds.append(rb)
294 return tuple(builds)
297# ---------------------------------------------------------------------------
298# Legacy shim: config/builds/<name>.yaml → Spec
299# ---------------------------------------------------------------------------
302def spec_from_build(
303 build_name: str,
304 config_root: Path | None = None,
305 *,
306 freeze_lists: bool = True,
307 artifacts_dir: Path | None = None,
308) -> Spec:
309 """Lower a legacy build (recipes × target) into a ``Spec``.
311 Every choice the resolver made — compression fallbacks, optimizer
312 thresholds (already expanded to per-platform ``min_rating``), selection —
313 is read back from the ``ResolvedPlatformConfig`` and written down
314 explicitly, so the Spec has no recipe or generation indirection.
316 Legacy ``lists/`` curation is frozen into hash-addressed artifacts when
317 ``freeze_lists`` is true (default), so the lowered Spec reproduces the
318 legacy plan exactly.
320 Naming: the legacy pydantic ``config.build_spec.BuildSpec`` keeps its name
321 until this shim is the only reader of ``config/builds``; at that point
322 ``BuildSpec`` is retired and the name is NOT reclaimed — ``Spec`` stays
323 ``Spec`` (recorded per brief v2 changelog item 2).
324 """
325 from romfarmer.core.paths import get_paths
326 from romfarmer.driver.curated import freeze_lists as _freeze
327 from romfarmer.new_orchestrator import NewBuildOrchestrator
328 from romfarmer.utils.storage_budget import parse_size_spec
330 ws = Path(get_paths().workspace_root)
331 cfg = config_root or ws / "config"
332 orch = NewBuildOrchestrator.from_config(build_name, config_root=cfg)
333 bs = orch.build_spec
334 composed = orch.composed_target
335 art_dir = artifacts_dir or ws / "artifacts"
337 roots = load_source_roots(cfg)
339 storage = None
340 shim_notes: list[str] = []
341 if bs.has_budget_constraint():
342 try:
343 storage = parse_size_spec(str(bs.storage_budget))
344 except Exception as exc:
345 shim_notes.append(
346 f"storage_budget {bs.storage_budget!r} not parseable ({exc}); storage_bytes left unset"
347 )
349 platforms: list[SpecPlatform] = []
350 for rc in sorted(orch.resolved_configs, key=lambda r: r.platform):
351 sel = rc.selection
352 dat_src = getattr(getattr(rc, "dat", None), "source", None)
353 dat_src_value = getattr(dat_src, "value", dat_src)
354 dat_filter = dat_src_value is not None and str(dat_src_value) != "none"
355 ref = None
356 if freeze_lists:
357 art = _freeze(rc.platform, ws / "lists", art_dir)
358 ref = art.ref if art is not None else None
359 max_bytes = None
360 if sel is not None and getattr(sel, "max_size_gb", None):
361 max_bytes = int(float(sel.max_size_gb or 0) * 1024**3)
362 platforms.append(
363 SpecPlatform(
364 platform=rc.platform,
365 sources=_alias_sources(rc, roots),
366 extraction=rc.extraction_type.value,
367 compression=rc.compression.value,
368 priority=0,
369 dat=SpecDat(
370 retool_1g1r=dat_is_retool_1g1r(rc),
371 source=str(dat_src_value) if dat_src_value is not None else None,
372 file=str(rc.dat.file) if (rc.dat is not None and rc.dat.file) else None,
373 ),
374 passes=SpecPasses(
375 dat_filter=dat_filter,
376 region=SpecRegion(preferred=tuple(sel.preferred_regions) if sel else ()),
377 rating=SpecRating(
378 min=getattr(sel, "min_rating", None) if sel else None,
379 top_n=getattr(sel, "top_n", None) if sel else None,
380 unrated=(
381 getattr(sel, "unrated", "keep")
382 if sel and getattr(sel, "min_rating", None) is not None
383 else None
384 ),
385 ),
386 curated_lists=SpecCuratedLists(ref=ref),
387 budget=SpecBudget(
388 max_bytes=max_bytes,
389 unrated_as=str(getattr(sel, "unrated_as", "median")) if sel else "median",
390 ),
391 sample=SpecSample(),
392 ),
393 )
394 )
396 spec = Spec(
397 target=SpecTarget(
398 frontend=composed.frontend.name,
399 device=getattr(composed.device, "name", None),
400 storage_bytes=storage,
401 reserve_bytes=None,
402 ),
403 platforms=tuple(platforms),
404 intent=SpecIntent(
405 text=f"lowered from config/builds/{build_name}.yaml (recipes: {', '.join(bs.recipes)})",
406 authored_by="shim:spec_from_build",
407 allocation_note="; ".join(shim_notes),
408 ),
409 )
410 from romfarmer.ir.spec import validate_spec
412 validate_spec(spec)
413 return spec
416def _alias_sources(rc: ResolvedPlatformConfig, roots: dict[str, Path]) -> tuple[Any, ...]:
417 out = []
418 for s in rc.sources:
419 if s.path is None:
420 continue
421 aliased = alias_path(Path(s.path), roots, recursive=bool(s.recursive))
422 if aliased is None:
423 raise SpecError(
424 f"{rc.platform}: source {s.path} is under no named root in config/sources.yaml — "
425 "add a root alias so the Spec stays portable (no absolute paths in specs)"
426 )
427 out.append(aliased)
428 return tuple(out)