Coverage for src/romfarmer/farmhand/optimizer/pool.py: 0%
124 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-04 16:33 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-04 16:33 -0700
1"""Pool manifest: collection and fast in-memory size estimation.
3A pool manifest captures all games from a superset build (min_rating=0.0,
4no size cap) so that the optimizer loop can run fast iterations in memory
5without touching the disk.
7Pool manifests live at::
9 output/{build_name}/.pool/{platform}.json
11Each manifest is a list of :class:`PoolEntry` dicts serialized with
12``dataclasses.asdict``.
14Typical lifecycle
15-----------------
161. Run a superset build (or use an existing broad build output).
172. Call :func:`collect_pool` to walk the output directory, look up ratings
18 from ``romfarmer.db``, and write per-platform JSON manifests.
193. The optimizer loop calls :func:`estimate_build_size` on every iteration —
20 pure in-memory, no disk I/O.
214. On convergence, the full orchestrator re-runs with the winning thresholds.
22"""
24from __future__ import annotations
26import dataclasses
27import json
28import logging
29import os
30import re
31import sqlite3
32from pathlib import Path
34from .state import BuildReport, PoolEntry
36logger = logging.getLogger(__name__)
38_DISC_RE = re.compile(r"\s*\(Disc\s*\d+\)|\s*\(Disk\s*\d+\)", re.IGNORECASE)
41# ---------------------------------------------------------------------------
42# Generation lookup (cached)
43# ---------------------------------------------------------------------------
46def _get_generation(platform: str) -> str:
47 """Platform → generation name; delegates to ``config.generation_loader``."""
48 from romfarmer.config.generation_loader import platform_generation
50 return platform_generation(platform)
53# ---------------------------------------------------------------------------
54# Default thresholds by generation
55# ---------------------------------------------------------------------------
57# Business rules:
58# gen3 / gen4 → floor immediately at 0.0 (tiny files, pack 100%)
59# gen5 / gen5_handheld → start 0.8, loosen in 0.05 steps
60# gen6 / gen6_handheld → start 0.9, tighten aggressively on overshoot
61# gen7 / gen7_handheld → start 0.9 same as gen6
62# others (arcade, portable, unknown) → 0.0
64DEFAULT_THRESHOLDS: dict[str, float] = {
65 "gen3": 0.0,
66 "gen4": 0.0,
67 "gen5": 0.8,
68 "gen5_handheld": 0.8,
69 "gen6": 0.9,
70 "gen6_handheld": 0.9,
71 "gen7": 0.9,
72 "gen7_handheld": 0.9,
73 "arcade": 0.0,
74 "portable": 0.0,
75 "unknown": 0.0,
76}
79# ---------------------------------------------------------------------------
80# Rating DB helpers
81# ---------------------------------------------------------------------------
84def _open_metadata_db(workspace_root: Path) -> Path | None:
85 """Locate romfarmer.db under the workspace."""
86 candidates = [
87 workspace_root / "metadata" / "database" / "romfarmer.db",
88 workspace_root / "romfarmer.db",
89 ]
90 for p in candidates:
91 if p.exists():
92 return p
93 return None
96def _fetch_ratings(db_path: Path, game_names: list[str]) -> dict[str, float]:
97 """Query scraped_games for ratings by base game name (best-effort fuzzy)."""
98 if not db_path or not db_path.exists():
99 return {}
101 conn = sqlite3.connect(str(db_path))
102 cursor = conn.cursor()
103 ratings: dict[str, float] = {}
105 for name in game_names:
106 try:
107 cursor.execute(
108 "SELECT rating FROM scraped_games WHERE name LIKE ? OR filename LIKE ? "
109 "ORDER BY rating DESC LIMIT 1",
110 (f"%{name}%", f"%{name}%"),
111 )
112 row = cursor.fetchone()
113 if row and row[0] is not None:
114 ratings[name] = float(row[0])
115 except Exception:
116 pass
118 conn.close()
119 return ratings
122# ---------------------------------------------------------------------------
123# collect_pool
124# ---------------------------------------------------------------------------
127def collect_pool(
128 build_name: str,
129 output_base: Path,
130 workspace_root: Path | None = None,
131) -> Path:
132 """Walk a superset build output directory and write pool manifests.
134 For each platform directory found under ``output_base / build_name /``,
135 enumerate all output files, group them by multi-disc base name, look up
136 ratings from ``romfarmer.db``, determine generation, and write a JSON
137 manifest to ``output_base / build_name / .pool / {platform}.json``.
139 Args:
140 build_name: Build name (e.g. "nointro-1g1r-eng-7z-batocera").
141 output_base: Base output directory (typically ``output/``).
142 workspace_root: Workspace root for locating metadata DB.
143 Defaults to ``output_base.parent``.
145 Returns:
146 Path to the pool root directory (``output_base / build_name / .pool``).
147 """
148 if workspace_root is None:
149 workspace_root = output_base.parent
151 build_output = output_base / build_name
152 if not build_output.exists():
153 raise FileNotFoundError(f"Build output not found: {build_output}")
155 pool_root = build_output / ".pool"
156 pool_root.mkdir(parents=True, exist_ok=True)
158 db_path = _open_metadata_db(workspace_root)
159 if db_path is None:
160 logger.warning("romfarmer.db not found; all ratings will be 0.0")
162 manifests_written = 0
164 for platform_dir in sorted(build_output.iterdir()):
165 if platform_dir.name.startswith(".") or not platform_dir.is_dir():
166 continue
168 platform = platform_dir.name
169 generation = _get_generation(platform)
170 entries = _collect_platform_entries(platform_dir, platform, generation, db_path)
172 manifest_path = pool_root / f"{platform}.json"
173 _write_manifest(manifest_path, entries)
174 logger.info(f" Pool manifest: {platform} → {len(entries)} games")
175 manifests_written += 1
177 logger.info(f"Collected pool: {manifests_written} platforms → {pool_root}")
178 return pool_root
181def _collect_platform_entries(
182 platform_dir: Path,
183 platform: str,
184 generation: str,
185 db_path: Path | None,
186) -> list[PoolEntry]:
187 """Enumerate files in a platform output directory → list of PoolEntry."""
188 # Group files by base game name (strip disc suffix)
189 groups: dict[str, list[Path]] = {}
190 for root, _dirs, files in os.walk(platform_dir):
191 for fname in files:
192 if fname.startswith("."):
193 continue
194 fpath = Path(root) / fname
195 stem = fpath.stem
196 base = _DISC_RE.sub("", stem).strip()
197 groups.setdefault(base, []).append(fpath)
199 if not groups:
200 return []
202 # Fetch ratings in one batch
203 ratings = _fetch_ratings(db_path, list(groups.keys())) if db_path else {}
205 entries: list[PoolEntry] = []
206 for base_name, disc_files in sorted(groups.items()):
207 total_size = sum(f.stat().st_size for f in disc_files if f.exists())
208 rating = ratings.get(base_name, 0.0)
209 is_multi = len(disc_files) > 1
210 entries.append(
211 PoolEntry(
212 name=base_name,
213 rating=rating,
214 generation=generation,
215 size_bytes=total_size,
216 multi_disc_group=base_name if is_multi else None,
217 is_disc_anchor=True,
218 platform=platform,
219 )
220 )
221 return entries
224def _write_manifest(path: Path, entries: list[PoolEntry]) -> None:
225 payload = [dataclasses.asdict(e) for e in entries]
226 with open(path, "w") as f:
227 json.dump(payload, f, indent=2)
230# ---------------------------------------------------------------------------
231# load_pool
232# ---------------------------------------------------------------------------
235def load_pool(pool_root: Path) -> dict[str, list[PoolEntry]]:
236 """Load all per-platform pool manifests from ``pool_root``.
238 Returns:
239 Mapping of platform name → list of PoolEntry objects.
240 """
241 result: dict[str, list[PoolEntry]] = {}
242 if not pool_root.exists():
243 return result
245 for manifest_path in sorted(pool_root.glob("*.json")):
246 platform = manifest_path.stem
247 try:
248 with open(manifest_path) as f:
249 raw = json.load(f)
250 result[platform] = [PoolEntry(**entry) for entry in raw]
251 except Exception as e:
252 logger.warning(f"Failed to load pool manifest {manifest_path}: {e}")
254 return result
257# ---------------------------------------------------------------------------
258# estimate_build_size (the hot loop path)
259# ---------------------------------------------------------------------------
262def estimate_build_size(
263 pool: dict[str, list[PoolEntry]],
264 thresholds: dict[str, float],
265 platform_overrides: dict[str, float] | None = None,
266) -> BuildReport:
267 """Apply thresholds to the pool and return an estimated BuildReport.
269 This is pure in-memory — no disk I/O. O(N) in total game count.
271 Args:
272 pool: Platform → entries, from :func:`load_pool`.
273 thresholds: Generation name → min_rating. Unknown generations
274 default to 0.0.
275 platform_overrides: Optional per-platform min_rating that takes
276 precedence over the generation threshold.
278 Returns:
279 :class:`BuildReport` with ``is_estimated=True``.
280 """
281 overrides = platform_overrides or {}
283 total_bytes = 0
284 per_platform: dict[str, int] = {}
285 per_gen_bytes: dict[str, int] = {}
286 per_gen_count: dict[str, int] = {}
287 per_platform_count: dict[str, int] = {}
288 multi_disc_groups = 0
289 total_games = 0
291 for platform, entries in pool.items():
292 platform_bytes = 0
293 platform_count = 0
295 for entry in entries:
296 threshold = overrides.get(platform, thresholds.get(entry.generation, 0.0))
297 if entry.rating >= threshold:
298 platform_bytes += entry.size_bytes
299 platform_count += 1
300 per_gen_bytes[entry.generation] = (
301 per_gen_bytes.get(entry.generation, 0) + entry.size_bytes
302 )
303 per_gen_count[entry.generation] = per_gen_count.get(entry.generation, 0) + 1
304 if entry.multi_disc_group is not None:
305 multi_disc_groups += 1
307 per_platform[platform] = platform_bytes
308 per_platform_count[platform] = platform_count
309 total_bytes += platform_bytes
310 total_games += platform_count
312 return BuildReport(
313 total_size_bytes=total_bytes,
314 per_platform_sizes=per_platform,
315 per_generation_sizes=per_gen_bytes,
316 per_generation_game_counts=per_gen_count,
317 per_platform_game_counts=per_platform_count,
318 multi_disc_groups_included=multi_disc_groups,
319 total_game_count=total_games,
320 is_estimated=True,
321 )