Coverage for src/romfarmer/driver/summary.py: 86%
160 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"""PlanSummary — the agent's entire sensory input (intent brief v2 §4, v4 §2).
3Everything the intent loop knows about the world arrives through this
4struct, so every lever it can turn has a signal here:
6- ``rating.min`` → ``rated_fraction``, ``rating_quantiles`` (over the
7 catalog ENTERING the budget pass — solve for a
8 unit count in one step, don't binary-search)
9- ``budget.max_bytes`` → ``bytes_est_p50`` / ``bytes_est_p90`` (telemetry
10 quantiles; the p50/p90 gap is the cost of
11 ignorance — where a sample build would pay).
12 The card binds on AGGREGATE p90 (``fits``); a fixed
13 safety margin is gone.
14- ``rating.min`` → ``bytes_kept_at_rating`` — solve for the threshold
15 in one step so the stated policy, not the budget
16 trim, is why a game is absent
17- rating-per-GB (above seam)→ ``heaviest`` — the 4-disc RPG that costs six
18 single-disc games
19- ``curated_lists.ref`` → ``removed_by_pass.curated_lists``, ``top_dropped``
20- ``dat.retool_1g1r`` → ``removed_by_pass.dat_filter`` (count only; its
21 reasons are uninformative repeats)
22- capability tiers → ``tier`` / ``quality`` per platform
24Size discipline: ~60 tokens for a platform with no judgment drops, ~300 with
25a full ``top_dropped``; 40 platforms ≈ 4–12k tokens. ``top_dropped`` never
26lists ``dat_filter`` / ``region`` casualties.
27"""
29from __future__ import annotations
31import json
32import math
33from dataclasses import dataclass, field
34from typing import Any
36from romfarmer.ir.catalog import Catalog, PassTrace
38JUDGMENT_PASSES = ("rating", "budget", "curated_lists", "one_g_one_r", "arcade")
39TOP_DROPPED = 10
41# The correctness checks a summary performs. Listed in every PlanSummary so
42# "zero warnings" reads as "none of THESE fired", never as "correct". Each has
43# a fixture in tests/driver/test_warnings.py — a check that cannot fire and a
44# check that never fires look identical otherwise.
45CHECKS: tuple[str, ...] = (
46 "chain-mismatch: resolved chain ≠ frontend's preferred chain for the platform",
47 "no-capability-entry: device profile silent on the platform (tier unknown, not assumed)",
48 "tier-x: platform is tier X on this device",
49 "tier-c: platform is tier C — only playable_list titles should ship",
50 "dat-missing: a DAT was expected for the source but none was found",
51 "unrated-drop-thin: unrated=drop with rated_fraction < 50%",
52 "p90-family-factor: chain has no telemetry; p90 is a family factor",
53 "p90-over-platform-budget: platform p90 exceeds its own max_bytes (informational)",
54 "over-capacity: aggregate p90 (or p50 when unknown) exceeds storage − reserve",
55 "budget-over-policy: budget removed more than stated policy did and allocation_note is empty",
56)
58# p90/p50 spread by chain family when a chain has a prior but no telemetry.
59# Deliberately wide for unmeasured families; measured ones come from
60# unit_telemetry quantiles (2026-09-03: 7z p90/p50 ≈ 1.08 on nes/megadrive,
61# chd ≈ 1.19 on psx). A null p90 would silently drop the card's binding
62# constraint back to p50 — cold run #2 had to do this arithmetic by hand.
63FAMILY_P90_FACTOR: dict[str, float] = {
64 "passthrough": 1.0,
65 "zip": 1.03,
66 "7z": 1.10,
67 "chd": 1.25,
68 "cue_bin": 1.0,
69 "iso": 1.0,
70 "rvz": 1.0,
71 "wux": 1.0,
72 "xiso": 1.8, # xbox n=4: p90/p50 ≈ 1.6 and the spread is 4× — wide on purpose
73 "squashfs": 1.8,
74 "ps3": 1.2,
75}
78@dataclass(frozen=True)
79class PlatformSummary:
80 platform: str
81 chain: tuple[str, ...]
82 tier: str | None
83 quality: float | None
84 units_in: int
85 units_out: int
86 bytes_src: int
87 bytes_est_p50: int
88 bytes_est_p90: int | None
89 p90_ratio: (
90 float | None
91 ) # bytes_est_p90 / bytes_est_p50 — scale max_bytes by 1/this to fit at p90
92 p90_source: str # "telemetry" | "exact" | "family-factor" | "unknown"
93 prediction: str # CostModel label, e.g. "merged:prior:measured=0.83,telemetry=0.828,n=24"
94 rated_fraction: float
95 rating_quantiles: dict[str, float] # p10 p25 p50 p75 p90 over the catalog entering budget
96 bytes_kept_at_rating: dict[str, int] # threshold → p50 bytes a rating.min of that value keeps
97 heaviest: tuple[
98 dict[str, Any], ...
99 ] # ≤10 largest units entering budget: name, bytes_p50, rating
100 removed_by_pass: dict[str, int]
101 top_dropped: tuple[dict[str, str], ...]
102 notes: tuple[str, ...] = ()
103 warnings: tuple[str, ...] = ()
105 def to_dict(self, detail: bool = True) -> dict[str, Any]:
106 """``detail=False`` drops the per-unit lists (heaviest, top_dropped,
107 bytes_kept_at_rating) — ~2 KB/platform → ~300 B — for platforms the
108 agent is not actively tuning."""
109 d: dict[str, Any] = {
110 "platform": self.platform,
111 "chain": list(self.chain),
112 "tier": self.tier,
113 "quality": self.quality,
114 "units_in": self.units_in,
115 "units_out": self.units_out,
116 "bytes_src": self.bytes_src,
117 "bytes_est_p50": self.bytes_est_p50,
118 "bytes_est_p90": self.bytes_est_p90,
119 "p90_ratio": (round(self.p90_ratio, 4) if self.p90_ratio is not None else None),
120 "p90_source": self.p90_source,
121 "prediction": self.prediction,
122 "rated_fraction": round(self.rated_fraction, 3),
123 "rating_quantiles": {k: round(v, 3) for k, v in self.rating_quantiles.items()},
124 "removed_by_pass": {k: v for k, v in self.removed_by_pass.items() if v},
125 }
126 if detail:
127 d["bytes_kept_at_rating"] = self.bytes_kept_at_rating
128 d["heaviest"] = list(self.heaviest)
129 if self.top_dropped:
130 d["top_dropped"] = list(self.top_dropped)
131 else:
132 d["detail"] = "omitted — request with dry_run(detail=[platform])"
133 if self.notes:
134 d["notes"] = list(self.notes)
135 if self.warnings:
136 d["warnings"] = list(self.warnings)
137 return d
140@dataclass(frozen=True)
141class PlanSummary:
142 spec_hash: str
143 platforms: tuple[PlatformSummary, ...]
144 storage_bytes: int | None
145 reserve_bytes: int | None
146 bytes_total_p50: int
147 bytes_total_p90: (
148 int | None
149 ) # aggregate: p50 + sqrt(Σ (p90_i − p50_i)²) — errors decorrelate across platforms
150 headroom_p50: int | None # usable − p50 (negative = over)
151 headroom_p90: int | None # THE constraint: fits iff headroom_p90 ≥ 0 (p50 when p90 unknown)
152 fits: bool | None # None when storage is unknown
153 binding: str # "p90" | "p50 (no telemetry)" | "none (no storage_bytes)"
154 budget_trimmed_units: int
155 warnings: tuple[str, ...] = field(default_factory=tuple)
156 checks: tuple[str, ...] = CHECKS # what "zero warnings" means: none of THESE fired
158 def to_dict(self, detail: set[str] | None = None) -> dict[str, Any]:
159 """``detail``: platforms to expand (``None`` = all, ``set()`` = none)."""
160 return {
161 "spec_hash": self.spec_hash,
162 "storage_bytes": self.storage_bytes,
163 "reserve_bytes": self.reserve_bytes,
164 "bytes_total_p50": self.bytes_total_p50,
165 "bytes_total_p90": self.bytes_total_p90,
166 "headroom_p50": self.headroom_p50,
167 "headroom_p90": self.headroom_p90,
168 "fits": self.fits,
169 "binding": self.binding,
170 "budget_trimmed_units": self.budget_trimmed_units,
171 "warnings": list(self.warnings),
172 "platform_warnings": sum(len(p.warnings) for p in self.platforms),
173 "checks_performed": [c.split(":", 1)[0] for c in self.checks],
174 "platforms": [
175 p.to_dict(detail=(detail is None or p.platform in detail)) for p in self.platforms
176 ],
177 }
179 def to_json(self, detail: set[str] | None = None) -> str:
180 return json.dumps(self.to_dict(detail), separators=(",", ":"), ensure_ascii=False)
183# ---------------------------------------------------------------------------
184# RESOLVE-time correctness warnings (no catalog needed) — shared with validate_spec
185# ---------------------------------------------------------------------------
188def correctness_warnings(
189 platform: str,
190 chain: tuple[str, ...],
191 *,
192 tier: str | None,
193 preferred_chain: tuple[str, ...] | None,
194 resolve_notes: tuple[str, ...] = (),
195) -> tuple[str, ...]:
196 """Warnings derivable from RESOLVE alone.
198 Cold run #1 would have shown its whole failure on this list before its
199 first dry run.
200 """
201 out: list[str] = []
202 if tier is None:
203 out.append(
204 "no-capability-entry: device profile has no capability entry for this platform — "
205 "tier unknown, not assumed"
206 )
207 if preferred_chain and tuple(chain) != tuple(preferred_chain):
208 out.append(
209 f"chain-mismatch: chain {'→'.join(chain)} is not the frontend's preferred "
210 f"{'→'.join(preferred_chain)} — a self-consistent spec, but probably not the card you meant"
211 )
212 if tier == "X":
213 out.append("tier-x: tier X on this device — do not ship")
214 if tier == "C":
215 out.append("tier-c: tier C — only titles on the device's playable_list should ship")
216 for n in resolve_notes:
217 if n.startswith("DAT expected"):
218 out.append("dat-missing: " + n)
219 return tuple(out)
222# ---------------------------------------------------------------------------
223# Builders
224# ---------------------------------------------------------------------------
227def _quantiles(values: list[float]) -> dict[str, float]:
228 if not values:
229 return {}
230 vs = sorted(values)
231 n = len(vs)
233 def q(p: float) -> float:
234 return vs[min(n - 1, int(p * n))]
236 return {"p10": q(0.10), "p25": q(0.25), "p50": q(0.50), "p75": q(0.75), "p90": q(0.90)}
239def _short_reason(reason: str) -> str:
240 # "1g1r: 'X' region=[...] superseded by 'Y' ..." → keep it, but cap length
241 return reason if len(reason) <= 120 else reason[:117] + "…"
244def summarize_platform(
245 *,
246 platform: str,
247 chain: tuple[str, ...],
248 catalog_in: Catalog,
249 catalog_out: Catalog,
250 traces: tuple[PassTrace, ...],
251 stages: tuple[tuple[str, Catalog], ...],
252 cost_model: Any,
253 telemetry_quantiles: dict[str, float] | None,
254 tier: str | None = None,
255 quality: float | None = None,
256 unrated_rank: float | None = None,
257 max_bytes: int | None = None,
258 preferred_chain: tuple[str, ...] | None = None,
259 resolve_notes: tuple[str, ...] = (),
260) -> PlatformSummary:
261 """Summarise one platform's plan. Pure given its inputs.
263 ``unrated_rank`` is where the budget pass ranks unrated units (``None`` =
264 median of rated, the default policy); ``max_bytes`` the platform's own
265 budget, used only for the informational p90 flag.
266 """
267 tool = chain[0] if chain else None
268 bytes_src = sum(u.source_size for u in catalog_out.units)
270 try:
271 p50, label = cost_model.predict_output_bytes(bytes_src, platform, tool)
272 except Exception as exc:
273 p50, label = bytes_src, f"fallback:source_size ({exc})"
274 p90: int | None = None
275 p90_source = "unknown"
276 if tool == "passthrough":
277 p90, p90_source = int(p50), "exact" # bytes are copied as-is: no uncertainty
278 elif telemetry_quantiles and "p90" in telemetry_quantiles:
279 p90, p90_source = int(bytes_src * telemetry_quantiles["p90"]), "telemetry"
280 elif tool in FAMILY_P90_FACTOR:
281 p90, p90_source = int(p50 * FAMILY_P90_FACTOR[tool]), "family-factor"
282 p90_ratio = (p90 / p50) if (p90 is not None and p50) else None
284 # rating stats over the catalog ENTERING the budget pass
285 entering_budget = next((c for name, c in stages if name == "budget"), catalog_out)
286 rated = [u.rating for u in entering_budget.units if u.rating is not None]
287 rated_fraction = len(rated) / len(entering_budget.units) if entering_budget.units else 0.0
289 # bytes a given rating.min would keep (p50), with unrated ranked as the budget pass would —
290 # the agent solves for a threshold in one step, and the stated policy is the actual cause.
291 ratio_p50 = (p50 / bytes_src) if bytes_src else 1.0
292 median_rated = sorted(rated)[len(rated) // 2] if rated else 0.0
293 rank_unrated = median_rated if unrated_rank is None else unrated_rank
295 def _rank(u: Any) -> float:
296 return float(u.rating) if u.rating is not None else rank_unrated
298 per_unit = [
299 (_rank(u), int(u.source_size * ratio_p50), u.canonical_name, u.rating)
300 for u in entering_budget.units
301 ]
302 kept_at: dict[str, int] = {}
303 for th in (0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85):
304 kept_at[f"{th:.2f}"] = sum(b for r, b, _, _ in per_unit if r >= th - 1e-9)
305 heaviest = tuple(
306 {"name": n, "bytes_p50": b, "rating": (round(rt, 2) if rt is not None else None)}
307 for _, b, n, rt in sorted(per_unit, key=lambda t: -t[1])[:TOP_DROPPED]
308 )
310 removed_by_pass = {t.pass_name: len(t.removed) for t in traces}
311 names = {u.unit_id: u.canonical_name for u in catalog_in.units}
312 top: list[dict[str, str]] = []
313 for t in traces:
314 if t.pass_name not in JUDGMENT_PASSES:
315 continue
316 for uid, why in t.removed:
317 if len(top) >= TOP_DROPPED:
318 break
319 top.append(
320 {"name": names.get(uid, str(uid)), "pass": t.pass_name, "why": _short_reason(why)}
321 )
322 notes = tuple(resolve_notes) + tuple(n for t in traces for n in t.notes)
324 warnings: list[str] = list(
325 correctness_warnings(
326 platform,
327 tuple(chain),
328 tier=tier,
329 preferred_chain=preferred_chain,
330 resolve_notes=resolve_notes,
331 )
332 )
333 if rated_fraction < 0.5 and any("unrated=drop" in why for t in traces for _, why in t.removed):
334 warnings.append(
335 f"unrated-drop-thin: rated_fraction {rated_fraction:.0%} < 50% with unrated=drop"
336 )
337 if p90_source == "family-factor" and tool is not None:
338 warnings.append(
339 f"p90-family-factor: no telemetry for chain {tool!r} — p90 is a family factor "
340 f"({FAMILY_P90_FACTOR[tool]}×); a --test-sample build would replace it with a measurement"
341 )
342 elif p90 is None:
343 warnings.append(f"p90-unknown: chain {tool!r} has no prior and no telemetry")
344 if max_bytes is not None and p90 is not None and p90 > max_bytes:
345 warnings.append(
346 f"p90-over-platform-budget: p90 {p90:,} exceeds this platform's budget.max_bytes "
347 f"{max_bytes:,} (informational — the card binds on aggregate p90)"
348 )
350 return PlatformSummary(
351 platform=platform,
352 chain=tuple(chain),
353 tier=tier,
354 quality=quality,
355 units_in=len(catalog_in.units),
356 units_out=len(catalog_out.units),
357 bytes_src=bytes_src,
358 bytes_est_p50=int(p50),
359 bytes_est_p90=p90,
360 p90_ratio=p90_ratio,
361 p90_source=p90_source,
362 prediction=label,
363 rated_fraction=rated_fraction,
364 rating_quantiles=_quantiles([float(r) for r in rated]),
365 bytes_kept_at_rating=kept_at,
366 heaviest=heaviest,
367 removed_by_pass=removed_by_pass,
368 top_dropped=tuple(top),
369 notes=notes,
370 warnings=tuple(warnings),
371 )
374def summarize(
375 spec_hash: str,
376 platforms: list[PlatformSummary],
377 *,
378 storage_bytes: int | None,
379 reserve_bytes: int | None,
380 allocation_note: str = "",
381) -> PlanSummary:
382 total_p50 = sum(p.bytes_est_p50 for p in platforms)
383 # Aggregate p90: per-platform errors partly decorrelate, so summing per-platform p90s
384 # over-states the risk. Combine the (p90 − p50) spreads in quadrature.
385 spreads = [
386 (p.bytes_est_p90 - p.bytes_est_p50) for p in platforms if p.bytes_est_p90 is not None
387 ]
388 known = len(spreads) == len(platforms) and bool(platforms)
389 total_p90: int | None = (
390 int(total_p50 + math.sqrt(sum(d * d for d in spreads))) if known else None
391 )
392 usable = None if storage_bytes is None else storage_bytes - (reserve_bytes or 0)
393 warnings: list[str] = []
394 fits: bool | None
395 if usable is None:
396 fits, binding = None, "none (no storage_bytes)"
397 elif total_p90 is not None:
398 fits, binding = (
399 total_p90 <= usable,
400 "p90 (root-sum-square of per-platform spreads: independent sampling noise only — "
401 "a wrong measurement base moves every platform of a chain the same way and is "
402 "covered only by that chain's smoke build)",
403 )
404 if not fits:
405 warnings.append(
406 f"over-capacity: over usable capacity at p90 by {total_p90 - usable:,} bytes — reduce budget.max_bytes / tighten rating.min"
407 )
408 else:
409 fits, binding = total_p50 <= usable, "p50 (no telemetry for some chain)"
410 if not fits:
411 warnings.append(
412 f"over-capacity: over usable capacity at p50 by {total_p50 - usable:,} bytes"
413 )
414 else:
415 warnings.append(
416 "p90 unknown for at least one platform — fits at p50 only; sample builds would settle it"
417 )
418 trimmed = sum(p.removed_by_pass.get("budget", 0) for p in platforms)
419 stated = sum(
420 p.removed_by_pass.get("rating", 0) + p.removed_by_pass.get("curated_lists", 0)
421 for p in platforms
422 )
423 if trimmed > stated and not allocation_note.strip():
424 warnings.append(
425 f"budget-over-policy: the budget pass removed {trimmed} units, more than stated policy did ({stated}); if that is "
426 "deliberate, say so in intent.allocation_note so an absent game traces to a decision"
427 )
428 return PlanSummary(
429 spec_hash=spec_hash,
430 platforms=tuple(platforms),
431 storage_bytes=storage_bytes,
432 reserve_bytes=reserve_bytes,
433 bytes_total_p50=total_p50,
434 bytes_total_p90=total_p90,
435 headroom_p50=None if usable is None else usable - total_p50,
436 headroom_p90=None if (usable is None or total_p90 is None) else usable - total_p90,
437 fits=fits,
438 binding=binding,
439 budget_trimmed_units=trimmed,
440 warnings=tuple(warnings),
441 )