Coverage for src/romfarmer/config/resolver.py: 72%
190 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"""Config resolver — the composition engine.
3The resolver takes a BuildSpec and produces a ResolvedPlatformConfig for
4each platform in the build. This is the heart of the new system.
6Resolution algorithm:
7 for each platform in (union of recipe platforms) - excludes:
8 1. Load SlimPlatformConfig (intrinsic facts)
9 2. Stack recipes in order (later wins for overlapping fields)
10 3. Apply target constraints (frontend compression fallback, folder mapping)
11 4. Apply device filter (skip unsupported platforms)
12 5. Apply budget/tier constraints (if applicable)
13 6. Derive output path
14 → emit ResolvedPlatformConfig
15"""
17import logging
18from dataclasses import MISSING, dataclass, field, fields, make_dataclass
19from pathlib import Path
20from typing import Any
22from .build_spec import BuildSpec
23from .models import (
24 CompressionFormat,
25 ExtractionType,
26 MetadataFilterConfig,
27 SelectionConfig,
28 SourceConfig,
29)
30from .recipe import RecipeSpec
31from .slim_platform import (
32 ArcadeFilter,
33 DATReference,
34 ListPatterns,
35 PS3Config,
36 SlimPlatformConfig,
37 XboxConfig,
38)
39from .target import ComposedTarget
41logger = logging.getLogger(__name__)
44@dataclass(frozen=True)
45class ResolvedPlatformConfig:
46 """Fully resolved configuration for one platform in one build.
48 This is the output of the resolver — everything needed to build
49 a pipeline for this platform. No further lookups needed.
51 Frozen (2026-09-03): RESOLVE's output is a value. The resolver composes
52 it on a mutable ``_ResolvedDraft`` and emits it once; later stages use
53 ``dataclasses.replace`` for derived copies (e.g. tier assignment).
54 """
56 # Identity
57 platform: str
58 display_name: str | None = None
59 platform_type: str | None = None # 'arcade' or None
60 emulator: str | None = None
61 metadata_system: str | None = None
63 # Processing
64 extraction_type: ExtractionType = ExtractionType.NONE
65 compression: CompressionFormat = CompressionFormat.NONE
66 multi_disc: bool = False
68 # DAT
69 dat: DATReference | None = None
71 # Sources
72 sources: list[SourceConfig] = field(default_factory=list)
73 chd_sources: list[SourceConfig] | None = None
75 # Filtering
76 selection: SelectionConfig | None = None
77 metadata_filter: MetadataFilterConfig | None = None
78 apply_lists: bool = True
79 list_patterns: ListPatterns | None = None
80 arcade_filter: ArcadeFilter | None = None
81 bios: list[str] | None = None
82 samples_sources: list[SourceConfig] | None = None
84 # Output
85 output_dir: Path | None = None
86 folder_name: str = "" # From frontend folder mapping
87 organization: str = "flat" # From frontend/target default
88 metadata: bool = True
90 # Platform-specific
91 ps3: PS3Config | None = None
92 xbox: XboxConfig | None = None
94 # Extras (DLC/updates)
95 extras: Any | None = None # ExtrasConfig from slim_platform
97 # Build context
98 tier: int | None = None
99 tier_strategy: str | None = None
101 # Source recipe name (for debugging/logging)
102 recipe_name: str | None = None
104 @property
105 def is_arcade(self) -> bool:
106 """Check if this is an arcade platform."""
107 return self.platform_type == "arcade"
109 def get_metadata_system(self) -> str:
110 """Get the system name for metadata lookups."""
111 return self.metadata_system or self.platform
114def _make_draft_type() -> type:
115 """Mutable twin of ``ResolvedPlatformConfig`` used only while composing."""
116 spec = []
117 for f in fields(ResolvedPlatformConfig):
118 if f.default_factory is not MISSING:
119 spec.append((f.name, f.type, field(default_factory=f.default_factory)))
120 elif f.default is not MISSING:
121 spec.append((f.name, f.type, field(default=f.default)))
122 else:
123 spec.append((f.name, f.type))
124 return make_dataclass("_ResolvedDraft", spec)
127_ResolvedDraft = _make_draft_type()
130def _freeze(draft: Any) -> ResolvedPlatformConfig:
131 return ResolvedPlatformConfig(
132 **{f.name: getattr(draft, f.name) for f in fields(ResolvedPlatformConfig)}
133 )
136class ConfigResolver:
137 """Resolves a BuildSpec into per-platform ResolvedPlatformConfigs.
139 This is the composition engine that merges:
140 platform intrinsics + recipe choices + target constraints = resolved config
141 """
143 def __init__(
144 self,
145 platforms: dict[str, SlimPlatformConfig],
146 recipes: dict[str, RecipeSpec],
147 composed_target: ComposedTarget | None = None,
148 ):
149 """Initialize the resolver.
151 Args:
152 platforms: Map of platform name → SlimPlatformConfig
153 recipes: Map of recipe name → RecipeSpec
154 composed_target: Loaded target (frontend + device)
155 """
156 self.platforms = platforms
157 self.recipes = recipes
158 self.composed_target = composed_target
160 def resolve(
161 self,
162 build: BuildSpec,
163 ) -> list[ResolvedPlatformConfig]:
164 """Resolve a build spec into per-platform configs.
166 Args:
167 build: The build specification
169 Returns:
170 List of ResolvedPlatformConfig, one per platform
171 """
172 # Step 1: Determine which platforms to process
173 platform_names = self._collect_platforms(build)
174 logger.info(f"Resolved {len(platform_names)} platforms for build '{build.name}'")
176 # Step 2: Load recipes referenced by this build
177 build_recipes = self._load_build_recipes(build)
179 # Step 3: Resolve each platform
180 resolved = []
181 for platform_name in sorted(platform_names):
182 platform = self.platforms.get(platform_name)
183 if platform is None:
184 logger.warning(f"Platform '{platform_name}' not found, skipping")
185 continue
187 config = self._resolve_platform(
188 platform=platform,
189 recipes=build_recipes,
190 build=build,
191 )
193 if config is not None:
194 resolved.append(config)
196 return resolved
198 def _collect_platforms(self, build: BuildSpec) -> set[str]:
199 """Determine which platforms to process for this build.
201 Priority:
202 1. If build.platforms is set, use exactly those
203 2. Otherwise, union of all recipe platform lists
204 3. Minus build.exclude
205 4. Minus device unsupported platforms
206 """
207 if build.platforms is not None:
208 # Explicit platform list
209 platform_names = set(build.platforms)
210 else:
211 # Union of all recipe platform lists
212 platform_names = set()
213 for recipe_name in build.recipes:
214 recipe = self.recipes.get(recipe_name)
215 if recipe is None:
216 raise ValueError(f"Recipe '{recipe_name}' not found")
217 if recipe.platforms:
218 platform_names.update(recipe.platforms)
219 # Recipes with empty platforms don't contribute to the union
220 # (they apply to whatever other recipes bring in)
222 # Apply excludes
223 platform_names -= set(build.exclude)
225 # Apply device unsupported filter
226 if self.composed_target:
227 unsupported = set()
228 for name in platform_names:
229 if not self.composed_target.supports_platform(name):
230 unsupported.add(name)
231 logger.info(
232 f"Platform '{name}' not supported by device '{self.composed_target.device.name}', excluding"
233 )
234 platform_names -= unsupported
236 return platform_names
238 def _load_build_recipes(self, build: BuildSpec) -> list[RecipeSpec]:
239 """Load and validate recipes referenced by the build."""
240 recipes = []
241 for recipe_name in build.recipes:
242 recipe = self.recipes.get(recipe_name)
243 if recipe is None:
244 raise ValueError(
245 f"Recipe '{recipe_name}' not found. "
246 f"Available recipes: {', '.join(sorted(self.recipes.keys()))}"
247 )
248 recipes.append(recipe)
249 return recipes
251 def _resolve_platform(
252 self,
253 platform: SlimPlatformConfig,
254 recipes: list[RecipeSpec],
255 build: BuildSpec,
256 ) -> ResolvedPlatformConfig | None:
257 """Resolve a single platform by stacking recipes on top of intrinsics.
259 Returns None if the platform should be skipped.
260 """
261 # Start with intrinsics (mutable draft; frozen on return)
262 config = _ResolvedDraft(
263 platform=platform.name,
264 display_name=platform.display_name,
265 platform_type=platform.type,
266 emulator=platform.emulator,
267 metadata_system=platform.metadata_system,
268 extraction_type=platform.extraction,
269 multi_disc=platform.multi_disc,
270 dat=platform.dat,
271 sources=platform.sources,
272 chd_sources=platform.chd_sources,
273 list_patterns=platform.list_patterns,
274 arcade_filter=platform.arcade_filter,
275 bios=platform.bios,
276 samples_sources=platform.samples_sources,
277 ps3=platform.ps3,
278 xbox=platform.xbox,
279 extras=platform.extras,
280 )
282 # Stack recipes in order (later wins for overlapping fields)
283 last_matching_recipe = None
284 for recipe in recipes:
285 if recipe.applies_to(platform.name):
286 self._apply_recipe(config, recipe)
287 last_matching_recipe = recipe.name
289 config.recipe_name = last_matching_recipe
291 # Apply optimizer generation thresholds (before global selection override
292 # so that explicit build.selection can still win if set).
293 if build.optimizer_thresholds:
294 self._apply_optimizer_thresholds(config, build.optimizer_thresholds)
296 # Apply build-level selection override (if any)
297 if build.selection is not None:
298 config.selection = build.selection
300 # Apply target constraints
301 if self.composed_target:
302 self._apply_target_constraints(config, platform.name)
304 # Derive output path
305 config.output_dir = self._derive_output_path(config, build)
307 return _freeze(config)
309 def _apply_recipe(
310 self,
311 config: Any, # _ResolvedDraft (mutable) — frozen by _resolve_platform
312 recipe: RecipeSpec,
313 ) -> None:
314 """Apply a recipe's processing choices to a resolved config.
316 Mutates config in place. Later recipes override earlier ones.
317 """
318 # Compression
319 if recipe.compression is not None:
320 effective = recipe.get_effective_compression()
321 if effective is not None:
322 config.compression = effective
324 # Selection (stacks — later recipe replaces)
325 if recipe.selection is not None:
326 config.selection = recipe.selection
328 # Metadata filter (stacks — later recipe replaces)
329 if recipe.metadata_filter is not None:
330 config.metadata_filter = recipe.metadata_filter
332 # Apply lists
333 if recipe.apply_lists is not None:
334 config.apply_lists = recipe.apply_lists
336 # Metadata
337 if recipe.metadata is not None:
338 config.metadata = recipe.metadata
340 # Arcade filter overrides
341 if recipe.arcade_filter_overrides is not None and config.arcade_filter is not None:
342 # Merge overrides into existing arcade filter
343 af_data = config.arcade_filter.model_dump()
344 af_data.update(recipe.arcade_filter_overrides)
345 config.arcade_filter = ArcadeFilter(**af_data)
347 # PS3 overrides
348 if recipe.ps3_updates_enabled is not None and config.ps3 is not None:
349 ps3_data = config.ps3.model_dump()
350 ps3_data["use_sony_psn"] = recipe.ps3_updates_enabled
351 config.ps3 = PS3Config(**ps3_data)
353 if recipe.ps3_dlc_enabled is not None and config.ps3 is not None:
354 ps3_data = config.ps3.model_dump()
355 ps3_data["dlc_enabled"] = recipe.ps3_dlc_enabled
356 config.ps3 = PS3Config(**ps3_data)
358 def _apply_target_constraints(
359 self,
360 config: Any, # _ResolvedDraft (mutable) — frozen by _resolve_platform
361 platform_name: str,
362 ) -> None:
363 """Apply target (frontend + device) constraints.
365 - Folder name mapping from frontend
366 - Compression fallback (e.g., 7z → zip for RocknIX)
367 - Default organization style from frontend
368 - Metadata default from frontend
369 """
370 target = self.composed_target
371 if target is None:
372 return
374 # Folder name from frontend mapping
375 config.folder_name = target.get_folder_name(platform_name)
377 # Organization from frontend defaults
378 if hasattr(target.frontend, "defaults") and target.frontend.defaults:
379 config.organization = target.frontend.defaults.organization
380 config.metadata = target.frontend.defaults.metadata
382 # Compression fallback
383 # If the recipe set 7z but the frontend doesn't support it, fall back
384 if config.compression != CompressionFormat.NONE:
385 fallback = getattr(target.frontend, "compression_fallback", {})
386 if fallback:
387 comp_str = config.compression.value
388 if comp_str in fallback:
389 fallback_str = fallback[comp_str]
390 try:
391 config.compression = CompressionFormat(fallback_str)
392 logger.info(
393 f" {platform_name}: compression fallback "
394 f"{comp_str} → {fallback_str} (frontend: {target.frontend.name})"
395 )
396 except ValueError:
397 logger.warning(f" Invalid fallback format: {fallback_str}")
399 # Override with target's preferred compression if set
400 target_pref = target.get_preferred_compression(platform_name, default=None)
401 if target_pref and target_pref != "none":
402 try:
403 pref_format = CompressionFormat(target_pref)
404 # Only override if recipe didn't explicitly set something
405 # (target preferred is a hint, recipe is explicit)
406 if config.compression == CompressionFormat.NONE:
407 config.compression = pref_format
408 except ValueError:
409 pass
411 def _apply_optimizer_thresholds(
412 self,
413 config: Any, # _ResolvedDraft (mutable) — frozen by _resolve_platform
414 thresholds: dict[str, float],
415 ) -> None:
416 """Apply per-generation optimizer thresholds as a per-platform min_rating.
418 Looks up the platform's generation (via CONSOLE_GENERATIONS) and, if
419 the generation has a non-zero threshold, installs a SelectionConfig
420 with ``min_rating`` set accordingly.
422 The existing ``config.selection`` is preserved and only
423 ``min_rating`` is overridden, so other selection constraints
424 (e.g., ``top_n``, ``max_size_gb``) remain intact.
425 """
426 from romfarmer.config.generation_loader import platform_generation
428 gen = platform_generation(config.platform)
429 threshold = thresholds.get(gen, 0.0)
431 if threshold <= 0.0:
432 # Floor gens (gen3/gen4/arcade) — include everything, no filter needed
433 return
435 if config.selection is not None:
436 # Patch the existing SelectionConfig in place (copy with new min_rating)
437 existing = config.selection.model_dump()
438 existing["min_rating"] = threshold
439 config.selection = SelectionConfig(**existing)
440 else:
441 config.selection = SelectionConfig(min_rating=threshold)
443 logger.debug(
444 f" {config.platform}: optimizer threshold {gen}={threshold:.2f} "
445 f"→ selection.min_rating={threshold:.2f}"
446 )
448 def _derive_output_path(
449 self,
450 config: Any, # _ResolvedDraft or ResolvedPlatformConfig
451 build: BuildSpec,
452 ) -> Path:
453 """Derive the output path for a platform.
455 Pattern: {output_base} / {folder_name}
457 The folder_name comes from the frontend's folder mapping.
458 The output_base comes from the build spec.
459 """
460 output_base = build.get_output_base()
461 folder = config.folder_name or config.platform
462 return output_base / folder
465def resolve_build(
466 build: BuildSpec,
467 platforms: dict[str, SlimPlatformConfig],
468 recipes: dict[str, RecipeSpec],
469 composed_target: ComposedTarget | None = None,
470) -> list[ResolvedPlatformConfig]:
471 """Convenience function to resolve a build in one call.
473 Args:
474 build: Build specification
475 platforms: Map of platform name → SlimPlatformConfig
476 recipes: Map of recipe name → RecipeSpec
477 composed_target: Optional composed target (frontend + device)
479 Returns:
480 List of ResolvedPlatformConfig
481 """
482 resolver = ConfigResolver(
483 platforms=platforms,
484 recipes=recipes,
485 composed_target=composed_target,
486 )
487 return resolver.resolve(build)