Coverage for src/romfarmer/planner/costmodel.py: 50%

82 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1"""CostModel — enum-keyed compression ratio service. 

2 

3Design decisions (from the architecture blueprint): 

4- **Single service** — all size predictions come from here; no scattered 

5 defaults elsewhere. 

6- **Enum-keyed** — ``(platform, tool)`` key. Unknown platform → loud 

7 ``UnknownPlatformError``, not a silent fallback. This surfaces missing 

8 config early rather than silently producing wrong budgets. 

9- **Priors from ``size_data.json``** — historical output sizes recorded after 

10 real builds. 

11- **Posteriors from telemetry** — ``KnowledgeBase.get_compression_ratio`` 

12 feeds back actual ``source_size / output_size`` ratios from 

13 ``ROMTransformation`` rows. 

14- **Bayesian merge** — weighted average; telemetry weight scales with sample 

15 count up to a cap of 1.0 (full confidence at ``TELEMETRY_CAP`` samples). 

16""" 

17 

18from __future__ import annotations 

19 

20import json 

21import logging 

22from pathlib import Path 

23from typing import TYPE_CHECKING 

24 

25if TYPE_CHECKING: 

26 from romfarmer.analysis.knowledge import KnowledgeBase 

27 

28logger = logging.getLogger(__name__) 

29 

30# --------------------------------------------------------------------------- 

31# Priors. ratio = output_bytes / input_bytes where input_bytes is what the 

32# budget pass actually feeds in: ``GameUnit.source_size`` — the SOURCE FILE 

33# bytes (a No-Intro .zip, a Redump .zip), NOT the uncompressed ROM. 

34# 

35# Measured 2026-09-03 (review P0 item 2): 

36# 7z: output/nointro-1g1r-eng-7z-batocera-v2/<platform>/*.7z vs the source 

37# .zip size from file_digest_cache — 7z re-compression of a zip saves 

38# only 7–20 %. The previous table (nes 0.55, snes 0.60 …) was relative 

39# to uncompressed ROM bytes and over-predicted savings by ~40 %. 

40# chd: psx from unit_telemetry (smoke-psx-chd n=12) — 0.828 vs the source 

41# zip. Legacy rom_transformations ratios were vs uncompressed bytes 

42# and are deliberately not used (see the disc block below). 

43# Unmeasured platforms fall back to ``_FAMILY_PRIORS`` by tool (label 

44# ``prior:family:<tool>``) — visible in every budget PassTrace reason so an 

45# operator can see when a number is a family guess rather than a measurement. 

46# --------------------------------------------------------------------------- 

47_HARDCODED_PRIORS: dict[str, dict[str, float]] = { 

48 # platform → {tool → ratio} 

49 # ── disc ── 

50 # psx measured 2026-09-03 from unit_telemetry (smoke-psx-chd, n=12, CHD vs 

51 # SOURCE ZIP bytes: agg 0.828, per-unit 0.66–0.98). The legacy 

52 # rom_transformations numbers (psx 0.551, dreamcast 0.353, xbox 0.279 …) 

53 # were measured against the UNCOMPRESSED bin/iso and under-predict output 

54 # by ~⅓ — the unsafe direction for a storage budget. They are NOT used; 

55 # every other disc platform takes the family prior until its own 

56 # unit_telemetry accumulates. 

57 "psx": {"chd": 0.83}, 

58 "psp": {"cso": 0.85, "chd": 0.85}, 

59 "pspminis": {"chd": 0.85, "passthrough": 1.0}, 

60 "ps3": {"passthrough": 0.90, "ps3": 0.90}, 

61 # xbox measured 2026-09-04 from unit_telemetry (smoke-xbox-xiso, n=4, XISO vs 

62 # SOURCE ZIP: agg 0.359, per-title 0.15–0.60 — padding-dominated Redump ISOs 

63 # vs full ones). Prior hedged HIGH (0.50) because n is tiny and 

64 # under-prediction overfills a card; the posterior takes over as samples 

65 # accumulate. The old family guess 0.70 was 2× too high. 

66 "xbox": {"xiso": 0.50}, 

67 "gamecube": {"rvz": 1.0}, # source is already .rvz inside the zip 

68 "wii": {"rvz": 1.0}, 

69 "wiiu": {"wux": 1.0}, 

70 # ── cartridge / handheld (measured, 7z vs source zip) ── 

71 "atari2600": {"7z": 0.977, "zip": 1.0}, # n=696 

72 "atari5200": {"7z": 0.928, "zip": 1.0}, # n=134 

73 "atari7800": {"7z": 0.856, "zip": 1.0}, # n=81 

74 "atarijaguar": {"7z": 0.910, "zip": 1.0}, # n=70 

75 "atarilynx": {"7z": 0.910, "zip": 1.0}, # n=103 

76 "colecovision": {"7z": 0.933, "zip": 1.0}, # n=165 

77 "fds": {"7z": 0.877, "zip": 1.0}, # n=257 

78 "gamegear": {"7z": 0.880, "zip": 1.0}, # n=300 

79 "gb": {"7z": 0.886, "zip": 1.0}, # n=666 

80 "gb2players": {"7z": 0.881, "zip": 1.0}, # n=799 

81 "gba": {"7z": 0.829, "zip": 1.0}, # n=1137 

82 "gbc": {"7z": 0.820, "zip": 1.0}, # n=667 

83 "gbc2players": {"7z": 0.800, "zip": 1.0}, # n=1013 

84 "intellivision": {"7z": 0.861, "zip": 1.0}, # n=133 

85 "mastersystem": {"7z": 0.879, "zip": 1.0}, # n=408 

86 "megadrive": {"7z": 0.857, "zip": 1.0}, # n=937 

87 "msx1": {"7z": 0.915, "zip": 1.0}, # n=37 

88 "msx2": {"7z": 0.890, "zip": 1.0}, # n=20 

89 "n64": {"7z": 0.921, "zip": 1.0}, # n=373 

90 "nds": {"7z": 0.814, "zip": 1.0}, # n=866 

91 "sgb": {"7z": 0.872, "zip": 1.0}, # n=100 

92 "sgb-gbc": {"7z": 0.813, "zip": 1.0}, # n=58 

93 "snes": {"7z": 0.894, "zip": 1.0}, # n=895 

94 # ── cartridge (unmeasured — family prior applies via _FAMILY_PRIORS) ── 

95 "nes": {"7z": 0.88, "zip": 1.0}, 

96 "3ds": {"passthrough": 1.00}, 

97 "switch": {"passthrough": 1.00}, 

98 # ── arcade (source zip copied as-is) ── 

99 "arcade": {"zip": 1.0, "passthrough": 1.0, "arcade": 1.0}, 

100 "mame": {"zip": 1.0, "passthrough": 1.0, "arcade": 1.0}, 

101 "fbneo": {"zip": 1.0, "passthrough": 1.0, "arcade": 1.0}, 

102 "neogeo": {"zip": 1.0, "passthrough": 1.0, "arcade": 1.0}, 

103} 

104 

105# Tool-family fallback for platforms with no measured prior. Values are the 

106# medians of the measured platforms above (7z: 0.877 across 23 platforms; 

107# chd: 0.83 from psx, n=12). Deliberately on the HIGH side: over-predicting 

108# under-fills a card (safe, re-run picks it up); under-predicting overfills it. 

109_FAMILY_PRIORS: dict[str, float] = { 

110 "7z": 0.88, 

111 "zip": 1.0, 

112 "chd": 0.85, 

113 "cue_bin": 1.0, 

114 "iso": 1.0, 

115 "xiso": 0.60, # xbox measured 0.36 (n=4); hedged high 

116 "squashfs": 0.60, 

117 "rvz": 1.0, 

118 "wux": 1.0, 

119 "ps3": 0.90, 

120 "cso": 0.85, 

121 "passthrough": 1.0, 

122 "arcade": 1.0, 

123} 

124 

125# Number of telemetry samples needed for full confidence 

126_TELEMETRY_CAP = 100 

127 

128# Default tool per platform when caller does not specify. The budget pass 

129# passes ``manifest.chain[0]`` so this is only a last resort. 

130_DEFAULT_TOOL: dict[str, str] = { 

131 plat: next(iter(tools)) for plat, tools in _HARDCODED_PRIORS.items() 

132} 

133 

134 

135class UnknownPlatformError(KeyError): 

136 """Raised when ``CostModel`` is queried for an unregistered platform. 

137 

138 Never silently returns 0.85 or any other magic constant — the caller 

139 must register a prior or handle this explicitly. 

140 """ 

141 

142 

143class CostModel: 

144 """Compression-ratio service for the budget pass. 

145 

146 Args: 

147 size_data_path: Path to ``config/size_data.json``. ``None`` means 

148 use only hard-coded priors. 

149 knowledge_base: Optional KB for telemetry posteriors. When ``None``, 

150 only priors are used. 

151 """ 

152 

153 def __init__( 

154 self, 

155 size_data_path: Path | None = None, 

156 knowledge_base: KnowledgeBase | None = None, 

157 ) -> None: 

158 # {platform: {tool: ratio}} 

159 self._priors: dict[str, dict[str, float]] = { 

160 plat: dict(tools) for plat, tools in _HARDCODED_PRIORS.items() 

161 } 

162 self._kb = knowledge_base 

163 

164 if size_data_path is not None and size_data_path.exists(): 

165 self._load_size_data(size_data_path) 

166 

167 # ------------------------------------------------------------------ 

168 # Public API 

169 # ------------------------------------------------------------------ 

170 

171 def ratio( 

172 self, 

173 platform: str, 

174 tool: str | None = None, 

175 ) -> tuple[float, str]: 

176 """Return ``(ratio, source_label)`` for *platform*. 

177 

178 *ratio* is ``output_bytes / input_bytes``. 

179 

180 Raises: 

181 UnknownPlatformError: if no prior or telemetry exists for *platform*. 

182 """ 

183 if tool is None and platform not in self._priors: 

184 # No tool named and no platform prior: nothing to reason from. 

185 # Loud by design — never a silent magic constant. 

186 raise UnknownPlatformError( 

187 f"CostModel: no prior registered for platform={platform!r} and no " 

188 f"tool given. Add an entry to _HARDCODED_PRIORS or pass tool=." 

189 ) 

190 resolved_tool = _normalise_tool(tool or _DEFAULT_TOOL.get(platform, "passthrough")) 

191 prior, prior_label = self._prior_ratio(platform, resolved_tool) 

192 if prior is None: 

193 raise UnknownPlatformError( 

194 f"CostModel: no prior registered for platform={platform!r} " 

195 f"tool={resolved_tool!r} and no family prior for that tool. " 

196 f"Add an entry to _HARDCODED_PRIORS or _FAMILY_PRIORS." 

197 ) 

198 

199 # Telemetry posterior — weight grows with the REAL sample count 

200 if self._kb is not None: 

201 tel = self._kb.get_compression_ratio(platform, resolved_tool) 

202 if tel is not None: 

203 tel_ratio, n = tel 

204 weight = min(1.0, n / _TELEMETRY_CAP) 

205 merged = prior * (1.0 - weight) + tel_ratio * weight 

206 label = f"merged:{prior_label}={prior:.3f},telemetry={tel_ratio:.3f},n={n}" 

207 return merged, label 

208 

209 return prior, prior_label 

210 

211 def predict_output_bytes( 

212 self, 

213 source_bytes: int, 

214 platform: str, 

215 tool: str | None = None, 

216 ) -> tuple[int, str]: 

217 """Return ``(predicted_output_bytes, source_label)``.""" 

218 r, label = self.ratio(platform, tool) 

219 return int(source_bytes * r), label 

220 

221 def register_prior(self, platform: str, tool: str, ratio: float) -> None: 

222 """Register or override a prior for *platform* / *tool*. 

223 

224 Useful in tests and for platforms not in the built-in table. 

225 """ 

226 if platform not in self._priors: 

227 self._priors[platform] = {} 

228 self._priors[platform][tool] = ratio 

229 

230 # ------------------------------------------------------------------ 

231 # Private 

232 # ------------------------------------------------------------------ 

233 

234 def _prior_ratio(self, platform: str, tool: str) -> tuple[float | None, str]: 

235 """``(ratio, label)`` — exact (platform, tool) first, else the tool family. 

236 

237 The old behaviour fell through to "any tool for this platform", which 

238 made the tool key decorative (a snes ``zip`` prior answered ``7z``). 

239 """ 

240 plat_entry = self._priors.get(platform) 

241 if plat_entry is not None and tool in plat_entry: 

242 return plat_entry[tool], "prior:measured" 

243 fam = _FAMILY_PRIORS.get(tool) 

244 if fam is not None: 

245 return fam, f"prior:family:{tool}" 

246 return None, "prior:none" 

247 

248 def _load_size_data(self, path: Path) -> None: 

249 """Load ``size_data.json`` and update priors. 

250 

251 ``size_data.json`` format:: 

252 

253 { 

254 "<platform>": [ 

255 { 

256 "output_size_bytes": 453980902260, 

257 "input_size_bytes": 670000000000, 

258 "compression": "chd", 

259 ... 

260 }, 

261 ... 

262 ] 

263 } 

264 

265 Only records with both ``input_size_bytes > 0`` and 

266 ``output_size_bytes > 0`` are used. 

267 """ 

268 try: 

269 raw = json.loads(path.read_text()) 

270 except (json.JSONDecodeError, OSError) as exc: 

271 logger.warning("CostModel: could not load %s: %s", path, exc) 

272 return 

273 

274 for platform, records in raw.items(): 

275 if not isinstance(records, list): 

276 continue 

277 platform_key = _normalise_platform(platform) 

278 totals: dict[str, tuple[float, float]] = {} # tool → (sum_in, sum_out) 

279 for rec in records: 

280 if not isinstance(rec, dict): 

281 continue 

282 in_b = rec.get("input_size_bytes") or 0 

283 out_b = rec.get("output_size_bytes") or 0 

284 if in_b <= 0 or out_b <= 0: 

285 continue 

286 tool_key = _normalise_tool(rec.get("compression") or "passthrough") 

287 prev = totals.get(tool_key, (0.0, 0.0)) 

288 totals[tool_key] = (prev[0] + in_b, prev[1] + out_b) 

289 

290 for tool_key, (total_in, total_out) in totals.items(): 

291 if total_in > 0: 

292 ratio = total_out / total_in 

293 if platform_key not in self._priors: 

294 self._priors[platform_key] = {} 

295 self._priors[platform_key][tool_key] = ratio 

296 logger.debug( 

297 "CostModel: loaded prior platform=%s tool=%s ratio=%.3f", 

298 platform_key, 

299 tool_key, 

300 ratio, 

301 ) 

302 

303 

304def _normalise_platform(name: str) -> str: 

305 """Lower-case + strip whitespace.""" 

306 return name.lower().strip() 

307 

308 

309def _normalise_tool(name: str) -> str: 

310 """Normalise compression string to a canonical tool key.""" 

311 name = name.lower().strip() 

312 _map = { 

313 "none": "passthrough", 

314 "": "passthrough", 

315 "chdman": "chd", 

316 "dolphin-rvz": "rvz", 

317 "extract-xiso": "xiso", 

318 "maxcso": "cso", 

319 "wit": "wux", 

320 } 

321 return _map.get(name, name)